Kevin Chen
Kevin Chen

Reputation: 122

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?

Upvotes: 1

Views: 181

Answers (2)

Rakesh KR
Rakesh KR

Reputation: 6527

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

Upvotes: 1

Rowi
Rowi

Reputation: 565

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

Upvotes: 1

Related Questions