简体   繁体   中英

Java JDBC with mySql - passing id from table

Here is the code:

public static Connection getConnection() throws Exception {

    String name1 = "Danny";
    String city1 = "Wien";

    try {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/supermarket??verifyServerCertificate=false&useSSL=true";
        String username = "myuser";
        String password = "mypass";
        Class.forName(driver);

        Connection conn = DriverManager.getConnection(url, username, password);

        String sql = "insert into marketinfo "
                + " (name, country)" + " values (" + name1 + ", " + city1 + ")";

        Statement insertie = conn.prepareStatement(sql);

        insertie.executeUpdate(sql);

    } catch (Exception e) {
        System.out.println(e);
    }

    return null;
}

My error is "Unknown column 'Danny' in 'field list'" .

In Sql database my table contains id, name and city. I want to pass the id field because that id is incremented automatically.

There's alot going on in that code, and as others have suggested you should break it up. But actually performing the query can be done like this:

public class YourClass {
    private static final String SQL = "INSERT INTO marketinfo (name, country) VALUES (?,?)";

    public void addMarketInfo(String name, String city) {
        try (Connection conn = getConnection();
             PreparedStatement stmt = conn.prepareStatement(SQL)) {

            stmt.setString(1, name);
            stmt.setString(2, city);
            stmt.executeUpdate();

        } catch (SQLException e) {
            // This is fine for debugging, but you probably want to log this or throw an exception
            // Depends on how the rest of your application is set up
            e.printStackTrace();
        }
    }
}

All your code creating the connection should most likely get moved to another class, and then called by the getConnection() method as in my example.

If you're using JDBC, PreparedStatements are used ALOT. It's worth looking more more examples on how they are used. Among other benefits, they're really helpful for avoiding string concatenation bugs like your original question.

This is the wrong way to do it. You should learn about PreparedStatement and how to bind values to parameters.

But it's worse than that.

Your method is getConnection , but it's also performing the query. Methods should do one thing well.

You don't close any of your resources. Another bad idea.

You print a stack trace to the console. Better to log it.

You hard wire your connection parameters instead of passing them in.

There's no connection pooling here.

seems you missed inner quotes around var name1 and city1

 String sql = "insert into marketinfo "
        + " (name, country)" + " values ('"+ name1 +"', '"+ city1 +"')";

but most important you should use parametrized query instead of string concat .

To fix this you need to quote your variables in the SQL:

String sql = "insert into marketinfo "
            + " (name, country)" + " values ('"+ name1 +"', '"+ city1 +"')";

However, this is awful code, and you should not do it like this.

See here for why not: https://www.acunetix.com/websitesecurity/sql-injection/

As a hit, your sql should look like this:

String sql = "insert into marketinfo "
                + " (name, country)" + " values (:name, :city)";

Then, you use a prepared statement to set the values. Code like this is why websites get all their private information stolen.

String or varchar type should be between two quotes 'some string' , but this still not secure so to avoid Syntax errors (Like you have now) or SQL Injection it's better to use PreparedStatement :

String sql = "insert into marketinfo (name, country) values (?, ?)";

try(PreparedStatement insertie = con.prepareStatement(sql);){
    insertie.setString(1, name1);
    insertie.setString(2, city1);
    insertie.executeUpdate();
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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