如上圖, 向MySQL數據庫中插入中文內容時, 插入的信息變成了問號。
解決辦法如下:
1. 設置jsp頁面的編碼格式。
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%response.setCharacterEncoding("UTF-8");%>
我的項目中是這樣的:
<!--index.jsp作為程序中的主頁,用於放置添加圖書信息的表單。此表單提交到AddBook.jsp頁面處理-->
<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%response.setCharacterEncoding("UTF-8");%>
<form action="AddBook.jsp" method="post" onsubmit="return check(this);">
<h2>添加圖書信息</h2>
圖書名稱: <input type="text" name="title"><br>
圖書價格: <input type="text" name="price"><br>
圖書數量: <input type="text" name="amount"><br>
圖書作者: <input type="text" name="author">
<br>
<br>
<input align="right" type="submit" value="提交" name="submit">
</form>
2. 設置數據庫的編碼方式:
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%request.setCharacterEncoding("UTF-8");%>
我的項目中是這樣的:
<!--本AddBook.jsp頁面用於處理添加圖書信息的請求。此頁面通過JDBC所提交的圖書信息數據寫入數據庫中-->
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%request.setCharacterEncoding("UTF-8");%>
<jsp:useBean id="book" class="cth.Book"/>
<jsp:setProperty name="book" property="*"/>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
Connection connection = null;//Connection連接
Class.forName("com.mysql.jdbc.Driver");//加載數據驅動,注冊到驅動管理器
String url = "jdbc:mysql://localhost:3306/mysql?characterEncoding=utf-8";//數據庫連接字符串
String username = "Chintsai";//數據庫用戶名
String password = "1234";//數據庫密碼
connection = DriverManager.getConnection(url, username, password);
String sql = "insert into purchase_book(title,price,amount,author) values (?,?,?,?)";//添加圖書信息的SQL語句
PreparedStatement preparedStatement = null;//獲取PreparedStatement
try {
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, book.getTitle());//對SQL語句中的第1個參數賦值
preparedStatement.setDouble(2, book.getPrice());//對SQL語句中的第2個參數賦值
preparedStatement.setInt(3, book.getBookCount());//對SQL語句中的第3個參數賦值
preparedStatement.setString(4, book.getAuthor());//對SQL語句中的第4個參數賦值
int row = preparedStatement.executeUpdate();//執行更新操作,返回所影響的行數
if (row > 0)//判斷是否更新成功
out.println("成功添加了" + row + " 條信息");//更新成功輸出信息
} catch (Exception e) {
e.printStackTrace();
} finally {
try {//關閉PreparedStatement,釋放資源
if (preparedStatement != null)
preparedStatement.close();
preparedStatement = null;
} catch (Exception e) {
e.printStackTrace();
}
try {//關閉Connection,釋放資源
if (connection != null)
connection.close();
connection = null;
} catch (Exception e) {
e.printStackTrace();
}
}
%>
<br>
<a href="index.jsp">返回</a>
</body>
</html>
3. 設置JDBC連接的編碼方式:
即上圖中的那一行代碼:
String url = "jdbc:mysql://localhost:3306/mysql?characterEncoding=utf-8";//數據庫連接字符串
這一步很多人容易疏漏,因而產生亂碼,要特別注意喲 (^U^)ノ~YO
最后,貼上完整的項目代碼:Github