gpt4 book ai didi

不接受 Java JDBC 查询

转载 作者:太空宇宙 更新时间:2023-11-03 11:55:49 24 4
gpt4 key购买 nike

嘿,我正在制作一个小网络应用程序,其中有一个 java 文件,其中包含连接数据库和获取数据的功能。但是我得到了一个异常,任何人都知道为什么,因为如果我是对的,我的查询是有效的。

我使用 eclipse 和 mysql workbench。

功能:

import java.sql.*;

public class Functions {
public void dbConn(String nVal, String inpVal){

System.out.println("Running function...");

if(nVal != null || inpVal != null){
String sqlSerch;
if(nVal.equals("name")){
sqlSerch = "ID, aNaam FROM profiles WHERE naam = 'casper'";
}else{
sqlSerch = "naam, aNaam FROM profiles WHERE ID = " + inpVal;
}

//driver / db path
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/profile";
//DB user&password
final String USER = "root";
final String PASS = "";
//declare con & sql var
Connection conn = null;
Statement stmt = null;
//register jdbc driver
try{
Class.forName(JDBC_DRIVER);
//make a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//SQL Statement
stmt = conn.createStatement();
String sql = "SELECT "+ sqlSerch;
ResultSet rs = stmt.executeQuery(sql);

//Declareer variablen met data uit db
//int id = rs.getInt("ID");
String naam = rs.getString("naam");
String aNaam = rs.getString("aNaam");

System.out.println( naam + aNaam);


rs.close();
stmt.close();
conn.close();

}catch(Exception e){
System.out.println(e);
}


System.out.println(" - " + nVal + " - " + inpVal);


}
}
}

异常(exception):

java.sql.SQLException: Column 'naam' not found.

数据库结构:

enter image description here

提前谢谢你,

卡斯珀

最佳答案

当您通过 nVal 参数接收“名称”时,您仅选择 IDaNaam 列。

因此,如果您尝试从 ResultSet 获取 naam 的值,您将得到异常

此外,我建议将您的查询结果限制为 1,因为您将 WHERE 子句与 naamID 一起使用,这似乎不是唯一的,除非有屏幕截图中未包含某些约束。

希望这对您有所帮助。

关于不接受 Java JDBC 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762592/

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