![](/img/trans.png)
[英]I can't connect to a remote db using java in netbeans and apache server
[英]I can't read from DB using java netbeans
我有這段代碼,我遇到了一個問題,需要使用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()
嘗試使用rs.getString("Name")
代替rs.getNString("Name")
。
采用:
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"));
}
我100%確信這可行。 我從Namberi得到這個答案。
rs.getString("Name") instead of rs.getNString("Name")
if (rs.next()) {
rs.getString("Name");
}
rs.close();
stmt.close();
con.close();
是的,最好將PreparedStatement用於SQL注入和反斜杠,引號等的轉義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.