Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert data to a sqlite database with table name as variable

I would like to insert data into my sqlite data base but with a variable as the name of the table where the data should be entered.

try {

            Random rand = new Random();
            uniqueID = rand.nextInt(9998) + 1; //Generates a random number from 1 - 9999 inclusively
            String dateStart = day1.getText() + "/" + month1.getText() + "/" + year1.getText();
            String dateEnd = day2.getText() + "/" + month2.getText() + "/" + year2.getText();
            String projectN = projectName.getText();
            String addr = address.getText();
            //String engineerN = engineerName.getText();
            //String engineerP = engineerPassword.getText();

            Class.forName("org.sqlite.JDBC");
            conn2.setAutoCommit(false);


            PreparedStatement ps = conn2.prepareStatement("insert into "My table name" (uniqueid,name,address,startingdate,estcompletion) values(?,?,?,?,?,?)");
            ps.setInt(1, uniqueID);
            ps.setString(2, projectN);
            ps.setString(3, addr);
            ps.setString(4, dateStart);
            ps.setString(5, dateEnd);
            //ps.setString(6, engineerN);

            ps.execute();

            ps.close();
            conn2.commit();
            conn2.close();
           } 
    catch ( Exception e1) {
             System.err.println( e1.getClass().getName() + ": " + e1.getMessage() );
             System.exit(0);
           }
        }
    }
public String JJI() {
    return projectName.getText();

}
}

"My table name" in the prepared statement is the place where I want to put my table name getting it from projectName.getText(); at the end. The user enters projectname.getText in another class. Thank you for the help!

like image 212
Skib Rs Avatar asked Apr 13 '26 04:04

Skib Rs


1 Answers

  1. Store your table name in a String variable (how you like): String tableName = "users";

  2. Make a query variable that contains your SQL query:

String query = "insert into '" + tableName + "' (uniqueid,name,address,startingdate,estcompletion) values(?,?,?,?,?,?)";

  1. If you would like to have variables to insert, replace the "?" with your variable names as you have done in your code:

    ps.setInt(1, uniqueID); ps.setString(2, projectN); ps.setString(3, addr); ps.setString(4, dateStart); ps.setString(5, dateEnd);

  2. Execute the query:

PreparedStatement ps = conn2.prepareStatement(query); ps.execute();

like image 80
moffeltje Avatar answered Apr 14 '26 21:04

moffeltje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!