Repetition in updating rows in MySQL table
我正在尝试更新已存在的MySQL表中的列。这些值必须从文本文件中读取,然后必须插入到指定的列中。
我尝试了以下方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | int counter=0; while((fileLine=in.readLine())!=null) { System.out.println("Line read is:"+fileLine); //execute db insertion try { //insert in the database Query="update db.table set col4=?"; //database preparedStmt3 = DBConnection.con.prepareStatement(Query); preparedStmt3.setString (1, fileLine); preparedStmt3.executeUpdate(); System.out.println("Complete update statement for row:"+counter); counter++; } catch (Exception e) { System.out.println("DB_Error:_"+ e.toString()); } } //end while loop |
我试过输出
编辑:文本文件包含以下行:美国农业协会血脑屏障连铸机滴滴涕电子工程师学会快速傅里叶变换
我添加了一些
而db只包含插入的最后一行
SQL不添加WHERE子句来指定要更新的行。因此,在每次迭代中,列中的所有记录都将其
您正在使用更新查询插入值。使用
1 | INSERT INTO db.table (col4) VALUES (?) |
试试这个,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | Connection conn = ConnectionBean.getInstance().getDBConnection(); int counter=0; String fileLine; BufferedReader in; String query1 ="select id from test"; // get all the id's from the table you wanna do the update ArrayList<Integer> al = new ArrayList<Integer>(); // store them in an arraylist try { PreparedStatement stmnt = conn.prepareStatement(query1); ResultSet rs = stmnt.executeQuery(); while(rs.next()) { al.add(rs.getInt("id")); } } catch(Exception ex) { ex.printStackTrace(); } try { in = new BufferedReader(new FileReader("file1.txt")); int h=1; while((fileLine=in.readLine())!=null && al.size()>0) { String query="UPDATE chaitu.test SET col=? WHERE id="+h ; PreparedStatement statement = conn.prepareStatement(query); statement.setString(1, fileLine); statement.executeUpdate(); h++; } //end while loo } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } |