JDBC和mysql 加事務總結
阿新 • • 發佈:2020-12-07
技術標籤:工作
preparedstatement介面的操作步驟(防止SQL注入)
增刪改:ps.executeUpdate();
查詢:rs = ps.executeQuery();
以查詢為例
// 查詢語句
public static void select() {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
// 連線資料庫
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb?useSSL=false" ,"root","li19961102");
//開啟事務
con.setAutoCommit(false);
// 建立操作物件並執行SQL語句
ps = con.prepareStatement("select * from student where id=?");
ps.setInt(1, 1);
// 將查詢傳給給rs
rs = ps.executeQuery();
// 提交事務
con.commit();
while(rs.next()) {
int id = rs.getInt ("id");
String name = rs.getString("name");
Boolean gender = rs.getBoolean("gender");
Date birthday = rs.getDate("birthday");
System.out.println("編號 " + id + " 姓名 " + name + " 性別1為男 0為女 " + gender + " 生日為 " + birthday);
}
} catch (SQLException e) {
e.printStackTrace();
// 事務回滾
try {
con.rollback();
System.out.println("出現異常回滾事務");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}