欢迎来到Java学习网!
设为首页 | 加入收藏
当前位置: 首页 > 数据库 > MySql >

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();
}
}
}

    相关教程
    推荐内容