将csv加载到mysql表中

时间:2018-03-27 11:05:44

标签: mysql arrays jdbc bufferedreader

我遇到了我正在处理的java-csv-mysql gui应用程序的问题。 我将在以下功能中分解应用程序: 1.使用JFileChooser选择一个CSv, 2.阅读csv 3.将csv导入Mysql表 4.将csv内容导入表格后显示它们。

我设法让它做以下功能。 1.选择一个csv文件 2.读取csv文件......-只读取一行 3.显示阅读记录

我遇到以下问题时遇到问题 1.读取csv中的“全部”记录 2.上传到csv。

我得到的错误是一个ArrayIndexOutofBoundsException:3 这是由于阅读csv。 csv具有以下格式:

            $ npm run build

            > f7-cnode@2.2.0 build C:\wamp64\www\Cordova\Cordova-ts\1
            > cross-env NODE_ENV=production webpack --config build/webpack.config.js -p --colors --hide-modules --display-optimization-bailout

            Hash: bf98e84f9caf99c38ba5
            Version: webpack 3.10.0
            Time: 12844ms
             5 assets

            ERROR in app.js from UglifyJs
            Unexpected token: name (Dom7) [app.js:749,6]

            ERROR in app.js from UglifyJs
            Unexpected token: name (Dom7) [app.js:749,6]
            Child html-webpack-plugin for "index.html":
                 1 asset
            Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js!src/assets/css/icons.css:
                 2 assets
            Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js!node_modules/less-loader/dist/cjs.js!node_modules/postcss-loader/lib/index.js!src/assets/app.less:
                 1 asset
            npm ERR! code ELIFECYCLE
            npm ERR! errno 2
            npm ERR! f7-cnode@2.2.0 build: `cross-env NODE_ENV=production webpack --config build/webpack.config.js -p --colors --hide-modules --display-optimization-bailout`
            npm ERR! Exit status 2
            npm ERR!
            npm ERR! Failed at the f7-cnode@2.2.0 build script.
            npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

            npm ERR! A complete log of this run can be found in:
            npm ERR!     C:\Users\ThinkIT\AppData\Roaming\npm-cache\_logs\2018-03-27T10_53_58_787Z-debug.log

csv在读取csv时需要执行以下操作 1.阅读csv, 2.将最后一列分隔为'/'。

这将导致有4列而不是3列。

这是我到目前为止的代码。

    2018/01/25,58,294616/0
    2018/01/27,102,298970/0

这是我得到的例外。

  public class Payment_import_v4 extends JFrame{
private JTable table;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable(){
        public void run()
        {
            createAndshowGUI();
        }
    });
}


private static void createAndshowGUI(){
            Payment_import_v4 form = new Payment_import_v4();
            form.setVisible(true);
} 

public Payment_import_v4(){
    //form frame
    super("Payment Import");
    setSize(900,600);
    setLocation(500,280);
    getContentPane().setLayout(null);

    //Label Result
    final JLabel lblResult = new JLabel("Result",JLabel.CENTER);
    lblResult.setBounds(150,22,370,14);
    getContentPane().add(lblResult);

    //Table
    table = new JTable();
    getContentPane().add(table);

    //Table Model
    final DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.addColumn("PayDate");
    model.addColumn("Ammount");
    model.addColumn("LinkId");
    model.addColumn("BranchNo");

    //ScrollPane
    JScrollPane scroll = new JScrollPane(table);
    scroll.setBounds(84,98,506,79);
    getContentPane().add(scroll);

    //Button Open
    JButton btnOpen = new JButton("Select File");
    btnOpen.setBounds(268,47,135,23);
    btnOpen.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
            JFileChooser fileOpen = new JFileChooser();
            FileFilter filter = new FileNameExtensionFilter("CSV file","csv");
            fileOpen.addChoosableFileFilter(filter);

            int ret = fileOpen.showDialog(null,"Choose file");

            if(ret == JFileChooser.APPROVE_OPTION){

                File file = fileOpen.getSelectedFile();//gets selectedFile.

                try {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    int row = 0;

                    //if (br.readLine() != null) {line = br.readLine();

                        while ((br.readLine()) != null) {
                            String line = br.readLine();// br string variable
                            String[] rawRow = line.split(",");
                            String lastEntry = rawRow[rawRow.length - 1];//this contains the LinkId/branchNo
                            String[] properLastEntry = lastEntry.split("/");//this contains the LinkId/branchNo split into two columnms
                            String[] oneRow = new String[rawRow.length + 1];
                            System.arraycopy(rawRow, 0, oneRow, 0, rawRow.length - 1);
                            System.arraycopy(properLastEntry, 0, oneRow, oneRow.length - properLastEntry.length, properLastEntry.length);

                            model.addRow(new Object[0]);
                            model.setValueAt(rawRow[0], row, 0);
                            model.setValueAt(rawRow[1], row, 1);
                            model.setValueAt(rawRow[2], row, 2);
                            model.setValueAt(rawRow[3], row, 3);
                            row++;
                        }
                        br.close();
                    //}
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                lblResult.setText(fileOpen.getSelectedFile().toString());
            }
        }
    });
    getContentPane().add(btnOpen);

    //btn Save
    JButton btnSave = new JButton("Save");
    btnSave.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent ea){
           SaveData();
       } 
    });
    btnSave.setBounds(292,228,89,23);
    getContentPane().add(btnSave);

    }

private void SaveData(){
    Connection connect = null;
    Statement stmt = null;

    try{

        //DriverManager Loader
        Class.forName("com.mysql.jdbc.Driver");

        //connection string url.. the port//schema name//username//password
                                                //this is the test Server ;oginDetails
        connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/riskfin", "root", "riskfin");//-------------> this is for the localhost server
        stmt = connect.createStatement();

        for(int i = 0;i<table.getRowCount();i++)
        {
            String PayDate = table.getValueAt(i,0).toString();
            String Ammount = table.getValueAt(i,1).toString();
            String LinkID = table.getValueAt(i,2).toString();
            String BranchNo = table.getValueAt(i,3).toString();

            String  sql = "Insert into temp_payment_import "
                    +"VALUES('"+LinkID+"','"
                    +Ammount+"','"
                    +PayDate+"','"
                    +BranchNo+"')";

            stmt.execute(sql);
       }

        JOptionPane.showMessageDialog(null,"Data imported Successfully");

    }catch(Exception ex){
        JOptionPane.showMessageDialog(null,ex.getMessage());
        ex.printStackTrace();
    }
    try{
        if(stmt!= null){
            stmt.close();
            connect.close();
        }
    }catch(SQLException e){
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

   }

1 个答案:

答案 0 :(得分:0)

您花了很大力气编写非常准确的数组操作代码来处理CSV数据中的两个分隔符。但是你从未真正使用oneRow数组。改变这个:

model.addRow(new Object[0]);
model.setValueAt(rawRow[0], row, 0);
model.setValueAt(rawRow[1], row, 1);
model.setValueAt(rawRow[2], row, 2);
model.setValueAt(rawRow[3], row, 3);   // ArrayIndexOutOfBoundsException

到此:

model.addRow(new Object[0]);
model.setValueAt(oneRow[0], row, 0);
model.setValueAt(oneRow[1], row, 1);
model.setValueAt(oneRow[2], row, 2);
model.setValueAt(oneRow[3], row, 3);

根据定义,rawRow只会包含3个元素,因为最终的2个字词仍会显示为单个字词(尚未在/上再次分割的字词)。