读文件写入数据库

public class TestReadcsvFile {
public static void main(String[] args) {
readFile("C:\\Users\\Desktop\\77777.csv");
}
public static void readFile(String filePath){
Connection conn = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://替换成数据库IP:3306/替换成数据库名";
CsvReader read = null;
try {
Class.forName(driver);
conn =(Connection) DriverManager.getConnection(url, "数据库账号", "数据库密码");
// 创建CSV读对象 例如:CsvReader(文件路径,分隔符,编码格式);
read = new CsvReader(filePath, ',', Charset.forName("UTF-8"));
【读文件写入数据库】// 跳过第一行 如果需要,可以忽略
read.readHeaders();
while(read.readRecord()){
System.out.println(read.getRawRecord());
String lineTxt = read.getRawRecord();
String[] columns = lineTxt.split("; ");
String sql = "INSERT INTO 表名(ID,NAME) values(?,?)";
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
ps.setString(1, columns[0]);
ps.setString(2, columns[1]);
//ps.setString(3, columns[2]);
//ps.setString(4, columns[3]);
//ps.setString(5, columns[4]);
//ps.setString(6, columns[5]);
//ps.setString(7, columns[6]);
//ps.setString(8, columns[7]);
//ps.setString(9, columns[8]);
//ps.setString(10, columns[9]);
//ps.setString(11, columns[10]);
//ps.setString(12, columns[11]);
//ps.setString(13, columns[12]);
//ps.setString(14, columns[13]);
//ps.setString(15, columns[14]);
//数据库不为空赋现有值
if( columns[15] != null && !"".equals( columns[15])) {
ps.setString(16, columns[15]);
}else {
//数据为空赋默认值,这边举例赋值为null。
ps.setString(16, null);
};
if( columns[16] != null&&!"".equals( columns[16])) {
ps.setString(17, columns[16]);
}else {
ps.setString(17, null);
};
ps.setString(18, columns[17]);
ps.setString(19, columns[18]);
ps.executeUpdate();
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
conn.close();
read.close();
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("读取文件出错");
e.printStackTrace();
}
}
}
}

    推荐阅读