gpt4 book ai didi

Java SQL 问题

转载 作者:行者123 更新时间:2023-11-29 05:33:04 27 4
gpt4 key购买 nike

我在 java 文件名 javaDAO 中收到如下代码的错误尝试从 jbutton 调用方法。在我的 javaDAO 文件 3 中定义了方法1.extablishConnection2.检索名称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)

javaDAO 文件中的代码是在 netbeans IDE 中由 JFrame.java 中的 main 方法调用的

  //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");

最佳答案

我相信您在使用 PreparedStatementResultSet 时感到困惑。在执行查询之前未设置 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

关于Java SQL 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20450770/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com