SQL插入引号错误

时间:2015-02-17 09:07:03

标签: java sql

int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,"+u+","+p+",'1')");

我收到了错误

  

java.sql.SQLException:未知列'(U变量)'在'字段列表';

我肯定知道它是100%""但我似乎无法找到它出错的地方 任何帮助表示赞赏!

这是我的整个方法(我想学习如何用准备好的声明来做)

    public static void connectionDB(String u, String p, String f){
{
    try {
        String username = "/////////";
        String password = "///////";
        String url = "///////////////";
        Connection connection = DriverManager.getConnection(url, username, password);
        Statement stmt = connection.createStatement();
        int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");
    } catch (SQLException e) {
        e.printStackTrace();
    }

    System.out.println("Database connected!");
}

}

3 个答案:

答案 0 :(得分:6)

应该是

int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')");

<强>更新: -

你也可以查看预备语句,因为

当您必须使用不同的数据多次运行相同的语句时,准备语句要快得多。那是因为SQL只会验证一次查询,而如果你只是使用一个语句,它每次都会验证查询。

假设字段是A,B,C,D; A是int并且仍然是字符串

String insertTableSQL = "INSERT INTO Leden"
        + "(A,B,C,D) VALUES"
        + "(?,?,?,?)";

preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "Hello");
preparedStatement.setString(3, "this");
preparedStatement.setString(4, "OP");]

preparedStatement .executeUpdate();

答案 1 :(得分:1)

应该是

int rs = stmt.executeUpdate("INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')'");

答案 2 :(得分:1)

问题是,"在SQL中用于列或表等对象,而'用于字符串。所以在+ u +中,这似乎不存在于查询的上下文中。

因此,您的查询本身应该是(给定的,+u++p+是字符串。

INSERT INTO Leden VALUES (null,'+u+','+p+','1')

如果您需要在列中包含",则会显示为

INSERT INTO Leden VALUES (null,'"+u+"','"+p+"','1')

另外,我建议您指定要插入的列,使其看起来类似于:

INSERT INTO "Leden" ("col1", "col2", "col3", "col4") VALUES (null,'+u+','+p+','1')

这可以防止在通过其他列扩展表定义时查询失败。

此处使用预备语句也是一个好主意,因为它可以帮助您防止例如SQL注入。