Reputation: 11
I have this code and I faced a problem to read information from MySQL database using java netbeans, data type inside database 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());
}
}
}
Error:Can not call getNString() when field's charset isn't UTF-8
Upvotes: 0
Views: 6547
Reputation: 159844
Use:
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();
Also don't forget to comment in
if (rs.next()) {
System.out.print("Name: " + rs.getNString("Name"));
System.out.print("Number: " + rs.getNString("Number"));
}
Upvotes: 2
Reputation: 2817
I am 100% sure this works. This answer I got from Namberi.
rs.getString("Name") instead of rs.getNString("Name")
Upvotes: 1
Reputation: 109597
if (rs.next()) {
rs.getString("Name");
}
rs.close();
stmt.close();
con.close();
And yes, better use a PreparedStatement for SQL injection and escaping of backslash, quote and such.
Upvotes: 0