Home >Database >Mysql Tutorial >How Can I Use Prepared Statements to Insert Data into Tables with Dynamic Names?
Execute insert query using prepared statements and dynamic table names
Using prepared statements to perform batch queries efficiently is very convenient when you need to insert data into multiple tables with similar column structures. However, the task becomes more complex when the target table name needs to change dynamically.
As mentioned in the original question, one approach is to build a query string that contains placeholders for the field values and table names:
<code>String strQuery = "INSERT INTO ? (col1, col2, col3, col4, col5) VALUES (?,?,?,?,?,?);";</code>
While this approach allows dynamic insertion of field values, it has shortcomings when trying to change the table name. Prepared statements are designed to execute a predetermined query template using variable data. They do not support dynamic changes to the query structure itself (including table names).
The solution to this problem is to use string concatenation or placeholders combined with String.format:
<code>String tableName = "tableName1"; String query = String.format("INSERT INTO %s (col1, col2, col3, col4, col5) VALUES (?,?,?,?,?,?);", tableName);</code>
You can dynamically define the target table for each insert operation by concatenating the table name directly into the query string. This approach may not be as concise as using prepared statements in all cases, but it provides the flexibility of using a single query template to insert data into different tables.
The above is the detailed content of How Can I Use Prepared Statements to Insert Data into Tables with Dynamic Names?. For more information, please follow other related articles on the PHP Chinese website!