注册 登录
编程论坛 JAVA论坛

从键盘键入String类型的数据插入数据库中,为什么乱码?

南山南 发布于 2019-10-21 09:31, 3222 次点击
输入中文就乱码,eclipse默认编码格式是utf-8,数据库也是utf-8
这是代码
程序代码:

//从这里输入数据
    Date time = new Date(System.currentTimeMillis());
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date = sdf.format(time);
    String project = Input.getProject(s);
    String in_money = Input.getIn_money(s);
    String out_money = Input.getOut_money(s);
    Account a = new Account();
    a.setDate(date);
    a.setProject(project);
    a.setIn_money(in_money);
    a.setOut_money(out_money);
    Account account = new Account(date, project, in_money, out_money);
    account.printAccountInfo();
    boolean confirm = Input.getConfirm(s);
    if (confirm) {
        accountOperation.insertAccount(account);
    }
//把数据插入数据库中
public void insert_DB(Account account) throws ClassNotFoundException, SQLException {
        // 获得连接
        Connection conn = JDBCUtil.getConnection();
        // 发送语句
        String sql = "insert into account(date,project,in_money,out_money) value(?,?,?,?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, account.getDate());
        pstmt.setString(2, account.getProject());
        pstmt.setString(3, account.getIn_money());
        pstmt.setString(4, account.getOut_money());
        pstmt.executeUpdate();
        //System.out.println(account.getProject());
        
// 关闭连接
        JDBCUtil.closeResource(pstmt, conn);
    }

9 回复
#2
林月儿2019-10-21 09:42
查查数据库的字符编码
show variables like '%char%'好像是这个命令
#3
南山南2019-10-21 19:46
回复 2楼 林月儿
是utf-8啊,还是乱码
只有本站会员才能查看附件,请 登录
#4
林月儿2019-10-22 09:04
查查表和表字段的编码呢?
show create table account
#5
林月儿2019-10-22 09:05
你有工具直接右击设计表看看设置吧,不用命令行了
#6
南山南2019-10-22 10:22
回复 5楼 林月儿
是这个
ENGINE=InnoDB DEFAULT CHARSET=utf8;
#7
林月儿2019-10-22 14:40
字段的呢?下游看不出问题再看上有,打印输入内容看回显是否有问题。
#8
南山南2019-10-22 19:17
回复 7楼 林月儿
已解决,谢谢
我在连接数据库语句的URL后加上了 &characterEncoding=UTF-8
#9
林月儿2019-10-22 20:04
嗯,不客气
1