1. 首先確保電腦上的Java環境和MySQL數據庫都已經安裝配置好
MySQL下載地址(http://dzcnc.onlinedown.Net/down/MySQL-essential-5.1.40-win32.zip)
2. 下載所需的jar文件 mysql-connector-java-3.1.14.zip(ftp://FTP.oss.eznetsols.org/mysql/Downloads/Connector-J/MySQL-connector-Java-3.1.14.zip)
3. 解壓縮後將MySQL-connector-java-3.1.14-bin.jar 放到JRE下 C:\Program Files\Java\jre6\lib\ext
4. 搞定,編寫測試程序。
附:幾個常用的方法..
import Java.sql.Connection;
import Java.sql.DriverManager;
import Java.sql.ResultSet;
import Java.sql.SQLException;
import Java.sql.Statement;
public class DBConfigure {
private Statement stmt = null;
private ResultSet rs = null;
private Connection conn = null;
String sql;
String strurl;
/**
* 缺省的構造函數
*/
public DBConfigure() {
}
/**
* 連接數據庫
*/
public void OpenConn() {
try {
// 驅動的名稱
Class.forName("com.MySQL.jdbc.Driver");
String user = "root";
String passwd = "123456";
String strDBname = "jobsearch";
conn = DriverManager
.getConnection("jdbc:MySQL://localhost/"+strDBname+"?user=" + user
+ "&passWord=" + passwd + "");// 訪問的數據庫的帳號密碼
} catch (Exception e) {
System.out.println("OpenConnection:" + e.getMessage());
}
}
public ResultSet executeQuery(String sql) {
stmt = null;
rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
System.err.println("executeQuery:" + e.getMessage());
}
return rs;
}
public void executeUpdate(String sql) {
stmt = null;
try {
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
System.out.println("executeUpdate:" + e.getMessage());
}
}
public void closeStmt() {
try {
stmt.close();
} catch (SQLException e) {
System.err.println("closeStmt:" + e.getMessage());
}
}
public void closeConn() {
try {
conn.close();
} catch (SQLException ex) {
System.err.println("aq.closeConn:" + ex.getMessage());
}
}
}
測試代碼如下:
import Java.sql.*;
public class Test {
public static void main(String args[]) {
try {
DBConfigure db=new DBConfigure();
ResultSet rs=null;
db.OpenConn();
String sql="select * from page";
rs=db.executeQuery(sql);
while(rs.next()){ System.out.println(rs.getString("content"));
}
db.closeStmt();
} catch (Exception e) {
e.printStackTrace();
}
}
}