【发布时间】:2017-09-17 08:32:35
【问题描述】:
我想用这个类使 SQL 操作更容易,但是我得到一个异常,表明结果集是空的。相同的查询在 MySQL 工作台中工作。我不明白问题是什么。
import java.sql.*;
public class DataBase
{
private String user = "jsmith";
private String pass = "LetMeIn";
private String url = "jdbc:mysql://localhost:3306/java";
private String Schema, Table;
private Connection con;
private ResultSet Result;
private PreparedStatement pQuery;
public DataBase(String Database, String Table)
{
this.Schema = Database;
this.Table = Table;
}
private boolean createConnection()
{
boolean b = false;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, pass);
b = true;
} catch (Exception e) {
System.out.println("Connection Exception " + e.getMessage());
e.printStackTrace();
b = false;
}
return b;
}
public String getStringData(String Desireddata, String fromColumn, String condition)
{
boolean b = createConnection();
String retrivedString = "";
if (b != false && Schema != null && Table != null) {
try {
pQuery = con.prepareStatement("SELECT ? FROM " + Schema + "." + Table + " WHERE ? = ?");
pQuery.setString(1, Desireddata);
pQuery.setString(2, fromColumn);
pQuery.setString(3, condition);
Result = pQuery.executeQuery();
Result.next();
retrivedString = Result.getString(Desireddata);
} catch (Exception e) {
retrivedString = "False";
System.out.println(e.getMessage());
e.printStackTrace();
}
} else {
System.err.println("No Connection or Database not Defined ");
retrivedString = "False";
}
return retrivedString;
}
}
还有例外:
Illegal operation on empty result set.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:817)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5514)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5434)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5474)
at sync.DataBase.getStringData(DataBase.java:44)
...
【问题讨论】:
-
您不能对对象名称(表、列等)使用参数绑定,只能对值使用。