0

so Im trying to create new SQLite table which name is set by String created in my app. String is created from int userID and curret date (to string)

LocalDate date = LocalDate.now();

public void save()    {
    String db;
    db = String.valueOf("uid" + userID + date.toString());
    try {
        PreparedStatement pst = conn.prepareStatement("CREATE TABLE ?(name TEXT, kcal FLOAT, protein FLOAT, carbs FLOAT, fat FLOAT)");
        pst.setString(1, db);
        pst.executeUpdate();
    } catch (SQLException e)  {
        e.printStackTrace();
    }
}

Finnal string looks like this for example: uid02016-12-05

Unfortunatelly, I got

org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (near "?": syntax error)

and errors pointing to my PreparedStatement, i bet there is something wrong with '?', but how to do it other way?

Weeedooo
  • 501
  • 8
  • 25

1 Answers1

1

You can achieve that by simple string concat.

String query = "CREATE TABLE " + db + " (name TEXT, kcal FLOAT, protein FLOAT, carbs FLOAT, fat FLOAT)";
PreparedStatement pst = conn.prepareStatement(query);

I believe question marks in PreparedStatement are mentiond for parameters, not table name.

Piotr Sołtysiak
  • 998
  • 5
  • 13
  • Oh man, please no. OP has the right idea in using PreparedStatements. Its best not advocate string concatenation for sql queries. It just sends a bad message for people to follow. – ug_ Dec 05 '16 at 17:22
  • Neets backticks and escaping to prevent SQL injection – Alex K. Dec 05 '16 at 17:22
  • If you know how to dynamically change table name in PreparedStatement let us know. OP asked how to do it other way - for me such thing is bad idea anyway, but I'm not here to judge. – Piotr Sołtysiak Dec 05 '16 at 17:23
  • So Iv created string concatenation, changed date format to yyMMdd and it works now. But I understand thats not the right way to do it? Anyone could point me to the right direction then? – Weeedooo Dec 05 '16 at 17:34