自动增长(只有int型可以自动增长)

除了在数据库图形界面设置外:

玩转MySQL -----JDBC 的批处理_sql

还可以在java中用这句代码:st.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);

statement

//获取insert时生成的自动增长列如id
@Test //Statement
public void saveAutoIncrement1() throws Exception{
Connection con = ConnUtils.getConn();
String sql = "insert into book(name,price,birth) values('数据库原理',32.45,'2017-07-12 18:52:12')" ;
Statement st=con.createStatement();
st.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);
ResultSet rs=st.getGeneratedKeys();
if(rs.next()){
int id = rs.getInt(1); //第一个自动增长列的数据
System.out.println("自动增长列生成的id:"+id);
}

}

玩转MySQL -----JDBC 的批处理_System_02

prepareStatement

@Test //PreparedStatement
public void saveAutoIncrement2() throws Exception{
Connection con = ConnUtils.getConn();
String sql = "insert into book(name,price,birth) values(?,?,?)" ;
PreparedStatement pst=con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
pst.setString(1, "软件工程");
pst.setDouble(2, 33.58);

pst.setDate(3,new java.sql.Date( new java.util.Date().getTime() ));
//pst.setTime(3, new Time(19, 10, 20));
pst.executeUpdate();
ResultSet rs=pst.getGeneratedKeys();
while(rs.next()){
int id=rs.getInt(1);
System.out.println("自动增长列生成的id:"+id);
}
}

批处理

整个批处理只和MySQL数据库进行一次网络通讯。若不采用批处理,

则每条sql都要有一次通讯开销

statement:

st.addBatch(sql);//要传入sql语句

int a[]=st.executeBatch(); //返回值是每条sql语句影响的行数

@Test //Statement
public void batchDemo1() throws Exception{
Connection con = ConnUtils.getConn();
String sql_1 = "insert into book(name,price,birth) values('数据库原理";
String sql_2 = "',32.45,'2017-07-12 18:52:12')" ;
Statement st = con.createStatement();
for(int i=0;i<10;i++){
String sql = sql_1+ (i+1) + sql_2;
st.addBatch(sql);
}

String sql2 = "update book set price=price*1.1 where price<50";
st.addBatch(sql2);

//批处理的执行
int a[]=st.executeBatch(); //返回值是每条sql语句影响的行数

for(int k: a){
System.out.print(k+" ");
}
System.out.println();
}

玩转MySQL -----JDBC 的批处理_System_03

 

PreparedStatement:

pst.addBatch(); //注意,这里必须是空参,因为sql在pst内部封装着呢--它是活的,通过参数设置帮我们构造的sql

pst.addBatch(sql2); //通过pst也可以添加一条写死的sql

批处理的执行 int[] a = pst.executeBatch(); //返回值是每条sql语句影响的行数

@Test //PreparedStatement
public void batchDemo2() throws Exception{
Connection con = ConnUtils.getConn();
String sql = "insert into book(name,price) values(?,?)";
PreparedStatement pst = con.prepareStatement(sql);
for(int i=1;i<11;i++){
pst.setString(1, "Web开发"+i);
pst.setDouble(2, (22+i*3) );
pst.addBatch(); //注意,这里必须是空参,因为sql在pst内部封装着呢--它是活的,通过参数设置帮我们构造的sql
}
String sql2 = "update book set price=price*1.1 where price<50";
pst.addBatch(sql2); //通过pst也可以添加一条写死的sql


//批处理的执行
int[] a = pst.executeBatch(); //返回值是每条sql语句影响的行数

for(int k: a){
System.out.print(k+" ");
}
System.out.println();
}

玩转MySQL -----JDBC 的批处理_System_04