Before using JDBC to connect to a MySQL database, download the JDBC MySQL driver first: Http://pan.baidu.com/s/1pL0XqsV
After downloading the extract, 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 files 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 will then appear in the project directory to indicate that the driver was added successfully.
To start connecting to a database, there are generally 2 steps to connecting a database:
(1) Load the database driver and register it in the drive management (DriverManager) class
(2) connecting to a database
1 Packagecom.db;2 3 ImportJava.sql.DriverManager;4 Importjava.sql.SQLException;5 6 Importcom.mysql.jdbc.Connection;7 8 Public classdbhelper{9 //database, port number, databaseTen PrivateString Dburl = "Jdbc:mysql://localhost:3306/dormitorymanager"; One //Database user name A PrivateString dbUser = "root"; - //Database Login Password - PrivateString Dbpassword = "123456"; the //database-driven pinning - PrivateString jdbcname = "Com.mysql.jdbc.Driver"; - - //connecting to a database + PublicConnection Getconn () { - +Connection conn =NULL;//Create a Connection connection object A Try { atClass.forName (Jdbcname);//load the database driver and register it in the Drive management list -}Catch(ClassNotFoundException e) { - e.printstacktrace (); - } - Try { - //connecting to a database inconn =(Connection) drivermanager.getconnection (Dburl,dbuser,dbpassword); -}Catch(SQLException e) { to e.printstacktrace (); + } - returnConn; the } *}
JDBC Connection MySQL Database