我需要创建一个动态查询来更新行,并为用户提供该行中存在的每个列的输入窗口,然后在查询中插入这些值。
我现在不知道该怎么做,因为我是编程新手。
这是我的代码:
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(true);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM "+tablename);
ResultSetMetaData rsmd = rs.getMetaData();
//Grabs the first,second and third column name which only is used if you are deleting from the SPJ table.
FirstColumn = rsmd.getColumnName(1);
SecondColumn = rsmd.getColumnName(2);
ThirdColumn = rsmd.getColumnName(3);
//Changes the query depending on what table you have chosen
if(tablename.equals("SPJ")) {
query = "UPDATE "+ tablename +" WHERE " + FirstColumn + " = '" + row1 + "' AND " + SecondColumn + " = '" + row2 + "' AND " + ThirdColumn + " = '" +row3+"'" ;
} else {
query = "UPDATE "+ tablename +" WHERE " + FirstColumn + " = '" + row + "' VALUES("+values+")";
}
int columnCount = rsmd.getColumnCount();
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; ++i) {
row[i - 1] = rs.getString(i); // Or even rs.getObject()
}
// runs the query.
stmt.executeUpdate(query);
//closes connections
stmt.close();
c.close();
我尝试了这个,它为每个列提供了一个输入面板并将其放入数组但是我在WHERE附近遇到了sql语法错误? :/
int columnCount = rsmd.getColumnCount();
Object[] row = new Object[columnCount];
for (int i = 1; i <= columnCount; ++i) {
row[i-1] = JOptionPane.showInputDialog("Insert value: "+i); // Or even rs.getObject()
System.out.println(Arrays.toString(row));
}
}
答案 0 :(得分:0)
您使用错误的UPDATE语法。你应该使用这样的东西:
UPDATE table_name SET column1 = value1,column2 = value2,... WHERE some_column = SOME_VALUE;
有关更新的更多示例,请参阅此链接:SQL UPDATE
我错过了UPDATE语句中的SET。 VALUES用于INSERT语句。