How to Find Foreign Keys Using Inner Joins in Java
The Java JDBC library lets you connect to a database where you can query the tables. You use inner joins to find foreign keys, which are the fields contained in one table that links to another table. For instance, the "customerid" field in a customer table links to the foreign "customerid" key in the order table, so you can link customers to their respective orders.
Instructions
-
-
1
Open the Java editor you use to create your project. Open the project and source code file in which you want to link and use the inner join statements.
-
2
Add the JDBC libraries. Copy and paste the following code to the top of the Java source code file:
import java.sql.*;
-
-
3
Replace the "root" and "password" values with your own username and password in the following code to connect to the server and a database named "mydata":
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydata","root","password"); -
4
Set up the inner join statement. The following code connects a customer table to an orders table to find the foreign key called "customerid":
Statement query = con.createStatement();
ResultSet dataset = query.executeQuery
("select * from customers c join orders o on o.customerid=c.customerid"); -
5
Display the results. The following code displays the first customer name in the joined statement to verify that the query worked successfully:
string name = dataset.getInt("name");
System.out.println("Customer name: " + name);
-
1