这是代码:
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;
}
我的错误是“‘字段列表’中存在未知列‘Danny’”
。
在 Sql 数据库中,我的表包含 ID、名称和城市。我想传递 id 字段,因为该 id 会自动递增。
最佳答案
该代码中发生了很多事情,正如其他人建议的那样,您应该将其分解。但实际执行查询可以这样完成:
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();
}
}
}
创建连接的所有代码很可能都会移动到另一个类,然后由 getConnection() 方法调用,如我的示例中所示。
如果您使用 JDBC,则会大量使用PreparedStatements。值得查看更多有关如何使用它们的示例。除了其他好处之外,它们对于避免像您原来的问题这样的字符串连接错误确实很有帮助。
关于Java JDBC 与 mySql - 从表传递 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47144261/