Dynamically Specifying Table Names in Java PreparedStatement INSERT Queries
Creating batched INSERT queries using Java's PreparedStatement
often requires handling both variable field values and variable table names. This allows you to insert data into multiple tables with identical column structures without rewriting the query for each table.
A common, but flawed, approach attempts to parameterize the table name directly within the SQL statement:
<code class="language-java">String strQuery = "INSERT INTO ? (col1, col2, col3, col4, col5) VALUES (?,?,?,?,?,?);"; </code>
This doesn't work because PreparedStatement
parameterization is intended for column values, not table or schema names. You cannot set the table name using stmt.setString(1, "tableName1");
The Effective Solution: String Concatenation
The correct method involves dynamically constructing the SQL query string by concatenating the table name before creating the PreparedStatement
. This ensures the table name is correctly incorporated into the query:
<code class="language-java">String tableName = "tableName1"; String query = "INSERT INTO " + tableName + " (col1, col2, col3, col4, col5) VALUES (?,?,?,?,?,?);"; PreparedStatement stmt = connection.prepareStatement(query);</code>
This technique provides the flexibility needed to efficiently manage batched INSERT operations targeting multiple tables with shared column definitions. Remember to sanitize tableName
to prevent SQL injection vulnerabilities if it comes from an untrusted source.
The above is the detailed content of How Can I Use a Variable Table Name in a Java PreparedStatement INSERT?. For more information, please follow other related articles on the PHP Chinese website!