Connect JDBC to MySQL database and jdbcmysql Database
Before using JDBC to connect to the MySQL database, first download the jdbc mysql DRIVER: http://pan.baidu.com/s/1pL0XqsV
After downloading and unzipping, create a new lib folder in the java project created by Eclipse, and then copy the extracted mysql-connection-java-5.1.7-bin.jar file to the lib folder,
Then right-click on the mysql-connection-java-5.1.7-bin.jar ---> select Build Path ----> click Add to Build Path. The Referenced Libraries file appears in the project directory, indicating that the driver is successfully added.
You can start to connect to the database. Generally, there are two steps to connect to the database:
(1) load the database driver and register it into the DriverManager class.
(2) connect to the database
1 package com. db; 2 3 import java. SQL. driverManager; 4 import java. SQL. SQLException; 5 6 import com. mysql. jdbc. connection; 7 8 public class DBHelper {9 // database, port number, Database 10 private String dbUrl = "jdbc: mysql: // localhost: 3306/DormitoryManager "; 11 // database username 12 private String dbUser = "root"; 13 // database username 14 private String dbPassword = "123456 "; 15 // The database driver is fixed to 16 private String jdbcName = "com. mysql. jdbc. driver "; 17 18 // connect to database 19 public Connection getconn () {20 21 Connection conn = null; // create a Connection object 22 try {23 Class. forName (jdbcName); // load the database driver and register it to the driver management list. 24} catch (ClassNotFoundException e) {25 e. printStackTrace (); 26} 27 try {28 // connect to database 29 conn = (Connection) DriverManager. getConnection (dbUrl, dbUser, dbPassword); 30} catch (SQLException e) {31 e. printStackTrace (); 32} 33 return conn; 34} 35}