我在远程计算机(Ubuntu)上有一个MySQL数据库,我想通过本地计算机(Windows)访问。我知道这样做我GRANT
可以访问我的MySQL用户。
GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' IDENTIFIED BY 'password';
我正在使用JAVA JDBC来访问我的MySQL数据库。我能够执行INSERT
查询,但SELECT
查询返回一个空结果集。
public class MySqlConnector {
Connection db;
String user = null;
String password = null;
String dbName = null;
String componentsTable;
public MySqlConnector(){
this.user = "user"; // MySQL Userid
this.password = "password"; // MySQL Password
this.dbName = "database"; // Database Name
}
public MySqlConnector(String dbName, String user, String password){
if(dbName != null){
this.dbName = dbName;
}
if(user != null){
this.user = user;
}
if(password != null){
this.password = password;
}
}
public Connection getConnection(){
try {
// JDBC Driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println(dbName + " " + user + " " + password);
db = DriverManager.getConnection("jdbc:mysql://IPADDRESS:PORT/"+dbName,user,password);
System.out.println("Connect Established");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return db;
}
public void insertQuery(String query){
Statement statement = null;
try {
statement = (Statement)db.createStatement();
statement.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet executeQuery(String query){
Statement statement= null;
ResultSet resultset= null;
try {
statement = (Statement) db.createStatement();
statement.executeQuery(query);
resultset = statement.getResultSet ();
} catch (SQLException e) {
e.printStackTrace();
}
return resultset;
}
public void closeConnection() throws SQLException{
db.close();
}
}
在我查询时的servlet中
MySqlConnector mysql = new MySqlConnector();
mysql.getConnection();
mysql.insertQuery("INSERT INTO table_name VALUES(10)");
mysql.closeConnection();
工作得很漂亮。但是,executeQuery返回空。
MySqlConnector mysql = new MySqlConnector();
mysql.getConnection();
ResultSet result = mysql.executeQuery("SELECT * FROM table_name");
mysql.closeConnection();
我错过了什么建议或任何建议?
答案 0 :(得分:0)
该错误出现在代码的其他部分,此处未列出。有两件事出了问题 -
NullPointerException
ResultSet
读取特定列时,我写了错误的列名,因此收到了非法访问权。感谢大家查看我的问题并撰写答案/评论。
答案 1 :(得分:-2)
我认为Resultset
查询必须是:
Resultset result = mysql.executeQuery("SELECT * FROM table_name");