1、新建一个csv文件
id,name,age
1,liji,22
2,zhangsan,33
3,lisi,44
2、创建一个和csv文件对应的一个对象
package hb.csvfile;
public class K_user {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3、读取csv文件,然后将其转为K_user对象,最后插入到数据库中
package hb.csvfile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CVSFileDemo {
public static void main(String[] args) {
//System.out.println(new File(".").getAbsolutePath());
FileInputStream fis = null;
BufferedReader br = null;
String url="jdbc:mysql://localhost:3306/hb?user=root&password=admin";
Connection con = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url);
stmt = (Statement) con.createStatement();
fis = new FileInputStream("D:\\JavaProject\\myaxis\\src\\hb\\csvfile\\test.csv");
br = new BufferedReader(new InputStreamReader(fis));
String result;
//用来判断是否是标题,做的标记
int count = 0;
while ((result = br.readLine()) != null) {
System.out.println(result);
result=result.trim();
if(count > 0){
if (!"".equals(result) && result.length() > 0) {
String[] strs = result.split(",");
K_user user = new K_user();
try {
user.setId(Integer.parseInt(strs[0]));
user.setName(strs[1]);
user.setAge(Integer.parseInt(strs[2]));
} catch (Exception e) {
System.out.println("数据不正确,无法正确转换类型");
}
//转为对象之后只需要把这个对象作为参数传递给某个方法即可
stmt.execute("INSERT INTO K_USER(id,NAME,AGE) values(null,'"+user.getName()+"',"+user.getAge()+")");
}
}
count++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}