JDBC连接
JDBC连接一般需要以下步骤:
1 加载驱动
Class.forName("com.mysql.jdbc.Driver");
1
2 获取连接对象
Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/homeworksubmit?user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
1
2
3 创建命令对象
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
1
2
3
4 执行sql语句
Result rs=stmt.executeQuery(sql);
PreparedStatement
public interface PreparedStatement extends Statement;可以看到PreparedStatement是Statement的子接口,我们在执行查询或者更新数据表数据的时候,拼写SQL语句是一个很费力并且容易出错的事情,PreparedStatement可以简化这样的一个过程.
PreParedStatement
1).why?我们为什么要使用它
使用Statement需要进行拼写SQl语句,辛苦并且容易出错,之前使用Statement的SQL语句的形式是这样的
1
2
3
4
5
|
String sql = "insert into examstudent" + " values(" + student.getFlowId() + "," + student.getType() + ",'" + student.getIdCard() + "','" + student.getExamCard() + "','" + student.getStudentName() + "','" + student.getLocation() + "'," + student.getGrade() + ")" ; |
使用PreparedStatement:是Statement的子接口,可以传入带占位符的SQL语句,提供了补充占位符变量的方法
1
|
PreparedStatement ps=conn.preparedStatement(sql); |
可以看到将sql作为参数传入了,就不需要我们在费力拼写了。
2)变成了这样的形式
1
|
String sql= "insert into examstudent values(?,?,?,?,?,?,?)" ; |
可以调用PreparedStatement的setXxx(int index,Object val)设置占位符的值,其中index的值从1开始
执行SQl语句:excuteQuery()或者excuteUpdate()就可以完成查询或者数据的更新.【注意】:此时函数的参数位置不需要传入SQL语句,注意同使用Statement的update函数的差别
具体代码实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
@Test public void testPreparedStatement() { Connection connection = null ; PreparedStatement preparedStatement = null ; try { // 连接数据库 connection = JDBCTools.getConnection(); // 使用占位符的SQl语句 String sql = "insert into customers(name,email,birth)" + "values(?,?,?)" ; // 使用preparedStatement的setXxx方法设置每一个位置上的值 preparedStatement = connection.prepareStatement(sql); // 设置name字段 preparedStatement.setString( 1 , "ATGUIGU" ); // 设置email字段 preparedStatement.setString( 2 , "simale@163.com" ); // 设置birth字段 preparedStatement.setDate( 3 , new Date( new java.util.Date().getTime())); // 执行更新操作 preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { // 释放资源 JDBCTools.release( null , preparedStatement, connection); } } |
使用PreparedStatement执行SQl(更新操作:插入、删除、更新,但不包括select查询操作),JDBCTools中的通用函数update更改成下面的形式:这里使用了可变参数,而不是使用数组
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public static void update(String sql,Object ...args){ /** * 执行SQL语句,使用PreparedStatement */ Connection connection= null ; PreparedStatement preparedStatement= null ; try { connection=JDBCTools.getConnection(); preparedStatement=connection.prepareStatement(sql); for ( int i= 0 ;i<args.length;i++){ preparedStatement.setObject(i+ 1 , args[i]); } preparedStatement.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { JDBCTools.release( null , preparedStatement, connection); } } |
————————————————
版权声明:本文为CSDN博主「sushauai」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sushauai/article/details/50879704