Step1: You can download the mysql JDBC driver mysql-connector-java- *. Jar at http://www.mysql.com/products/connector-j/index.html, and add it to ClassPath.
Step2: Register a JDBC driver
Try {class.Forname ("com.mysql.jdbc.driver);} catch (classnotfoundexception e) {system.out.println (" Cannot No Driver ");
Step3: Provide JDBC URL
JDBC: mysql: // Host Name: Port number / database name? User = *** & password = *** & useunicode = true & characterencoding = UTF8
Port number: MySQL's default is 3306
Useunicode, CHARACTERENCODING: If you want to access Chinese, you must use it, indicating whether you use Unicode and specify the encoding method.
Step4: Gets from DriverManager Connection
You can pass the JDBC URL to DriverManager.getConnection () to get the Connection object, such as:
try {String url = "jdbc: mysql: // localhost: 3306 / GUESTBOOK user = caterpillar & password = 123456?"; Connection conn = DriverManager.getConnection (url); if (conn.isClosed ()!) System.out.println ( "Database connection is successful!"); Conn.close ();} catch (sqlexception e) {....}
You can also get UserName and Password to DriverManager.getConnection () get the Connection object, such as:
String url = "jdbc: mysql: // localhost: 3306 / addressbook"; string user = "zhujun"; string password = "123456"; connection conn = drivermanager.getConnection (URL, User, Password);
A complete example: