Java 连接数据库需要与数据库对应的驱动包,MY SQL 的话可以通过http://dev.mysql.com/downloads/connector/j/ 来下载对应版本的jar包。下载完成之后拷贝mysql-connector-java-*-bin.jar 到项目lib目录,如果是Maven项目则在pom 里面添加对应的依赖关系就可以了。如下:

[code language=”xml”]

mysql mysql-connector-java 5.1.28
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

JDBC 连接 MySQL 数据库:

[code language="java"]

package com.devnp.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8";
private static String userName = "root"; // base on your login user name
private static String password = "!qaz2wsx"; // base on your login user

public static Connection getConnection() {
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

public static void connectionClose(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}