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:有的情况下,尽管修改了页面的编码,但是还是显示乱码,这是应该测试以下数据库中是否乱码,或者从数据库中拿到的数据是否乱码,依次判断问题出在哪里。然后进行对应的修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值