Here's an example JDBC connection program in Java that uses the MySQL JDBC driver and connects to a database with the provided details:
public class JdbcConnectionExample {
public static void main(String[] args) {
// JDBC driver and database URL
String jdbcDriver = "com.mysql.jdbc.Driver";
String dbUrl = "jdbc:mysql://localhost:3306/students";
// Database credentials
String user = "root";
String password = "secret";
// Establish connection to database
Connection conn = null;
try {
// Register JDBC driver
Class.forName(jdbcDriver);
// Open a connection
conn = DriverManager.getConnection(dbUrl, user, password);
// Do something with the connection
// ...
// Close the connection
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
} finally {
// Close the connection
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}
This program uses the com.mysql.jdbc.Driver JDBC driver and connects to a MySQL database at localhost:3306/students with the username root and password secret. After establishing a connection, you can execute SQL queries and perform other database operations using the Connection object. Finally, the connection is closed in a finally block to ensure that it is properly released.
No comments:
Post a Comment
If you have any doubts, please let me know