java - How to insert values in a table with dynamic columns Jdbc/Mysql -
i want add values in table has dynamic columns. managed create table dynamic columns cannot figure out how insert data.
//create table sql = "create table mydb.mytable" + "(level integer(255) )"; int columnnumber = 5; //number of columns //add columns (i=0;i<columnnumber;i++){ string columnname = "level_" +i: string sql = "alter table mydb.mytable add " + columnname + " integer(30)"; } //insert data //how insert data dynamically, without knowing number of columns?
you can use database metadata column names. has advantage don't need know column names, rather retrieved dynamically in code.
public static list<string> getcolumns(string tablename, string schemaname) throws sqlexception{ resultset rs=null; resultsetmetadata rsmd=null; preparedstatement stmt=null; list<string> columnnames =null; string qualifiedname = (schemaname!=null&&!schemaname.isempty())?(schemaname+"."+tablename):tablename; try{ stmt=conn.preparestatement("select * "+qualifiedname+" 0=1"); rs=stmt.executequery();//you'll empty resultset you'll still metadata rsmd=rs.getmetadata(); columnnames = new arraylist<string>(); for(int i=1;i<=rsmd.getcolumncount();i++) columnnames.add(rsmd.getcolumnlabel(i)); }catch(sqlexception e){ throw e;//or log } finally{ if(rs!=null) try { rs.close(); } catch (sqlexception e) { // todo auto-generated catch block throw e } if(stmt!=null) try { stmt.close(); } catch (sqlexception e) { // todo auto-generated catch block throw e } } return columnnames; }
once have column names, can use (list.size() of course give number of columns).
update:
//i assume values (data inserted) list of object types , populated list<object> data = new arraylist<>(); //you populate list //getting column names list<string> columnnames = getcolumns("mytable", "mydb"); string insertcolumns = ""; string insertvalues = ""; if(columnnames != null && columnnames.size() > 0){ insertcolumns += columnnames.get(0); insertvalues += "?"; } for(int = 1; < columnnames.size();i++){ insertcolumns += ", " + columnnames.get(i) ; insertvalues += "?"; } string insertsql = "insert mydb.mytable (" + insertcolumns + ") values(" + insertvalues + ")"; try{ preparestatement ps = conn.preparestatement(insertsql); for(object o : data){ ps.setobject(o); //you must pass objects of correct type } ps.execute(); //this inserts data }catch(sqlexception sqle){ //do }
this code assume pass objects of correct types preparedstatement.setobject(object o) method. it's possible retrieve column types using metadatabase information , use info enforce type checking make code more complicated
Comments
Post a Comment