很多的朋友在写JDBC的是时候,遇见了因为在SQL语句中含有中文无法运行的情况,今天给大家解决下这个问题,下面把代码展示一下:
package oop.hu.ytu.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import oop.hg.ytu.beans.LoginBean;
import oop.hg.ytu.utils.JdbcUtils;
/**
* 处理用户登录请求
* @author Administrator
*
*/
public class LoginDomain {
public LoginBean select(String tableName,String username){
Connection con = null;
PreparedStatement pt = null;
ResultSet rs = null;
LoginBean bean = new LoginBean();
try {
username = "\""+username+"\"";
con = JdbcUtils.getConnection();
String sql = "select name,password from "+tableName+" where name="+username+"";
pt = con.prepareStatement(sql);
// pt.setString(1, tableName);
// pt.setString(2, u);
rs = pt.executeQuery();
while(rs.next()){
bean.setUsername(rs.getString("name"));
bean.setPassword(rs.getString("password"));
}
} catch (Exception e) {
throw new RuntimeException(e);
}finally{
JdbcUtils.free(rs, pt, con);
}
return bean;
}
}
username = "\""+username+"\"";这句话是进行字符串处理,加上双引号。String sql = "select name,password from "+tableName+" where name="+username+"";
这句话是重点,一定不能使用PreparedStatement提供的字符串处理方法,一定要直接自己拼接出字符串来运行,这样对于中文的处理就没问题了;
大家赶紧试一试吧!