JSP(Java Server Pages)是一種基于Java語言的服務器端頁面開發(fā)技術,可用于構建動態(tài)Web頁面。而MySQL則是一種流行的關系型數(shù)據(jù)庫。在JSP開發(fā)過程中,我們經(jīng)常需要對MySQL數(shù)據(jù)庫進行增刪改查操作。
示例代碼如下:
//建立數(shù)據(jù)庫連接
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
//增加操作
String addSql = "insert into user(name, age) values(?, ?)";
pstmt = conn.prepareStatement(addSql);
pstmt.setString(1, "Tom");
pstmt.setInt(2, 25);
pstmt.executeUpdate();
//修改操作
String updateSql = "update user set age=? where name=?";
pstmt = conn.prepareStatement(updateSql);
pstmt.setInt(1, 30);
pstmt.setString(2, "Tom");
pstmt.executeUpdate();
//查詢操作
String querySql = "select * from user where name=?";
pstmt = conn.prepareStatement(querySql);
pstmt.setString(1, "Tom");
rs = pstmt.executeQuery();
while(rs.next()){
String name = rs.getString("name");
int age = rs.getInt("age");
}
//刪除操作
String deleteSql = "delete from user where name=?";
pstmt = conn.prepareStatement(deleteSql);
pstmt.setString(1, "Tom");
pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null){
rs.close();
}
if(pstmt != null){
pstmt.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
在上述代碼中,首先通過JDBC API調用相關方法建立數(shù)據(jù)庫連接,接著采用PreparedStatement來預編譯SQL語句并執(zhí)行。通過setXXX()方法設置參數(shù)的值,最后調用executeUpdate()方法來執(zhí)行增刪改操作或者調用executeQuery()方法來執(zhí)行查詢操作。
通過JDBC API對MySQL數(shù)據(jù)庫進行增刪改查是JSP開發(fā)中經(jīng)常用到的操作,對于開發(fā)者來說掌握這些操作能夠使工作更加高效。