JSP技術可以輕易地將用戶的輸入信息存儲到后臺的MySQL數(shù)據(jù)庫中。下面是一個用于實現(xiàn)該功能的示例程序:
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
String url = "jdbc:mysql://localhost:3306/example";
String username = "root";
String password = "";
String driver = "com.mysql.jdbc.Driver";
Connection con = null;
PreparedStatement ps = null;
try {
// Load MYSQL driver
Class.forName(driver);
// Establish a connection
con = DriverManager.getConnection(url, username, password);
// Get input values from the user
String name = request.getParameter("name");
String phone = request.getParameter("phone");
String email = request.getParameter("email");
// Insert values into database
String query = "INSERT INTO customers (name, phone, email) VALUES (?, ?, ?)";
ps = con.prepareStatement(query);
ps.setString(1, name);
ps.setString(2, phone);
ps.setString(3, email);
ps.executeUpdate();
// Print success message
out.println("Record has been added successfully!");
} catch (Exception e) {
out.println(e.getMessage());
} finally {
try {
if (ps != null) {
ps.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
out.println(e.getMessage());
}
}
%>
在上述代碼中,我們首先導入了java.sql.*和java.io.*兩個包,然后建立了與mysql的鏈接,再獲取用戶輸入信息并實現(xiàn)將數(shù)據(jù)插入到數(shù)據(jù)庫中的操作,最后打印插入成功的消息。