jdbc控制自動提交功能

不設限發表於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 TestAutoCommit {


public static void main(String[] args) throws Exception {
TestAutoCommit auto=new TestAutoCommit();
Connection conn=auto.getConn();
boolean commit=conn.getAutoCommit();
System.out.println("自動提交:  "+commit);

//關閉提交功能
conn.setAutoCommit(false);
System.out.println("自動提交: "+conn.getAutoCommit());
Statement stmt=conn.createStatement();
stmt.execute("insert into student(name,sex,grade) values('xxxxx','m','2008811237')");
stmt.execute("insert into student(name,sex,grade) values('yyyyy','f','2008811219')");
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));
}
// 提交事務
conn.commit();
System.out.println("-------------------------------------");
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));
}
//恢復原來的提交模式
conn.setAutoCommit(commit);
stmt.close();
}

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

相關文章