Posted on 2007-12-07 21:23
yukui 阅读(379)
评论(0) 编辑 收藏 所属分类:
技术
Step1:可在http://www.mysql.com/products/connector-j/index.html下载MySQL JDBC驱动程序mysql-connector-java-*.jar,并加入到ClassPath下面.
Step2:注册JDBC驱动程序
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.out.println("找不到驱动程序");
}
Step3:提供JDBC URL
jdbc:mysql://主机名:端口号/数据库名?user=***&password=***&useUnicode=true&characterEncoding=UTF8
端口号:MySQL的默认值是3306
useUnicode,characterEncoding:如果要存取中文,则必须使用,表明是否使用Unicode,并指定编码方式.
Step4:从DriverManager取得Connection
可以直接将JDBC URL传入DriverManager.getConnection()得到Connection对象,如:
try {
String url = "jdbc:mysql://localhost:3306/GUESTBOOK?user=caterpillar&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 DBTest {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/AddressBook";
String user = "ZhuJun";
String password = "123456";
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, password);
if(!conn.isClosed())
System.out.println("数据库连接成功!");
conn.close();
}
catch(ClassNotFoundException e) {
System.out.println("找不到驱动程序");
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
}
}