//(1)导入jar并加载驱动
Class.forName("com.mysql.jdbc.Driver");
//(2)获取连接
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","root");
(3)调用存储过程---PrepareStatement,Statement
CallableStatement callableStatement=connection.prepareCall("CALL selectUser()");//预编译sql语句
(1)通过execute执行
callableStatement.execute();
//获取结果集
ResultSet resultSet=callableStatement.getResultSet();
//(2)通过executeQuery执行
//取得结果集的每一行数据
ResultSet resultSet = callableStatement.executeQuery();
当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。
优缺点:
缺点:Statement,没有预编译
优点:能批处理不同Sql语句
package com.bdjg.test02;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class TestMain2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Long startTime=System.currentTimeMillis();
//(1)导入jar并加载驱动
Class.forName("com.mysql.jdbc.Driver");
//(2)获取连接
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","root");
//(3)四句语句,增加数据,修改数据,删除数据
String sql1="insert into user values(null,‘admin‘,‘123456‘)";
String sql2="update user set uname=‘ADMIN‘ where uname=‘admin‘";
String sql3="insert into user values(null,‘admin2‘,‘123456‘)";
String sql4="delete from user where uname=‘zhangsan‘";
//(4)获取Statement
Statement statement=connection.createStatement();
//(5)批处理去执行
statement.addBatch(sql1);
statement.addBatch(sql2);
statement.addBatch(sql3);
statement.addBatch(sql4);
//执行
statement.executeBatch();
//清除批处理操作
statement.clearBatch();
Long endTime=System.currentTimeMillis();
System.out.println("执行时间:"+(endTime-startTime));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
优缺点:
缺点:只能批处理同一种sql语句
优点:预编译
package com.bdjg.test02;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class TestMain3 {
//使用PrepareStatement实现批处理
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Long startTime=System.currentTimeMillis();
//(1)导入jar并加载驱动
Class.forName("com.mysql.jdbc.Driver");
//(2)获取连接
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest","root","root");
//(3)四句语句,增加数据,修改数据,删除数据
String sql="insert into user values(null,?,?)";
//(4)获取Statement
PreparedStatement preparedStatement=connection.prepareStatement(sql);
//(5)插入100条数据
for(int i=1;i<100;i++){//100遍循环,每次循环设置参数
preparedStatement.setObject(1, "admin"+i);
preparedStatement.setObject(2,"admin"+i);
preparedStatement.addBatch();//添加
preparedStatement.clearBatch();//清除批处理
}
preparedStatement.executeBatch();//执行批处理
Long endTime=System.currentTimeMillis();//获取当前毫秒数
System.out.println("执行时间:"+(endTime-startTime));//获得当前的时间
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
原文:https://www.cnblogs.com/daxixixy/p/14743466.html