An in depth analysis of JDBC and drivers for database connections in java
- 2020-06-23 00:29:36
- OfStack
An in-depth analysis of JDBC and drivers for database connections in java
To understand:
When an java application connects to a database, it communicates with a driver provided by the database vendor via jdbc(which comes with jdk), which in turn communicates with the database.
Driver provided by database vendor:
There are various types of databases, such as mysql, oracle, etc., and different databases have different drivers. So before doing anything else, first download and import the corresponding driver jar package.
Connection test steps:
Declare the url, username, and password for the database used (for the database)
private static String url="jdbc:mysql://localhost:3306/mydb";
private static String name="root";
private static String password="1234";
1. Load driver
2. Use connect to connect to the database
There are two ways to load a driver:
public static void main(String[] args) {
try {
// Load driver
Class.forName("com.mysql.jdbc.Driver");
// use connect Establish a connection to the database
Connection connection=(Connection) DriverManager.getConnection(url,name,password);
System.out.println(" Database connection successful ");
} catch (Exception e) {
System.out.println(" Database connection failed ");
e.printStackTrace();
}
}
Or:
public static void main(String[] args) {
try {
// Load driver
Driver driver=new Driver();
DriverManager.registerDriver(driver);//
// use connect Establish a connection to the database
Connection connection=(Connection) DriverManager.getConnection(url,name,password);
System.out.println(" Database connection successful ");
} catch (Exception e) {
System.out.println(" Database connection failed ");
e.printStackTrace();
}
}
Output:
Database connection successful
Thank you for reading, I hope to help you, thank you for your support to this site!