0

我正在尝试使用该prepareStatement功能。代码如下。执行后,它会返回一堆vlicense字符串而不是值。

当代码完成时statement.setString(),语句变为:

select 'vlicense' from Vehicle

但是,它必须是:

select vlicense from Vehicle

不带引号。谁能告诉我有什么问题?

statement = oConnection.prepareStatement("select ? from Vehicle");
String tempString = "vlicense";
statement.setString(1, tempString);
resultSet = statement.executeQuery();
4

4 回答 4

4

您不能将参数标记用于列名、表名、数据类型名或基本上不是数据的任何内容。

于 2009-06-02T23:53:28.163 回答
2

当您将绑定变量添加到这样的语句时,它会被转义,因此示例中的实际 SQL 字符串将作为“SELECT 'vlicense' FROM Vehicle' 进入数据库,选择文字字符串而不是您想要的列名。

在准备之前,您需要将该变量列名连接到您的 SQL 语句中:

statement = oConnection.prepareStatement("SELECT " + vlicense + " FROM Vehicle");

绑定变量实际上是用于查询参数而不是动态查询。

于 2009-06-02T23:58:37.497 回答
0

这 ?不能用于指定字段,只是在查询中执行一些过滤器,例如:

statement = conn.prepareStatement("select field from Vehicle where name=?");

在您的情况下,您的查询构建为:

select 'vlicense' from Vehicle

这意味着:为“车辆”的每条记录获取一个字符串“vlicense”。根据表中的记录数,您将获得n 个重复的字符串

于 2009-06-02T23:58:02.413 回答
0

它与jdbc或无关。 这只是一个错误的说法。prepared-statementsmysql
sql

如果您键入:

Select 'justanexample' from Vehicle

该表包含 4 行,您将获得 4 次

'justanexample'
'justanexample'
'justanexample'
'justanexample'

结果。

你没有指定你的表结构,但我猜这个语句应该看起来像这样:

select * from Vehicle where license = ?
于 2009-06-03T00:06:49.243 回答