验证数据并进行更新或插入

时间:2014-11-19 08:48:41

标签: java mysql sql-server

这是我的文件内容

id,invocienumber,accountnumber,billstartdate,billenddate,amountdue,status,billdate

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class ReadFromTextFile {

      public static void main(String[] args) throws Exception {
            String lineRead = null;
            Statement stmt = null;
            FileReader fr = null;
        Connection conn = null;
        String sql = "";
            try {
                  System.out.println("--Reading File--");
                  fr = new FileReader(new File("C:/Users/605798364/Desktop/SEMP REQ/InvoiceSummary.txt"));
                  BufferedReader reader = new BufferedReader(fr);
                  conn = getConnection();
                  stmt = conn.createStatement();
                  while ((lineRead = reader.readLine()) != null) {
                        System.out.println("Reading Insert Statement : \n" + lineRead.toString());                           
                        sql = lineRead.toString();
                        stmt.executeUpdate(sql);
                        System.out.println("--Query Executed successfully-- Data Inserted");
                  }
            }catch(SQLException se){
                se.printStackTrace();

            } catch (Exception e) {
                  System.err.println("Error: " + e.getMessage());
                  e.printStackTrace();
            } finally {
                  try{
                  if(stmt!=null)
                      conn.close();
                  if(conn!=null)
                       conn.close();
                }catch(SQLException se){
                  se.printStackTrace();
                }
                System.out.println("--Connection Closed Successfully--");
            }
      }

    public static Connection getConnection() throws Exception 
    {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost/test";
        String username = "root";
        String password = "root123";
        Connection conn = null;
        try{
            System.out.println("--Reading DB Connection--");
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username, password);
            System.out.println("--Connection established successfully--");
        }catch(Exception ex){
            System.err.println("Error : " + ex.getMessage());
        }
        return conn;
    }

}

` 我的程序应该读取文本文件并在db中插入记录。在插入之前检查“Invoicenumber”是否已存在记录,如果存在则更新而不是插入 怎么做更新?

`

0 个答案:

没有答案