1. 程式人生 > >jsp中向資料庫中插入資料及中文亂碼問題

jsp中向資料庫中插入資料及中文亂碼問題

首先附上最剛開始的程式碼,功能是向資料庫中插入資料,資料庫中的屬性如下:

<%
	String action = request.getParameter("action");	//表單中提交過來的資料。
	if(action != null && action.equals("submit")) {	//如果進行提交,則進行資料插入
		String title = request.getParameter("title");
		String content = request.getParameter("content");	
		
		Class.forName("com.mysql.jdbc.Driver");		//載入及註冊jdbc驅動
		String url = "jdbc:mysql://localhost:3306/bbs?user=root&password=199288";
		Connection con = DriverManager.getConnection(url);
		
		con.setAutoCommit(false);		//設定不自動提交
		String psql = "insert into article values (null, 0, ?, ?, ?, now(), 0)";
		PreparedStatement pstmt = con.prepareStatement(psql, Statement.RETURN_GENERATED_KEYS);
		pstmt.setInt(1, -1);
		pstmt.setString(2, title);
		pstmt.setString(3, content);
		pstmt.executeUpdate();
		
		ResultSet rs = pstmt.getGeneratedKeys();
		rs.next();
		int id = rs.getInt(1);
		rs.close();
		
		Statement stmt = con.createStatement();
		String ssql = "update article set rootid =" + id + " where id =" + id;
		stmt.executeUpdate(ssql);
		
		con.commit();			//手動提交
		con.setAutoCommit(true);		//還原
		
		if(stmt != null) {
			stmt.close();
			stmt = null;
		}
		
		if(pstmt != null) {
			pstmt.close();
			pstmt = null;
		}
		
		if(con != null) {
			con.close();
			con = null;
		}
		
		response.sendRedirect("index.jsp");		
	}
 %>


執行時可以看到頁面展示出來的中文出現亂碼的情況,經過測試,該頁面所得到的資料位為亂碼,因此在首句插入以下程式碼:

request.setCharacterEncoding("utf-8");


然後中文顯示就恢復正常了。

ps:有的情況下,儘管修改了頁面的編碼,但是還是顯示亂碼,這是應該測試以下資料庫中是否亂碼,或者從資料庫中拿到的資料是否亂碼,依次判斷問題出在哪裡。然後進行對應的修改。