简体   繁体   English

如何在我的 sql insert 语句的语法中找到错误?

[英]how do I locate the error In my syntax for sql insert statement?

I cannot find the problem in the syntax for my insert into statement.我在 insert into 语句的语法中找不到问题。 I am trying to insert it into certain columns.我正在尝试将其插入某些列。 I have a feeling that it has to do with the quotes, but I am not sure.我有一种感觉,这与引号有关,但我不确定。

    @Override
public void addToDatabase() {
    try {
        // 1. get a connection to database
        Connection myConn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:8889/Bank", "kculbreth36",
                "Gerder11");
        // 2. create a statement
        Statement st = myConn.createStatement();

        st.executeUpdate("INSERT INTO budgeting (Food, Entertainment, Clothes, Utilities, Total Spendings)"
                + " VALUES (food, entertainment, clothes, utilities, totalValue)");
        conn.close();

    } catch (Exception exc) {
        exc.printStackTrace();
    }
}

Having SQL like拥有像 SQL

VALUES (food, entertainment, clothes, utilities, totalValue)

is making sql think that food etc are columns names not variables.使 sql 认为food等是列名而不是变量。

You are better off using a PrepaparedStatement like您最好使用PrepaparedStatement类的

"INSERT INTO budgeting (Food, Entertainment, Clothes, Utilities, Total Spendings)"
            + " VALUES (?, ?, ?, ?, ?)"

and then using the set methods然后使用set方法

st.setString (1, food);  // assuming that food is a variable

or或者

st.setString(1, "Hotdog"); // for a hard-coded value

see https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.htmlhttps://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html

edit also note the comment made by @MohamedSaligh编辑还要注意@MohamedSaligh 的评论

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

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