SQL数据库更新语句不起作用

时间:2017-01-30 22:32:54

标签: java android sql

ResultSet rs = stat.executeQuery("select * from donor where username = '" +       username + "'");
        String type = rs.getString("bloodtype");
        System.out.println("the user's blood type is: " + type);
        String Updatesentence = "update bank set " + type +  " = " + type + " + 1 where name = '" + name + "'";
        System.out.println(Updatesentence);
        stat.executeUpdate(Updatesentence);

伙计我正在尝试使用此代码更新SQL数据库,虽然我没有在某处获得错误,但代码无法使用所需的结果。

            System.out.println(Updatesentence);
未打印

且未执行更新。我知道我的String声明可能有一些语法错误,但我无法解决它。

3 个答案:

答案 0 :(得分:2)

你有这个:

String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";

因此,如果用户的血型是AB ...

update bank set AB = AB + 1 where name = 'JohnSmith'

这显然不起作用。您需要在数据库中指明要更新的列。

答案 1 :(得分:0)

编写SQL语句时需要记住的最重要的事情之一是将查询 literal 与查询参数分开。这允许保护SQL Injection,并且还使DB可以使用不同的参数重用查询(和#34;硬解析" /仅优化查询一次)。使用JDBC执行此操作的方法是prepared statements

if not n:

当您使用预准备语句时,您不必担心将输入连接到查询中;它们将被消毒并自动注入。如果你以错误的方式做事,那么当你从代码中的不同变量逐个构造查询时,很容易出错,而这正是发生在您的示例中错误放置的def slowAdd(m, n): if not n: return m else: print('1 + ({}, {})'.format(m, n)) return 1 + slowAdd(m, n-1) print(slowAdd(5,5)) 1 + (5, 5) 1 + (5, 4) 1 + (5, 3) 1 + (5, 2) 1 + (5, 1) 10 变量。

答案 2 :(得分:0)

您的更新声明有误。它应该是 : String Updatesentence =“update bank set bloodtype =”+ type +“+ 1 where name ='”+ name +“'”;