我在Java文件名javaDAO中收到以下代码错误
尝试从jbutton调用方法。在我的javaDAO文件3中的方法是定义
1. extablishConnection
2.检索名称
3.关闭连接
从.access文件获取用户名和密码时,出现以下错误
Dec 8, 2013 11:31:59 AM vuAssignment.JFrame jButton1ActionPerformed
SEVERE: null
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6957)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3149)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute
(JdbcOdbcPreparedStatement.java:216)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeQuery
(JdbcOdbcPreparedStatement.java:91)
at vuAssignment.javaDAO.retrieveName(javaDAO.java:33)
at vuAssignment.JFrame.jButton1ActionPerformed(JFrame.java:139)
NetBeans IDE中JFrame.java中的main方法调用javaDAO文件中的代码
//method to establish connection
private void establishConnection() throws ClassNotFoundException,SQLException{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:ProductDb";
Class.forName(driver);
con = DriverManager.getConnection(url);
}
// method to call query
public void retrieveName(String pName,String pWord) throws
ClassNotFoundException,SQLException{
String user1= "";
String pass1 = "";
String sql = "SELECT * FROM admin where userName= ? && password= ?";
PreparedStatement stmt = con.prepareStatement(sql);
ResultSet res = stmt.executeQuery();
while (res.next()) {
user1 = res.getString("userName");
pass1 = res.getString("password");
}
if (pName.equals(user1) && pWord.equals(pass1))
JOptionPane.showMessageDialog(null,"correct");
else
JOptionPane.showMessageDialog(null,"incorrect");
最佳答案
我相信您对使用PreparedStatement
和ResultSet
感到困惑。在执行查询之前未设置SQL查询参数。您需要设置用户名和密码,例如
String sql = "SELECT * FROM admin where userName= ? && password= ?";
PreparedStatement stmt = con.prepareStatement(sql);
//you need the set the parameters
stmt.setString(1,userName);
stmt.setString(2,password);
//the result set will contain the column values of your query
ResultSet res = stmt.executeQuery();
while (res.next()) {
//to get the value of the first col
user1 = res.getString(column1_name);
//to get the value of the second col
pass1 = res.getString(column2_name);
}
希望对您有所帮助,请阅读PreparedStatement和ResultSet的文档