0

我有这段代码,我遇到了一个问题,使用 java netbeans 从 MySQL 数据库读取信息,数据库 varchar 中的数据类型

import com.mysql.jdbc.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Scanner;

public class NewDataBase {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        try{
              Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root", "password");
              Statement stmt = (Statement) con.createStatement();
              System.out.println("Enter name");
              String name =sc.next();
              String SQL = "select * from list where Name ='"+ name + "'";
              ResultSet rs = stmt.executeQuery(SQL);
              System.out.print("Name: " + rs.getNString("Name"));
              System.out.print("Number: " + rs.getNString("Number"));
              // while(rs.next())
              // {
              //   System.out.print("Name: " + rs.getNString("Name"));
              //  System.out.print("Number: " + rs.getNString("Number"));

              //}
        }catch(Exception e){
            System.out.print("Error:" + e.getMessage());
        } 
    }
}

错误:当字段的字符集不是 UTF-8 时,无法调用 getNString()

4

4 回答 4

2

尝试 rs.getString("Name")代替 rs.getNString("Name").

于 2012-07-16T18:39:48.783 回答
1

采用:

    Properties props = new Properties(); 
    props.put("user", "root");         
    props.put("password", "password");
    props.put("useUnicode", "true");
    props.put("useServerPrepStmts", "false"); // use client-side prepared statement
    props.put("characterEncoding", "UTF-8"); // ensure charset is utf8 here

    String url = "jdbc:mysql://localhost/mydb";
    Connection connection = DriverManager.getConnection(url, props);

    PreparedStatement ps = 
        connection.prepareStatement("INSERT INTO list (Name, Number) VALUES (?, ?)");

    String testNumber = "12345";
    String testName = "name1";
    pstmt1.setNCharacterStream(1, new StringReader(testName), testName.length());
    ps.setNCharacterStream(2, new StringReader(testNumber), testNumber.length());
    ps.execute();

也不要忘记评论

if (rs.next()) {
    System.out.print("Name: " + rs.getNString("Name"));
    System.out.print("Number: " + rs.getNString("Number"));
}
于 2012-07-16T19:02:13.833 回答
1

我 100% 确定这可行。这是我从 Namberi 那里得到的答案。

rs.getString("Name") instead of rs.getNString("Name")
于 2014-11-08T20:16:55.567 回答
0
if (rs.next()) {
    rs.getString("Name");
}
rs.close();
stmt.close();
con.close();

是的,最好使用 PreparedStatement 进行 SQL 注入和转义反斜杠、引号等。

于 2012-07-16T20:24:06.283 回答