我正在尝试从多个列名称(lo1,lo2,...)更新要动态获取的表。但是数据库中的值没有得到更新。 列名是co1,co2 ....
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
Connection conn = null;
PreparedStatement pstmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/netbeans","root","");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM colo");
rs = st.executeQuery("SELECT COUNT(*) FROM colo");
// get the number of rows from the result set
rs.next();
int rowCount = rs.getInt(1);
//txt_ans.setText(String.valueOf(rowCount));
int num_1 =300;
int num_2 =200;
int num_3 =300;
int num_4 =400;
String value = null;
int value1 ;
for(int i=1;i<=rowCount;i++)
{
String sql =("SELECT * FROM colo WHERE id = '"+i+"'");
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery(sql);
while(rs.next())
value = rs.getString("co1");
//txt_ans.setText(String.valueOf(value));
String x = "co2";
if(value.equals("lo1"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+x+"' = '"+num_1+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else if(value.equals("lo2"))
{
// value1= 1;
// txt_ans.setText(String.valueOf(value1));
String sql1 =("update colo set '"+ x +"' = '"+num_2+"' where id = '"+i+"'");
pstmt = conn.prepareStatement(sql1);
int r = pstmt.executeUpdate(sql1);
txt_ans.setText(String.valueOf(r));
}
else
{
value1 = 9009;
txt_ans.setText(String.valueOf(value1));
}
}
答案 0 :(得分:1)
问题在于使用单引号作为列名,例如&#39; x&#39; ,所以只需删除它们,如下所示:
setString
此外,请始终使用else if(value.equals("lo2"))
&#39; s ConcurrentMap
等方法来设置建议的值。
同样在Map
块内为其他查询应用相同的概念。