It is used to understand the JDBC and driver connected to the database, and to connect the database to jdbc.
Understanding:
When a java application establishes a connection with a database, it first communicates with the driver provided by the database vendor through jdbc (jdbc is included in jdk), and then the driver communicates with the database.
Drivers provided by database vendors:
There are multiple types of databases, such as mysql and oracle. Different databases have different drivers. Before other operations, download and import the corresponding driver jar package.
Connection test procedure:
First declare the url, user name, and password of the database used (database)
private static String url="jdbc:mysql://localhost:3306/mydb";private static String name="root";private static String password="1234";
1. Load the driver 2. Use connect to establish a connection with the database
There are two ways to load the driver:
1 public static void main (String [] args) {2 try {3 // load driver 4 Class. forName ("com. mysql. jdbc. driver "); 5 // use connect to establish a Connection with the database 6 connection Connection = (Connection) DriverManager. getConnection (url, name, password); 7 System. out. println ("database connection successful"); 8} catch (Exception e) {9 System. out. println ("database connection failed"); 10 e. printStackTrace (); 11} 12}
Or:
1 public static void main (String [] args) {2 try {3 // load Driver 4 driver Driver = new Driver (); 5 DriverManager. registerDriver (driver); // 6 // use connect to establish a Connection with the database 7 connection Connection = (Connection) DriverManager. getConnection (url, name, password); 8 System. out. println ("database connection successful"); 9} catch (Exception e) {10 System. out. println ("database connection failed"); 11 e. printStackTrace (); 12} 13}
Output:
Database Connection successful