1.安装MySQL数据库,建立自己的测试用例
2.下载Connector/J,加压将.jar文件复制到Jre\lib\ext目录下。网址:http://www.mysql.com/downloads/connector/j/
3.创建连接和关闭数据库的类DBHelper.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DBHelper{
private static final String url = "jdbc:mysql://127.0.0.1/test";
private static final String driverName = "com.mysql.jdbc.Driver";
private static final String user = "root";
private static final String password = "111111";
public Connection conn = null;
public PreparedStatement pst = null;
public DBHelper(String sql){
try{
Class.forName(driverName);//驱动器载入
conn = DriverManager.getConnection(url, user, password);//获取连接
pst = conn.prepareStatement(sql);//与准备之行语句
}catch(Exception e){
e.printStackTrace();
}
}
public void close(){
try{
this.conn.close();
this.pst.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
4.创建Demo.java类进行测试
import java.sql.ResultSet;
import java.sql.SQLException;
public class Demo{
static String sql = null;
static DBHelper db1 = null;
static ResultSet ret = null;
public static void main(String[] args){
sql = "select * from Employees";
db1 = new DBHelper(sql);
try{
ret = db1.pst.executeQuery();
while(ret.next()){
String id = ret.getString(1);
String age = ret.getString(2);
String first = ret.getString(3);
String last = ret.getString(4);
System.out.println(id + "\t" + age + "\t" + first + "\t" + last);
}
ret.close();
db1.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}