jdbc batch

不設限發表於2011-12-11
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class TestBatch {
public static void main(String[] args) throws Exception {
TestBatch tb=new TestBatch();
Connection conn=tb.getConn();
conn.setAutoCommit(false);

Statement stmt=conn.createStatement();

                //將給定的 SQL 命令新增到此 Statement 物件的當前命令列表中。

stmt.addBatch("insert into student(name,sex,grade) values('yabing','m','2008811238')");
stmt.addBatch("insert into student(name,sex,grade) values('binge','m','2008811236')");
//stmt.addBatch("delete from student where name='dandan4'");
stmt.addBatch("delete from student where name='dandan4'");
stmt.executeBatch();
conn.commit();
ResultSet rs=stmt.executeQuery("select * from student");

while(rs.next()){
System.out.println("Row: "+rs.getRow()+"\tId: "+rs.getInt(1)+"\tName: "+rs.getString(2)
+"\tSex: "+rs.getString(3)+"\tGrade: "+rs.getString(4));
}

rs.close();
stmt.close();
conn.close();
}

public Connection getConn() {
Connection conn=null;
String url="jdbc:mysql://127.0.0.1/dandan?user=root&password=dada";
try {
Class.forName("org.gjt.mm.mysql.Driver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
try {
conn=DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

}

相關文章