简体   繁体   English

Java resultSet getInt() 无返回值

[英]Java resultSet getInt() returns no value

Here, resultSet.getInt() doesn't work, but I do not know what is wrong with my code.在这里, resultSet.getInt() 不起作用,但我不知道我的代码有什么问题。

I want to increment the value of the column (with the name as the variable 'attendance').我想增加列的值(名称作为变量“出席”)。 Using the SELECT statement I want to read the current value and by using UPDATE I want to increment the corresponding value by 1. But the problem is that int a = r.getInt("'" + attendance + "'");使用 SELECT 语句我想读取当前值并使用 UPDATE 我想将相应的值增加 1。但问题是 int a = r.getInt("'" + admission + "'"); doesn't work.不起作用。 It always returns the value 0 although the current value isn't 0 (eg 1).尽管当前值不是 0(例如 1),但它始终返回值 0。 What is wrong with my code?我的代码有什么问题?

try {
                Class.forName("org.sqlite.JDBC");
                     c = DriverManager.getConnection("jdbc:sqlite:"+ x +".db");
                     s = c.createStatement();
                     r = s.executeQuery("SELECT '" + attendance + "' FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'");
                     while (r.next()){
                         int a = r.getInt("'" + attendance + "'");
                         int b = 1 + a;
                         String sql = "UPDATE viewer SET '" + attendance + "' = ? WHERE name = ? AND year = ? ";
                         p = c.prepareStatement(sql);
                         p.setInt (1,b);
                         p.setString (2,name);
                         p.setInt (3,year);
                         p.executeUpdate();
                     }
                     p.close();
                     c.close();
                     // r.getInt()  value always 0
            }
            catch (ClassNotFoundException | SQLException e) {
                JOptionPane.showMessageDialog(null, e);
            }

since you only have 1 column, you can use column index , instead of column names由于您只有 1 列,因此您可以使用column index ,而不是列名

int a = r.getInt(0);

Since you wrap the name of the column in single quotes, it is considered as the string literal 'attendance' and not the name of the column which is the value of the variable attendance .由于您将列的名称用单引号括起来,因此它被视为字符串文字'attendance'而不是列的名称,即变量attendance的值。
Change to:改成:

"SELECT " + attendance + " FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'"

(why do you concatenate the arguments name and year ? Use placeholders ? just like the UPDATE statement) (为什么要连接 arguments nameyear ?使用占位符?就像UPDATE语句一样)
and

"UPDATE viewer SET " + attendance + " = ? WHERE name = ? AND year = ? "

and

int a = r.getInt(attendance);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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