简体   繁体   中英

java sql column insert

I created a table with column actual & Predicted

I inserted a Array of size 220 into column in table using SQL & JAVA

st.execute("insert into host_1 (actual) values ('"+ac[j]+"')");

Now i try to insert predicted value

st.executeUpdate("insert into host_1 (exp_predict) values ('"+pre[i]+"')");

It get inserted from 221th row. I want it to be inserted from row0

Plz anyone help

An insert statement always creates a new row. If you want to set values to existing rows, you should use an update statement. Or, better yet still, insert both values at the same time:

// Assume, or check, that ac and pre are the same size:
int size = ac.length;

PreparedStatement ps = 
    myConnection.prepareStatement
    ("INSERT INTO host_1 (actual, exp_predict) VALUES (?, ?)");
for (int i = 0; i < size; ++i) {
    ps.setString(1, ac[i]);
    ps.setString(2, pre[i]);
    ps.addBatch();
}
ps.executeBatch();
"insert into host_1 (actual) values ('"+ac[j]+"')" 

Above inserts a entire row. Not just column.

What you should do is first insert the column actual, later update the rows inserted. Your first SQL is fine, you only need to modify the second.

st.executeUpdate("update host_1 set exp_predict = pre[i] where actual = ac[j]");

You should update host_1 with exp_predict in the same loop with the condition as like

for(int i = 0; i<221; i++){
 st.execute("insert into host_1 (actual) values ('"+ac[j]+"')");

 st.executeUpdate("update host_1 set exp_predict = '"+pre[i]+"' where 
 actual = '"+ac[j]+"'
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM