package com.a_jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* jdbc复习
*/
public class Day5month8 {
public static void main(String[] args) {
test1();
}
private static void test1() {
// TODO Auto-generated method stub
//1.获取连接
Connection conn= JdbcUtil.getConnection();
PreparedStatement pstm = null;
//2.sql语句
String sql = "insert into stu values('胡一天','123')";
try {
//3.获取预编译操作句柄
pstm = conn.prepareStatement(sql);
pstm.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JdbcUtil.close(conn, pstm, null);
}
}
}
以上为一个简单的增加操作
下面这个是普通添加2000千条数据‘
private static void test4() {
// TODO Auto-generated method stub
Connection conn = JdbcUtil.getConnection();
String sql = "insert into stu values(?,'123') ";
PreparedStatement pstm =null;
try {
pstm = conn.prepareStatement(sql);
for(int i=0;i<2000;i++) {
pstm.setString(1, "张三"+i);
pstm.executeUpdate();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JdbcUtil.close(conn, pstm, null);
}
}
jdbc批量操作三个方法:
Addbatch() 把sql或者参数添加到缓存区中
ExecuteBatch() 把缓存区中的sql或者参数发送给数据库并执行
ClearBatch() 清空缓存区中的内容
private static void batchTest2() {
// TODO Auto-generated method stub
Connection conn = JdbcUtil.getConnection();
String sql = "insert into stu values(?,'123') ";
PreparedStatement pstm =null;
try {
pstm = conn.prepareStatement(sql);
for(int i=1;i<=2000;i++) {
pstm.setString(1, "张三"+i);
//把sql添加到缓存中
pstm.addBatch();
//每20条发送一次数据
if(i%20==0) {
int[] row = pstm.executeBatch();
}
//清空缓存区
pstm.clearBatch();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JdbcUtil.close(conn, pstm, null);
}
}