shenzhinishimeng
shenzhinishimeng
2016-04-13 08:15

JSP中将数据存入数据库的时候乱码

5
  • java
  • 数据库

JSP中将数据存入数据库的时候乱码。将网页的编码方式用GB2312或者UTF-8都是乱码图片说明图片说明图片说明
用的是JDBC的连接方式连接的数据库。具体的代码如下
第一页gengxin.jsp
<%@ page language="java" contentType="text/html; charset=GB2312"
pageEncoding="GB2312"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
request.setCharacterEncoding("GB2312");
%>



添加商品信息



添加新商品信息



商品编号:

商品类别:

商品名称:

商品价格:

商品数量:







第二页 转码的
<%!public String Bytes(String str) {
    try {

        String strOld = str;
        byte[] strNew = strOld.getBytes("GB2312");
        String bytes = new String(strNew);
        return bytes;
    } catch (Exception e) {
    }
    return null;
}%>
第三页
<%@ page language="java" contentType="text/html; charset=GB2312"
pageEncoding="GB2312"%>

<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
request.setCharacterEncoding("GB2312");
%>


成功添加新商品信息


<%@ include file="convert.jsp"%>
<%
Connection conn = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String strConn = "jdbc:sqlserver://localhost:1433;DatabaseName=lianxi";
String strUser = "sa";
String strPassword = "123456";
conn = DriverManager.getConnection(strConn, strUser, strPassword);
Statement stmt = conn.createStatement();
String p_id = Bytes(request.getParameter("p_id"));
String p_type = Bytes(request.getParameter("p_type"));
String p_name = Bytes(request.getParameter("p_name"));
float p_price = Float.parseFloat(request.getParameter("p_price"));
int p_quantity = Integer.parseInt(request.getParameter("p_quantity"));
out.print("p_id的值" + p_id + "
");
out.print("p_type的值" + p_type + "
");
out.print("p_name的值" + p_name + "
");
out.print("p_price的值" + p_price + "
");
out.print("p_quantity的值" + p_quantity + "
");
        String strSql = "INSERT INTO product values('" + p_id + "','" + p_type + "','" + p_name + "','"
                + p_price + "','" + p_quantity + "')";
        //String strSql = "insert into product(p_id,p_type,p_name,p_price,p_quantity)values(?,?,?,?,?)";
        int intTemp = stmt.executeUpdate(strSql);
        if (intTemp != 0) {
            out.println("<font size=4pt color='red'>" + "商品添加成功!" + "</font>");
        } else {
            out.println("<font size=4pt color='red'>" + "商品添加失败!" + "</font>");
        }

    } catch (Exception e) {
        out.println(e.toString());
    }
%>


  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐

换一换