运行代码如下
@Test
public void test2() throws SQLException{
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String pwd="";
List<String[]> result=jdbcDriver(url,user,pwd);
}
其中url的test为数据库名
这里直接运行代码
@RunWith(Parameterized.class)
public class TestParameter {
private String name;
private String passwd;
public TestParameter(String name,String passwd){
this.name=name;
this.passwd=passwd;
}
@Parameters
public static Collection<String[]> getData() throws FileNotFoundException{
// return Arrays.asList(new
// String[][]{{"ray","ray"},{"cll","cll"}});
return DButil.csvDriver("D:\\Mars_WorkSpace\\webdrivertest\\userinfo.csv");
}
@Test
public void testparameter(){
System.out.println(name+"===="+passwd);
}
}
数据库以及CSV方法调用如下
public class DButil {
public static List<String[]> csvDriver(String filepath) throws FileNotFoundException{
List<String[]> list=new ArrayList<String[]>();
InputStream in=new FileInputStream(filepath);
BufferedReader buf=null;
buf=new BufferedReader(new InputStreamReader(in));
try {
String temp=null;
while(buf.readLine()!= null){
temp=buf.readLine();
String user[]=temp.split(",");
list.add(user);
}
buf.close();
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public static List<String[]> jdbcDriver(String url,String user,String pwd) throws SQLException{
//需要mysql-connection-java.jar
List<String[]> list=new ArrayList<String[]>();
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
String sql="select * from test";
try {
Class.forName("com.mysql.jdbc.Driver");
//注意这个是mysql数据库
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//三个变量分别是jdbc:mysql://localhost:3306/test root root
con=DriverManager.getConnection(url,user,pwd);
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
String[] users=new String[2];
users[0]=rs.getString(0);
users[1]=rs.getString(1);
list.add(users);
}
rs.close();
ps.close();
con.close();
return list;
}
}
以上的csv会出现每两行只读取一行的效果,未知原因
所以改进如下,但是会出现测试时最后一行报错,但是能够实现的情况,暂时代码如下
public class CSVReader {
public static List<String[]> ReaderCSV(String filepath) throws IOException{
List<String[]> list=new ArrayList<String[]>();
//String path="D:\\Mars_WorkSpace\\webdrivertest\\userinfo.csv";
FileInputStream fin = new FileInputStream(filepath);
BufferedReader buffReader=new BufferedReader(new InputStreamReader(fin));
String lineInfo=buffReader.readLine();
while(lineInfo!= null)
{
String user[]=lineInfo.split(",");
list.add(user);
lineInfo = buffReader.readLine();
}
return list;
}
}