1. 封装连接数据库的类:
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DBhelp {
public static final String url = "jdbc:mysql://***:3306/databasename";
public static final String user = "user";
public static final String password = "password";
public java.sql.Connection con = null;
public java.sql.PreparedStatement ps = null;
ResultSet rs = null;
userdata userdata= new userdata();
public DBhelp(String sql) {
try {
con = DriverManager.getConnection(url, user, password);//获取连接
ps = con.prepareStatement(sql);//准备执行语句
rs = ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
this.con.close();
this.ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2. 封装sql查询的结果
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mysql.jdbc.*;
public class DBsqlUtils {
public static List driverJDBC(String URL, String user, String password) {
List list = new ArrayList();
java.sql.Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select USER_NM,PASSWORD from data_user";
//int sum= Integer.parseInt("select count(*) from data_user");
try {
Class.forName("org.gjt.mm.mysql.Driver");
con = DriverManager.getConnection(URL, user, password);
ps = con.prepareStatement(sql);
//ps.setInt(1, USER);
rs = ps.executeQuery();
while (rs.next()) {
String[] tmp = new String[2];
tmp[0] = rs.getString("USER_NM");
tmp[1] = rs.getString("PASSWORD");
list.add(tmp);
}
}catch (Exception e) {
e.printStackTrace();
}
finally {
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
}
3. 使用junit读取数据测试
package MaijiaT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.Collection;
@RunWith(value = Parameterized.class)
public class TestJDBCjunit {
private String username;
private String password;
public TestJDBCjunit(String username, String password) {
this.username = username;
this.password = password;
}
@Parameters
public static Collection getData() {
return DBsqlUtils.driverJDBC("jdbc:mysql://192.168.44.128:3306/testdata", "wangqq","testpwd");
}
@Test
public void test() {
System.out.println(this.username + " " + this.password);
}
}
对于该测试可以使用junit执行测试,也可以使用testng.xml配置执行测试,需配置 <test name="jdbcTest" junit="true">