如何使用JSP向MySQL添加數據?以下是一些簡單的步驟:
第一步:建立數據庫連接
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
Connection conn = DriverManager.getConnection(url, "username", "password");
第二步:創建SQL語句
String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "user1");
ps.setString(2, "password1");
第三步:執行SQL語句
int result = ps.executeUpdate();
if (result >0) {
out.println("數據添加成功!");
}
第四步:關閉連接
ps.close();
conn.close();
完整的JSP代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%><%@ page import="java.sql.*" %><%
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
Connection conn = DriverManager.getConnection(url, "username", "password");
String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "user1");
ps.setString(2, "password1");
int result = ps.executeUpdate();
if (result >0) {
out.println("數據添加成功!");
}
ps.close();
conn.close();
%>