我使用JDBC通过java连接到SQLite数据库。
架构:
WorkInfo(id, job, salary)
Person(id, name)
下面的查询在我的数据库中运行正常,但是当我尝试使用JDBC时:
ResultSet rs = statement.executeQuery("select * from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("Person.id")); //column does not exist
System.out.println("name: " + rs.getString("name")); //works fine
输出:
如果使用person.id:no such column: 'person.id'
未指定:ambiguous column name 'id'
我尝试过使用WorkInfo和Person并使用别名,但它不断抛出相同的ambigious列名(如果保留为id)或列不存在。
答案 0 :(得分:3)
显式检索所需的列始终是一种很好的做法。我会将查询更改为:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id, person.name from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt(4));
System.out.println("name: " + rs.getString(5));
在这种情况下,您可以使用列索引而不是标签。
或使用AS
子句:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id as personId, person.name as personName "
+ "from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt("personId"));
System.out.println("name: " + rs.getString("personName"));
答案 1 :(得分:0)
您回来的ResultSet似乎包含以下列:
你有两个名为“id”的列(没有一个名为“Person.id”),所以当你试图获得它的'值'
只需在查询中指定所需的列并为其指定唯一的别名即可。例如:
ResultSet rs = statement.executeQuery("select Person.id AS 'personid', name from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("personid"));
System.out.println("name: " + rs.getString("name"));