prepareStatement设置参数,mysql数据出现中文‘?’的情景与解决方式
在prepareStatement中传入中文的参数,mysql数据库中出现“?”号
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/hejh", "root", "root");
String sql = "insert into user values(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setInt(1,4);
ps.setString(2, "hejh222");
ps.setString(3, "男");
int i = ps.executeUpdate();
System.out.println("插入了:"+i+"行数据");
} catch (Exception e) {
e.printStackTrace();
}
解决方式是在获取连接Connection对象时,追加设置字符编码为utf-8
try {
Class.forName("com.mysql.jdbc.Driver");
//prepareStatement插入的中文参数有可能会出现问号,可以在这里指定一下字符编码为utf-8
conn = DriverManager.getConnection("jdbc:mysql://localhost/hejh?useUnicode=true&characterEncoding=UTF-8", "root", "root");
String sql = "insert into user values(?,?,?)";
ps = conn.prepareStatement(sql);
ps.setInt(1,4);
ps.setString(2, "hejh222");
ps.setString(3, "男");
int i = ps.executeUpdate();
System.out.println("插入了:"+i+"行数据");
} catch (Exception e) {
e.printStackTrace();
}
至此,问题得以解决。