1. 可在 下载MySQL JDBC驱动程序mysql-connector-java-*.jar,如我下载的是mysql-connector-java-5.1.18-bin.jar并加入到ClassPath下面,或加入到项目中。
2. 注册JDBC驱动程序
try { Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundException e) { System.out.println("找不到驱动程序"); }
3. 提供JDBC URL
jdbc:mysql://主机名:端口号/数据库名?user=***&password=***&useUnicode=true&characterEncoding=UTF8
端口号:MySQL的默认值是3306
useUnicode,characterEncoding:如果要存取中文,则必须使用,表明是否使用Unicode,并指定编码方式.
4. 从DriverManager取得Connection
可以直接将JDBC URL传入DriverManager.getConnection()得到Connection对象,如:
try { String url = "jdbc:mysql://localhost:3306/GUESTBOOK?user=root&password=123456"; Connection conn = DriverManager.getConnection(url); if(!conn.isClosed()) System.out.println("数据库连接成功!"); conn.close(); } catch(SQLException e) { .... }
也可以将userName和password传入DriverManager.getConnection()得到Connection对象,如:
String url = "jdbc:mysql://localhost:3306/AddressBook"; String user = "ZhuJun"; String password = "123456"; Connection conn = DriverManager.getConnection(url, user, password);
一个完整的例子:
import java.sql.*; public class TestJDBC { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/2"; String user = "root"; String password = "19870714"; Connection conn = DriverManager.getConnection(url, user, password); if(!conn.isClosed()) { System.out.println("success"); } conn.close(); } }