共用方法mysql读取
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.sql.*;
import java.util.*;
/**
* 数据库操作工具
*
* @author longrong.lang
*/
public class JdbcReader {
static Connection conn = null;
/**
* 执行sql
*
* @param driverClassName
* 数据库驱动
* @param url
* 数据库配置连接
* @param username
* 账号
* @param password
* 密码
* @param sql
* sql语句
* @param columns
* [] 脚本运行中的参数数组
* @return paramList 参数的list
* @throws SQLException
* @throws ClassNotFoundException
*/
public static List<Map<String, String>> getDataList(String driverClassName,
String url, String username, String password, String sql,
String columns[]) {
List<Map<String, String>> paramList = new ArrayList<Map<String, String>>();
Map<String, String> param = new HashMap<>();
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName(driverClassName);
// 打开链接
conn = DriverManager.getConnection(url, username, password);
// 执行查询
stmt = conn.createStatement();
ResultSet rs = null;
rs = stmt.executeQuery(sql);
// 展开结果集数据库
while (rs.next()) {
Map<String, String> map = new LinkedHashMap<String, String>();
for (int i = 0; i < columns.length; i++) {
String cellData = rs.getString(i + 1);
map.put(columns[i], cellData);
}
paramList.add(map);
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// 处理 JDBC 错误
System.out.println("处理 JDBC 错误!");
} catch (Exception e) {
// 处理 Class.forName 错误
System.out.println("处理 Class.forName 错误");
} finally {
// 关闭资源
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
return paramList;
}
}
dataprovider使用
@DataProvider
public Object[][] dbDataMethod() throws ClassNotFoundException, SQLException {
String sql = "select * from cs1";
String columns[] = {"xm", "id"};
List<Map<String, String>> result = getDataList( sql, columns);
Object[][] files = new Object[result.size()][];
for (int i = 0; i < result.size(); i++) {
files[i] = new Object[]{result.get(i)};
}
return files;
}