JDBC进阶
PreparedStatement的使用:
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?" + "user=root&password=root"); pstmt = conn.prepareStatement("insert into dept values (?,?,?)"); pstmt.setInt(1,deptno); pstmt.setString(2,dname); pstmt.setString(3,loc); pstmt.executeUpdate();
transaction:
单词本身是交易的意思
在数据库中,保证语句要么同时执行成功,要么同时执行失败,典型例子银行转账
1 import java.sql.*; 2 public class TestJDBC { 3 4 public static void main(String[] args) { 5 Connection conn = null; 6 Statement stmt = null; 7 try { 8 Class.forName("oracle.jdbc.OracleDriver"); 9 conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl","scott","tigger"); 10 conn.setAutoCommit(false); 11 stmt = conn.createStatement(); 12 stmt.addBatch("insert into example values(12,'Game','BeiJing')"); 13 stmt.addBatch("insert into example values(13,'Game','BeiJing')"); 14 stmt.addBatch("insert into example values(14,'Game','BeiJing')"); 15 stmt.executeBatch(); 16 conn.commit(); 17 conn.setAutoCommit(true); 18 } catch (ClassNotFoundException e) { 19 e.printStackTrace(); 20 } catch (SQLException e) { 21 e.printStackTrace(); 22 if(conn != null) { 23 try { 24 conn.rollback();//一旦出错,要重新设置成自动执行 25 conn.setAutoCommit(true); 26 } catch (SQLException e1) { 27 e1.printStackTrace(); 28 } 29 } 30 } 31 try { 32 stmt.close(); 33 conn.close(); 34 } catch (SQLException e) { 35 e.printStackTrace(); 36 } 37 } 38 39 }