static String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true";
static String user = "root";
static String password = "root";
public static void main(String[] str) throws SQLException {
Driver driver = new com.mysql.jdbc.Driver();
Connection connection = null;
PreparedStatement preparedStatement = null;
// set property
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
try {
// 连接数据库
connection = driver.connect(url, props);
// 使用占位符的SQl语句
String sql = "insert into ?(id,username,age)" + "values(?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, "member5");
preparedStatement.setInt(2, 6);
preparedStatement.setString(3, "tom");
preparedStatement.setInt(4, 29);
// 执行更新操作
preparedStatement.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
connection.close();
}
}
报错:
总结:
PreparedStatement只能用来为参数(如参数值)设置动态参数,即用?占位,不可用于表名、字段名等