Connect JDBC to MySQL database and jdbcmysql Database

Source: Internet
Author: User

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}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.