简体   繁体   中英

JDBC getString() from the column of foreign key

I use mysql and jdbc to get table2Id.column in table1. table2Id is a foreign key of table1. And i use rs.getString("table2Id.column") get the error.

dbc = new DBconnection();
conn = dbc.getConnection();
PreparedStatement pst = "SELECT * FROM `table1`";
pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
String value = rs.getString("table2Id.column")

How can I get the column of foreign key?

If you are getting unknown column error, try with,

String value = rs.getString("table2Id");

And Change PreparedStatement pst = "SELECT * FROM `` table1 `` "; to PreparedStatement pst = "SELECT * FROM table1";

You can not simply get table2 column with out specifying it in the query.

You need to add your column to query.

SELECT t1.column as column1, t2.column as column2,... from table1 t1, table2 t2 where etc..

Thereafter in your java code, you can access using aliases,

resultSet.getString("column1")
resultSet.getString("column2")

or using column position(Position start from 1)

resultSet.getString(1);
resultSet.getString(2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM