我需要在插入表之前檢查數據庫中是否存在記錄。我有兩個表,一個是我插入數據和一個引用主表的日誌表。在這個日誌表中我有ID,date_import和file_import。所以我想檢查一下file_import是否已經存在。在插入之前檢查數據庫中的重複項
這裏是我從零開始的代碼:
//DATE
DateFormat dateF = new SimpleDateFormat("dd.MM.yyyy");
Date date = new Date();
//DATE
//DB INIT
String URL = "jdbc:mysql://192.168.1.128:3306";
Connection con = (Connection) DriverManager.getConnection(URL,user,pass);
Statement stmt = (Statement) con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
Statement stmt1 = (Statement) con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String mySQL_log = ("CREATE TABLE IF NOT EXISTS dbtest.T_AJPES_TR_LOG"
+ "(ID INT unsigned PRIMARY KEY AUTO_INCREMENT, Date_import VARCHAR(45),"
+ "File_import VARCHAR(75)) ENGINE = INNODB");
String mySQL_new_table = ("CREATE TABLE IF NOT EXISTS dbtest.T_AJPES_TR "
+ "(row_count INT PRIMARY KEY AUTO_INCREMENT,"
+ "rn CHAR(15),sSpre CHAR(5),reg CHAR(5),eno VARCHAR(10),davcna VARCHAR(15),Ime VARCHAR(75),"
+ "Priimek VARCHAR(75),ID_LOG INT unsigned,"
+ "CONSTRAINT FOREIGN KEY(ID_LOG) references T_AJPES_TR_LOG(ID) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = INNODB");
stmt1.executeUpdate(mySQL_log);
ResultSet uprs1 = stmt1.executeQuery("SELECT * FROM dbtest.T_AJPES_TR_LOG");
stmt.executeUpdate(mySQL_new_table);
ResultSet uprs = stmt.executeQuery("SELECT * FROM dbtest.T_AJPES_TR");
//SELECT INIT
//READ FILE
File folder = new File(readFolder);
String[] fileName = folder.list();
for (;k<fileName.length;k++) {
name = fileName[k];
if (name.contains(".xml")) {
FileInputStream fstream = new FileInputStream(readFolder + name);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//READ FILE
uprs.next();
file_exists = uprs1.getString("File_import");
if (!file_exists.equals(name)) {
uprs1.afterLast();
uprs1.moveToInsertRow();
uprs1.updateString("Date_import",dateF.format(date));
uprs1.updateString("File_import",name);
uprs1.insertRow();
i=0;
看起來您所發佈的代碼不完整。 – Ralph 2010-12-01 09:23:03
是什麼問題? – 2010-12-01 09:23:54
爲什麼不定義一個列作爲一個唯一的鍵,所以數據庫將自己管理呢?如果在該鍵列中具有相同值的記錄已經存在,它將拒絕插入任何記錄 – duduamar 2010-12-01 09:25:51