I have 2 tables in my Java database. I would like to load rows from table1 and put them in table2. How can it be done please? I'm using ResultSet res = stmt.executeQuery(SQL)
for reading from table I. What can I use to put this data to table II. ?
Here you are:
String sql = "insert into table1 select * from table2 [where conditions]";
Statement stmt = connection.prepareStatement(sql);
stmt.executeUpdate();
YOu can try something likethis:-
Statement st1 = con1.createStatement();
ResultSet rs = st1.executeQuery("select * from table1");
PreparedStatement ps = null;
while(rs.next())
{
ps = con2.prepareStatement("insert into table2 values(?,?)");
ps.setInt(rs.getInt());
ps.setString(rs.getString());
ps.executeUpdate();
}
Assuming that there are two columns in your table
You can use PreparedStatments for this
Example Code Is here
int result;
Connection connection = null; // manages connection
PreparedStatement insert = null;
connection = DriverManager.getConnection(DB_URL,"root","password");
insert = connection.prepareStatement("INSERT into table2" +
"(f1,f2,f3)" +
"VALUES(?,?,?)" );
insert.setString(1, Yourvaluehere);
insert.setInt(2, Yourvaluehere);
insert.setDouble(3, YourValueHere);
result = insert.executeUpdate();
//Yourvaluehere - should come from the getmethods of the object - which is what i do, you can do something better if you have it in mind
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.