Mysql 将csv文件转储到数据库中,导致错误连接关闭 package com.test.readfile; 导入java.util.Date; 公营雇员{ 私人长id; 私有字符串名; 私有字符串lastName; 私人双薪; 私刑; 私人约会日期; 公共字符串g

Mysql 将csv文件转储到数据库中,导致错误连接关闭 package com.test.readfile; 导入java.util.Date; 公营雇员{ 私人长id; 私有字符串名; 私有字符串lastName; 私人双薪; 私刑; 私人约会日期; 公共字符串g,mysql,csv,Mysql,Csv,将csv文件转储到数据库中,导致错误连接关闭 package com.test.readfile; 导入java.util.Date; 公营雇员{ 私人长id; 私有字符串名; 私有字符串lastName; 私人双薪; 私刑; 私人约会日期; 公共字符串getFirstName(){ 返回名字; } public void setFirstName(字符串firstName){ this.firstName=firstName; } 公共字符串getLastName(){ 返回姓氏; } pub

将csv文件转储到数据库中,导致错误连接关闭
package com.test.readfile;
导入java.util.Date;
公营雇员{
私人长id;
私有字符串名;
私有字符串lastName;
私人双薪;
私刑;
私人约会日期;
公共字符串getFirstName(){
返回名字;
}
public void setFirstName(字符串firstName){
this.firstName=firstName;
}
公共字符串getLastName(){
返回姓氏;
}
public void setLastName(字符串lastName){
this.lastName=lastName;
}
公共双薪制{
返回工资;
}
公共收入(双倍工资){
这个。薪水=薪水;
}
公共字符串getSin(){
归罪;
}
公共void setin(字符串sin){
这个。罪=罪;
}
公共长getId(){
返回id;
}
公共无效集合id(长id){
this.id=id;
}
公开日期getDob(){
返回dob;
}
公共无效设置日期(日期日期){
this.dob=dob;
}
}
包com.test.readfile;
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileReader;
导入java.io.IOException;
导入java.sql.Connection;
导入java.sql.Date;
导入java.sql.DriverManager;
导入java.sql.PreparedStatement;
导入java.sql.SQLException;
导入java.sql.Statement;
导入java.sql.Timestamp;
导入java.text.DateFormat;
导入java.text.ParseException;
导入java.text.simpleDataFormat;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.LinkedList;
导入java.util.List;
导入java.util.Map;
导入java.util.Scanner;
导入java.util.regex.Matcher;
导入java.util.regex.Pattern;
导入javax.swing.filechooser.FileFilter;
导入javax.swing.filechooser.FileNameExtensionFilter;
公共类文件读取器{
私有最终模式linePattern=Pattern.compile(“^(\\w++)\\s++(\\w++)\\s*+$”;
私有最终模式lineBreakPattern=Pattern.compile(“\r?\n”);
私有最终文件过滤器txtFilter=新文件名扩展过滤器(“*.txt”、“txt”);
私有最终文件TXT文件夹;
连接con=null;
语句stmt=null;
公共文件读取器(文件txtFolder){
this.txtFolder=txtFolder;
readFiles();
}
公共列表读取文件(){
试一试{
Class.forName(“com.mysql.jdbc.Driver”);
con=(连接)DriverManager.getConnection(“jdbc:mysql://localhost:3306/mysql“,”根“,”ptlusrapp$246”);
}捕获(SQLE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
捕获(ClassNotFoundException e1){
//TODO自动生成的捕捉块
e1.printStackTrace();
}
最终列表人员=新建LinkedList();
System.out.println(“txt文件夹”+txtFolder.getPath());
对于(最终文件txtFile:txtFolder.listFiles()){
if(txtFilter.accept(txtFile)){
System.out.println(“txt文件”+txtFile.getName());
addAll(readFile(txtFile));
}
}
System.out.println(“文件最终列表==>”+人);
插入数据(con、stmt、people);
还人,;
}
私有列表读取文件(文件txtFile){
尝试(最终扫描仪=新扫描仪(txtFile)){
/*scanner.useDelimiter(lineBreakPattern);
最终员工=新员工();
while(scanner.hasNext()){
最后一行字符串=scanner.next();
最终匹配器匹配器=linePattern.Matcher(线);
if(matcher.matches()){
开关(matcher.group(1.toUpperCase()){
案例“ID”:
setId(Integer.parseInt(matcher.group(2));
打破
案例“名称”:
Employee.setName(matcher.group(2));
打破
违约:
抛出新的IOException(“非法行”'+matcher.group()+“.”);
}
}
}*/
BufferedReader br=新的BufferedReader(新文件读取器(txtFile));
字符串currentLine=br.readLine();
DateFormat格式化程序=新的SimpleDateFormat(“dd-MM-yyyy”);
java.util.Date convertedDate=null;
String splitterString=“\\s”;
List processEmployeeList=new ArrayList();
while(currentLine!=null){
if(currentLine.indexOf(“,”>-1)
package com.test.mysql;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.test.mysql.FileReaderer;
public class automateImport {


    /**
     * @param args
     * @throws ClassNotFoundException 
     */
    public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException  {


      /*  Class.forName("com.mysql.jdbc.Driver");
        try {
            Connection con = (Connection) DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/mysql", "root", "root");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        FileReaderer fr = null;
        String dirpath = "";
        Scanner scanner1 = new Scanner(System.in);

        while (true) {
            System.out.println("Please give the directory:");
            dirpath = scanner1.nextLine();
            File fl = new File(dirpath);
            System.out.println("f1"+fl.getPath());
            if (fl.canRead()){
                 System.out.println("f2"+fl.getPath());
                fr = new FileReaderer(fl);
                break;
            }
            else{
                System.out.println("Error:Directory does not exists");
            }
        }
    }
}   
package com.test.mysql;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;


    public class FileReaderer {

        private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
        private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
        private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
        private final File txtFolder;
        Connection con = null;
        Statement stmt = null;

        public FileReaderer(File txtFolder) {
            this.txtFolder = txtFolder;
            readFiles();
        }

        public List<Person> readFiles() {

            try {
                Class.forName("com.mysql.jdbc.Driver");
                con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (ClassNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            final List<Person> people = new LinkedList<>();
            System.out.println("txt folder"+txtFolder.getPath());
            for (final File txtFile : txtFolder.listFiles()) {
                if (txtFilter.accept(txtFile)) {
                    System.out.println("txt Files " +txtFile.getName());
                    people.addAll(readFile(txtFile));

                }
            }
            System.out.println("File Final List==>"+people);

                 insertData(con,stmt,people);       

            return people;
        }

        private List<Person> readFile(File txtFile) {
            try (final Scanner scanner = new Scanner(txtFile)) {
               /* scanner.useDelimiter(lineBreakPattern);
                final Person person = new Person();
                while (scanner.hasNext()) {
                    final String line = scanner.next();
                    final Matcher matcher = linePattern.matcher(line);
                    if (matcher.matches()) {
                        switch (matcher.group(1).toUpperCase()) {
                            case "ID":
                                person.setId(Integer.parseInt(matcher.group(2)));
                                break;
                            case "NAME":
                                person.setName(matcher.group(2));
                                break;
                            default:
                                throw new IOException("Illegal line '" + matcher.group() + "'.");
                        }
                    }
                }*/
                BufferedReader br = new BufferedReader(new FileReader(txtFile));

                String currentLine = br.readLine();

                List<Person> processPersonList = new ArrayList<Person>(); 
                while (currentLine != null) {

                  String[] tokens = currentLine.split(",");
                  Person finalPerson = new Person();
                  finalPerson.setFirstName(tokens[0]);
                  finalPerson.setLastName(tokens[1]);
                  finalPerson.setSIN(tokens[2]);                
                  currentLine = br.readLine();
                  processPersonList.add(finalPerson);

                }
                System.out.println("final list==>"+processPersonList);

                br.close();
                return processPersonList;
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

       private void insertData(Connection con,Statement stmt,List<Person> pp){

           System.out.print("\nInserting records into table...");
           try{
               for(Person pr:pp){
                    System.out.println("First Name " +pr.getFirstName()+" Second Name " +pr.getLastName()+"SIN Name " +pr.getSIN());

            String sql = "INSERT INTO employee(first_name, last_name,sin) values (?,?,?)" ;
            PreparedStatement preparedStmt = con.prepareStatement(sql);
            preparedStmt.setString (1, pr.getFirstName());
            preparedStmt.setString (2, pr.getLastName());
            preparedStmt.setString (3, pr.getSIN());
            preparedStmt.execute();
               }

            System.out.println(" SUCCESS!\n");
            con.close();
            } catch (Exception e)
            {
              System.err.println("Got an exception!");
              System.err.println(e.getMessage());
            }
       } 
    }

package com.test.mysql;

public class Person {



        private String firstName;
        private String lastName;
        private String SIN;

        public String getFirstName() {
            return firstName;
        }
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }
        public String getLastName() {
            return lastName;
        }
        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
        public String getSIN() {
            return SIN;
        }
        public void setSIN(String sIN) {
            SIN = sIN;
        }


//
}
        package com.test.readfile;

        import java.util.Date;

        public class Employee {

            private long id;
            private String firstName;
            private String lastName;
            private Double salary;
            private String sin;
            private Date dob; 


            public String getFirstName() {
                return firstName;
            }
            public void setFirstName(String firstName) {
                this.firstName = firstName;
            }
            public String getLastName() {
                return lastName;
            }
            public void setLastName(String lastName) {
                this.lastName = lastName;
            }
            public Double getSalary() {
                return salary;
            }
            public void setSalary(Double salary) {
                this.salary = salary;
            }
            public String getSin() {
                return sin;
            }
            public void setSin(String sin) {
                this.sin = sin;
            }
            public long getId() {
                return id;
            }
            public void setId(long id) {
                this.id = id;
            }
            public Date getDob() {
                return dob;
            }
            public void setDob(Date dob) {
                this.dob = dob;
            }



        }

        package com.test.readfile;

        import java.io.BufferedReader;
        import java.io.File;
        import java.io.FileReader;
        import java.io.IOException;
        import java.sql.Connection;
        import java.sql.Date;
        import java.sql.DriverManager;
        import java.sql.PreparedStatement;
        import java.sql.SQLException;
        import java.sql.Statement;
        import java.sql.Timestamp;
        import java.text.DateFormat;
        import java.text.ParseException;
        import java.text.SimpleDateFormat;
        import java.util.ArrayList;
        import java.util.HashMap;
        import java.util.LinkedList;
        import java.util.List;
        import java.util.Map;
        import java.util.Scanner;
        import java.util.regex.Matcher;
        import java.util.regex.Pattern;

        import javax.swing.filechooser.FileFilter;
        import javax.swing.filechooser.FileNameExtensionFilter;


            public class FileReaderer {

                private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
                private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
                private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
                private final File txtFolder;
                Connection con = null;
                Statement stmt = null;

                public FileReaderer(File txtFolder) {
                    this.txtFolder = txtFolder;
                    readFiles();
                }

                public List<Employee> readFiles() {

                    try {
                        Class.forName("com.mysql.jdbc.Driver");
                        con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "ptlusrapp$246");
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    catch (ClassNotFoundException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    final List<Employee> people = new LinkedList<>();
                    System.out.println("txt folder"+txtFolder.getPath());
                    for (final File txtFile : txtFolder.listFiles()) {
                        if (txtFilter.accept(txtFile)) {
                            System.out.println("txt Files " +txtFile.getName());
                            people.addAll(readFile(txtFile));

                        }
                    }
                    System.out.println("File Final List==>"+people);

                         insertData(con,stmt,people);       

                    return people;
                }

                private List<Employee> readFile(File txtFile) {
                    try (final Scanner scanner = new Scanner(txtFile)) {
                       /* scanner.useDelimiter(lineBreakPattern);
                        final Employee Employee = new Employee();
                        while (scanner.hasNext()) {
                            final String line = scanner.next();
                            final Matcher matcher = linePattern.matcher(line);
                            if (matcher.matches()) {
                                switch (matcher.group(1).toUpperCase()) {
                                    case "ID":
                                        Employee.setId(Integer.parseInt(matcher.group(2)));
                                        break;
                                    case "NAME":
                                        Employee.setName(matcher.group(2));
                                        break;
                                    default:
                                        throw new IOException("Illegal line '" + matcher.group() + "'.");
                                }
                            }
                        }*/
                        BufferedReader br = new BufferedReader(new FileReader(txtFile));

                        String currentLine = br.readLine();
                        DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                        java.util.Date convertedDate = null;

                        String splitterString="\\s";

                        List<Employee> processEmployeeList = new ArrayList<Employee>(); 
                        while (currentLine != null) {

                            if(currentLine.indexOf(",")>-1)
                                splitterString = ",";
                            else
                                splitterString = "\\|"; 

                          String[] tokens = currentLine.split(splitterString);
                          Employee finalEmployee = new Employee();
                          finalEmployee.setId(Long.parseLong(tokens[0]));
                          finalEmployee.setFirstName(tokens[1]);
                          finalEmployee.setLastName(tokens[2]);                  
                          finalEmployee.setSalary(Double.parseDouble(tokens[3]));
                          finalEmployee.setSin(tokens[4]);
                          try {
                            convertedDate = formatter.parse(tokens[5]);
                            finalEmployee.setDob(convertedDate);
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                         // finalEmployee.setDob(convertedDate);
                          currentLine = br.readLine();
                          processEmployeeList.add(finalEmployee);

                        }
                        System.out.println("final list==>"+processEmployeeList);

                        br.close();
                        return processEmployeeList;
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }

               private void insertData(Connection con,Statement stmt,List<Employee> pp){

                   System.out.print("\nInserting records into table...");
                   try{
                       for(Employee pr:pp){
                            System.out.println("First Name " +pr.getFirstName()+" Second Name " +pr.getLastName()+"SIN Name " +pr.getSin() +"DOB: "+pr.getDob());

                    //String sql = "INSERT INTO employee(first_name, last_name,sin) values (?,?,?)" ;
                    String sql = "INSERT INTO employee(id,first_name,last_name,salary,sin,dob) values (?,?,?,?,?,?)" ;
                    PreparedStatement preparedStmt = con.prepareStatement(sql);
                    preparedStmt.setLong(1,pr.getId());
                    preparedStmt.setString (2, pr.getFirstName());
                    preparedStmt.setString (3, pr.getLastName());
                    preparedStmt.setDouble(4, pr.getSalary());
                    preparedStmt.setString (5, pr.getSin());
                    java.sql.Date sqlDate = new java.sql.Date(pr.getDob().getTime());
                    preparedStmt.setDate(6, sqlDate);

                    preparedStmt.execute();
                       }

                    System.out.println(" SUCCESS!\n");
                    con.close();
                    } catch (Exception e)
                    {
                      System.err.println("Got an exception!");
                      System.err.println(e.getMessage());
                    }
               } 
            }


        package com.test.readfile;
        import java.io.BufferedReader;
        import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.FileReader;
        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.Statement;
        import java.sql.ResultSet;
        import java.sql.SQLException;
        import java.util.ArrayList;
        import java.util.List;
        import java.util.Scanner;

        public class AutomateImport {

            /**
             * @param args
             * @throws ClassNotFoundException 
             */
            public static void main(String[] args) throws ClassNotFoundException, FileNotFoundException  {


              /*  Class.forName("com.mysql.jdbc.Driver");
                try {
                    Connection con = (Connection) DriverManager.getConnection(
                            "jdbc:mysql://localhost:3306/mysql", "root", "root");
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }*/
                FileReaderer fr = null;
                String dirpath = "";
                Scanner scanner1 = new Scanner(System.in);

                while (true) {
                    System.out.println("Please give the directory:");
                    dirpath = scanner1.nextLine();
                    File fl = new File(dirpath);
                    System.out.println("f1"+fl.getPath());
                    if (fl.canRead()){
                         System.out.println("f2"+fl.getPath());
                        fr = new FileReaderer(fl);
                        break;
                    }
                    else{
                        System.out.println("Error:Directory does not exists");
                    }
                }
            }
        }