Understand:
When a Java application connects to a database, the driver communicates with the database vendor through JDBC (jdbc is the JDK ) and the driver communicates with the database.
Drivers provided by the database vendor:
There are various types of databases, such as MySQL, Oracle, etc., and different databases have different drivers. So before you do anything else, first download the corresponding driver jar package.
Connection test steps:
Declare the URL, user name, and password (database) of the database you are using first
private static string Url= "Jdbc:mysql://localhost:3306/mydb";p rivate static string name= "root";p rivate static string password= "1234";
1. Loading drivers 2. Connect to the database using connect
There are two ways to load a driver:
1 Public Static voidMain (string[] args) {2 Try {3 //Loading Drivers4Class.forName ("Com.mysql.jdbc.Driver");5 //connect to a database using connect6Connection connection=(Connection) drivermanager.getconnection (Url,name,password);7SYSTEM.OUT.PRINTLN ("Database connection succeeded");8}Catch(Exception e) {9SYSTEM.OUT.PRINTLN ("Database connection Failed");Ten e.printstacktrace (); One } A}
Or:
1 Public Static voidMain (string[] args) {2 Try {3 //Loading Drivers4Driver driver=NewDriver ();5Drivermanager.registerdriver (driver);//6 //connect to a database using connect7Connection connection=(Connection) drivermanager.getconnection (Url,name,password);8SYSTEM.OUT.PRINTLN ("Database connection succeeded");9}Catch(Exception e) {TenSYSTEM.OUT.PRINTLN ("Database connection Failed"); One e.printstacktrace (); A } -}
Output:
Database connection succeeded
Understanding of JDBC and drivers for connection to the database