Use table name variables in Prepared Statement INSERT
When building a series of batched INSERT queries using Java PreparedStatement objects, many developers encounter the challenge of adding table name variables to the query. This is often desirable when working with multiple tables with the same column format.
Trying to hardcode the table name into a "?" variable in the query statement may cause errors. Instead, the table name should be kept as a variable and dynamically populated before executing the batch query.
Some people may try to use stmt.setString(1, "tableName1") to dynamically set the table name, but this is not possible in PreparedStatement. Instead, query and table names must be concatenated or formatted together before they are assigned to the PreparedStatement.
Solution:
You can dynamically construct SQL queries using string concatenation or the String.format method. The table name is not intended to be a variable in the PreparedStatement, but is part of the static query string.
Example:
<code class="language-java">String tableName = "tableName1"; // 将表名连接到查询中 String query = String.format("INSERT INTO %s (col1, col2, col3, col4, col5) VALUES (?,?,?,?,?,?);", tableName); PreparedStatement stmt = connection.prepareStatement(query);</code>
By dynamically constructing the query string before assigning it to the PreparedStatement, you ensure that each insert statement is directed to the appropriate table.
The above is the detailed content of How Can I Use a Table Name Variable in a PreparedStatement INSERT Query?. For more information, please follow other related articles on the PHP Chinese website!