执行多条SQL语句
String sqlSting1= "update user set username='赵六' where id=1" ;
String sqlSting2= "delete from user where id=4" ;
stSql. addBatch ( sqlSting1) ;
stSql. addBatch ( sqlSting2) ;
stSql. executeBatch ( ) ;
完整代码
package com. tyut. demo_jdbc ;
import java. sql. * ;
public class JDBCDemo {
private static ResultSet rs= null ;
private static Statement stSql = null ;
private static Connection conn= null ;
public static void main ( String [ ] args) throws SQLException , ClassNotFoundException {
try {
Class . forName ( "com.mysql.cj.jdbc.Driver" ) ;
String url= "jdbc:mysql://localhost:3306/test01?userSSL=false&serverTimezone=UTC" ;
String username= "root" ;
String userpwd= "123456" ;
conn= DriverManager . getConnection ( url, username, userpwd) ;
conn. setAutoCommit ( false ) ;
stSql= conn. createStatement ( ) ;
String sqlSting1= "update user set username='赵六' where id=1" ;
String sqlSting2= "delete from user where id=4" ;
stSql. addBatch ( sqlSting1) ;
stSql. addBatch ( sqlSting2) ;
stSql. executeBatch ( ) ;
conn. commit ( ) ;
System . out. println ( "成功" ) ;
} catch ( ClassNotFoundException e) {
e. printStackTrace ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
} finally {
if ( rs!= null )
rs. close ( ) ;
stSql. close ( ) ;
conn. close ( ) ;
}
}
}
结果
数据库