I want to make a single method to make inserts on different tables, I want the user to
put as parameters the name of the table and a list of the data to be inserted.
Something like this:
public void insertar(String tabla, LinkedList data)
{
String alta = "insert into " + tabla + " values(";
for(int i = 0; i < datos.size(); i++) {
alta = alta + "?,";
}
alta = alta.substring(0, alta.length() - 1) + ")";
System.out.println(alta);
try
{
PreparedStatement insertar = con.prepareStatement(alta);
}
catch (SQLException ex)
{
}
}
My problem is that I can’t figure out how to set the values once the
String is made because the size and type of the data can change depending of
the table i’m using.
Is there a way to do this?, or I need to make it different?
Thanks in advance!
Your linked list should probably contain something other than
String‘s. Have you considered creating a type ofBindingclass that knows how to go about setting the values on your preparedStatement? I am envisioning something like this:You can use the value you are trying to apply to the
PreparedStatementand the index into thePreparedStatementto create your concreteBindingimplementation. Of course you would need to write your ownBindingsubclasses to encompass the other types of data you are interested in using.Here is a slight modification to your code to be able to use the ideas above:
I think that this is a pretty handy solution and I hope it will help you out. Good Luck!