1. JDBC Powered Environment Create a new Java project—>Copy jdbc.jar to the project—> select jdbc.jar right-click the build path 2. Connect to the database to perform additions, deletions, modifications, and checks (1) // Set the driver type Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); (2) // Get a connection object conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433; database=userDB; ", "sa", "123"); (3) // Create an object to execute the command stmt = conn.createStatement(); (4) Implement additions, deletions, modifications, and checks 1) Adding, deleting, and modifying Execute SQL statements (add, delete, modify) stmt.executeUpdate(sql); 2) Inquiry
//执行查询sql语句 rs = stmt.executeQuery(sql); (5) Close all objects if(rs != null){ rs.close(); } if (stmt != null){ stmt.close(); } if (conn != null){ conn.close(); }
3. Use jdbc to manipulate transactions
//1开启事务 conn.setAutoCommit(false);
//2提交事务 conn.commit();
//3回滚事务 conn.rollback(); 4. Use the PreparedStatement question mark to pass the parameter String sql = "insert into userinfo values (?,?,?,?)"; Create an object to execute the command //stmt = conn.createStatement(); pstmt = conn.prepareStatement(sql); Set the value inside each question mark The first question mark pstmt.setInt(1, id); pstmt.setString(2, name); pstmt.setString(3, pwd); pstmt.setInt(4, balance); Execute SQL statements (add, delete, modify) //stmt.executeUpdate(sql); pstmt.executeUpdate();
|