我有这段代码,我遇到了使用 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()
最佳答案
用途:
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"));
}
关于java - 我无法使用 java netbeans 读取数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11510450/