sql语句中含有中文时执行报错
public Goods getByName(Connection connection, String name) {
Goods goods = new Goods();
String sql = "SELECT * FROM goods WHERE NAME=?";
try {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
int number = resultSet.getInt("number");
int price = resultSet.getInt("price");
String image = resultSet.getString("image");
goods = new Goods(id, name, number, price, image);
}
System.out.println(goods.toString());
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return goods;
}
以上例子中sql语句中包含中文,无法正常执行,resultSet为空。
解决:
在连接数据库时设置编码即可
String url = "jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8";
|