JSP是一種動(dòng)態(tài)網(wǎng)頁(yè)開(kāi)發(fā)技術(shù),結(jié)合MySQL數(shù)據(jù)庫(kù)可以實(shí)現(xiàn)網(wǎng)站數(shù)據(jù)的增刪改查功能。
在JSP中,可以使用JDBC連接MySQL數(shù)據(jù)庫(kù)進(jìn)行增刪改查操作。
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ page import="java.sql.*" %><%
String url="jdbc:mysql://localhost:3306/mydatabase";
String user="root";
String password="";
String driver="com.mysql.jdbc.Driver";
String name=request.getParameter("name");
String age=request.getParameter("age");
Connection con = null;
PreparedStatement ps = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
String sql_insert = "INSERT INTO student(name,age) VALUES (?,?)";
String sql_delete = "DELETE FROM student WHERE name=?";
String sql_update = "UPDATE student SET age=? WHERE name=?";
String sql_select = "SELECT * FROM student";
if(name!=null && age!=null) {
ps = con.prepareStatement(sql_insert);
ps.setString(1, name);
ps.setInt(2, Integer.parseInt(age));
ps.executeUpdate();
}
if(name!=null) {
ps = con.prepareStatement(sql_delete);
ps.setString(1, name);
ps.executeUpdate();
}
if(name!=null && age!=null) {
ps = con.prepareStatement(sql_update);
ps.setInt(1, Integer.parseInt(age));
ps.setString(2, name);
ps.executeUpdate();
}
ps = con.prepareStatement(sql_select);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
out.write(rs.getString("name") + " " + rs.getString("age") + "<br>");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
上述代碼使用PreparedStatement實(shí)現(xiàn)了數(shù)據(jù)的增刪改查功能。其中,輸入的參數(shù)通過(guò)request.getParameter方法獲取,結(jié)合SQL語(yǔ)句進(jìn)行操作。在JSP中,通過(guò)out.write方法將結(jié)果輸出到網(wǎng)頁(yè)中。