加载数据库固定代码:
Class.forName("com.mysql.jdbc.Driver");
String urlString = "jdbc:mysql://localhost:3306/lkkl?serverTimezone= GMT%2B8&useUnicode=true&characterEncoding=utf8";
String usernameString = "root";
String passwordString = "123456";
Connection connection = DriverManager.getConnection(urlString,
usernameString, passwordString);
使用Statement执行SQL语句:
Statement statement=connection.createStatement();
String sql="insert into bingli (zhanghao,bingli,yaopin,zhenduan,name) values(1,1,1,1,1)";
statement.execute();
使用Statement查询SQL语句(使用executeQuery):
使用Statement查询SQL语句(使用execute):
使用PreparedStatement执行SQL语句:
使用PreparedStatement执行SQL语句时,需要配合addBatch()函数和executeBatch()函数使用,才能使预处理发挥最大效率,其中,连接参数中需要加入rewriteBatched Statements=true
经数据测试,Statement插入数据时,若是自动提交,则所需时间随插入条数倍增。
当插入300条数据时,自动提交所需时间约为18秒,而手动提交平均只需要0.270秒。PrepareStatement的execute()方法继承自Statement,因此二者该方法的效率并无太大差距。但若使用PrepareStatement的addBatch()和executeBatch()方法,插入300条数据所需平均时间在0.100秒左右,使用该方法时,自动提交与手动提交所需时间相差不大。
当数据量为1000时,自动提交的Statement的execute()方法与PrepareStatement的addBatch()和executeBatch()方法平均效率相差在0.4 ~ 0.5秒内,(前者平均时间在0.5秒左右,后者在0.06 ~ 0.09秒左右)。当数据量在10000时,Statement所需平均时间在2.9 ~ 3.4秒内,PrepareStatement所需时间众数为0.25秒左右,平均时间在0.28 ~ 0.38秒内。
当数据量在十万时,Statement所需平均时间约为18秒,PrepareStatement所需时间在1.5~1.7秒之间