/*
* 练习批量操作数据库,比较方法一和方法二
*
* 方法二比方法一更优越
*
* */
import java.sql.*;
public class TestBatch {
public static void main(String[] args) {
String SQLUrl="jdbc:microsoft:sqlserver://192.168.1.23:1433;DatabaseName=Student";
String LoginName="sa";
String LoginPasswd="0";
Connection con=null;
Statement stmt=null;
PreparedStatement pstmt=null;
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con=DriverManager.getConnection(SQLUrl, LoginName, LoginPasswd);
//批量操作数据库: 方法一
stmt=con.createStatement();
stmt.addBatch("insert into UserLogin values('haha7','haha1')");
stmt.addBatch("insert into UserLogin values('haha8','haha2')");
stmt.addBatch("insert into UserLogin values('haha9','haha3')");
stmt.executeBatch();
stmt.close();
//批量操作数据库:方法二
pstmt=con.prepareStatement("insert into UserLogin values(?,?)");
pstmt.setString(1, "haha4");
pstmt.setString(2, "haha4");
pstmt.addBatch();
pstmt.setString(1, "haha5");
pstmt.setString(2, "haha5");
pstmt.addBatch();
pstmt.setString(1, "haha6");
pstmt.setString(2, "haha6");
pstmt.addBatch();
pstmt.executeBatch();
pstmt.close();
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}