PreparedStatement不能动态设置表名和列名

本文详细解析了在Java中使用PreparedStatement进行SQL操作时常见的错误,特别是关于不可将表名和字段名作为动态参数的问题,提供了代码示例并指出正确的使用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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只能用来为参数(如参数值)设置动态参数,即用?占位,不可用于表名、字段名等

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值