Java 验证数据并执行更新或插入操作
这是我的文件内容 id、发票号、账号、billstartdate、billenddate、到期金额、状态、billdateJava 验证数据并执行更新或插入操作,java,mysql,sql-server,Java,Mysql,Sql Server,这是我的文件内容 id、发票号、账号、billstartdate、billenddate、到期金额、状态、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.Stat
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”的记录是否已存在,如果存在,则更新而不是插入
如何做更新
`尝试创建另一个具有DB功能的方法。因为不建议用同一种方法读取文件和数据库。我只在另一种方法中具有数据库功能。。不是用同样的方法。你能帮我检查一下情况吗?这很简单。阅读insert语句后,您需要获取发票号。然后对其执行select语句。如果获取值,则执行update else insert.strUpdate=new StringBuffer();追加(“更新发票汇总集”);int arrSize=columnNames.length;对于(int i=0;i