Java Reference
In-Depth Information
String url = "jdbc: mysql://localhost:3306/employeeschema" ;
String username = "root";
String password = "mypassword123";
String query = "select E.Name, D.DName" +
"from employee E, department D" +
"where E.DNR=D.DNR;";
Connection connection = null;
Statement stmt=null;
try {
System.out.println("Connecting to the MySQL database...");
connection = DriverManager.getConnection(url, username, password);
System.out.println("MySQL Database connected!");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
System.out.print(rs.getString(1));
System.out.print(" ");
System.out.println(rs.getString(2));
}
stmt.close();
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
System.out.println("Closing the connection.");
if (connection != null) {
try {
connection.close();
} catch (SQLException ignore) {
}
}
}
}
}
7.
Save the class by clicking the disk icon or selecting File Save.
8.
Run the application by clicking the green play icon or selecting Run Run.
9.
You should receive the following output:
Loading JDBC driver...
JDBC driver successfully loaded!
Connecting to the MySQL database...
MySQL Database connected!
Bart Baesens ICT
Aimée Backiel ICT
Seppe vanden Broucke ICT
Michael Jackson Marketing
Sarah Adams Finance
Closing the connection.
How It Works
The program starts by importing the JDBC package by using the statement import java.
sql.*;. The first part of the code then sets up the connection with the database. The statement
Search WWH ::




Custom Search