1、首先,确保java环境和mysql/ target=_blank class=infotextkey>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 FilesJavajre6libext
测试例子:
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();
}
}
}