When I was writing JDBC, I met the problem that the SQL statement cannot run because it contains Chinese characters. So I put this sentence in the mysql client for testing and the result passes, I guess it's not a matter of character encoding. It's because the PreparedStatement interface does something I don't know that causes this problem. And is generally used directly? The question mark replaces the dynamic query requirement and must be enclosed in double quotation marks on the client. So I tested it and wrote the SQL statement directly to run it. The result is OK, only two escape characters \ "are added \". Next I will send the code,
- PackageOop. hu. ytu. dao;
- ImportJava. SQL. Connection;
- ImportJava. SQL. PreparedStatement;
- ImportJava. SQL. ResultSet;
- ImportOop. hg. ytu. beans. LoginBean;
- ImportOop. hg. ytu. utils. JdbcUtils;
- /**
- * Process user login requests
- * @ Author Administrator
- *
- */
- Public ClassLoginDomain {
- PublicLoginBean select (String tableName, String username ){
- Connection con =Null;
- PreparedStatement pt =Null;
- ResultSet rs =Null;
- LoginBean bean =NewLoginBean ();
- 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.exe cuteQuery ();
- While(Rs. next ()){
- Bean. setUsername (rs. getString ("Name"));
- Bean. setPassword (rs. getString ("Password"));
- }
- }Catch(Exception e ){
- Throw NewRuntimeException (e );
- }Finally{
- JdbcUtils. free (rs, pt, con );
- }
- ReturnBean;
- }
- }
Username ="\""+ Username +"\"".
String SQL ="Select name, password from"+ TableName +"Where name ="+ Username +"";
This sentence is important. You must not use the string processing method provided by PreparedStatement. You must splice the string directly to run the statement. In this way, the processing of Chinese characters will be okay. This is a tangle of me. It took a sigh of relief!