I have an error while trying to alter a MySQL table by adding columns to it dynamically where the column names are values stored in a Java array variable.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root","123");
Statement stmt=con.createStatement();
stmt.executeUpdate("create table distable (patient integer)");
PreparedStatement pst=con.prepareStatement("alter table distable add ? varchar(50)");
for(i=1;i<=col;i++)
{
pst.setString (1,out[i]);
pst.executeUpdate();
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
Here con is the variable which holds the connection. Using the connection I have created a table in MySQL and the name of the table is "distable". The table "distable" initially contains one integer column named Patient.
I need to alter the table "distable" and add new columns to it in run time. As I said the name of each column has to be the values stored in an array in Java. Hence I have used PreparedStatement, which contains a '?' which is a substitute for column names.
The number of columns to be inserted at runtime is stored in the variable "col". I have used setString() to set the column name at run time. The column names are stored in the array named "out". I have used executeUpdate() to execute the query.
When I run this code, the error i get is:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''GSM22449' varchar(50)' at line 1
'GSM22449' is the first value stored in the array [i.e. out[1]=GSM22449]. Therefore it is actually fetched and substituted at the place of '?' in the query. But the query is not executed.
Where does the error lies? Is there any problem with syntax?