Cory Sparks
Cory Sparks

Reputation: 255

SQLite error unrecognized token Unity

I am using Unity, here is a little snippet of my code. All I want to do is to put the data.token and the data.expire into SQLite. For some reason it keeps throwing me an error that is:

SqliteException: SQLite error
unrecognized token: "587503bc773a565d52401c87"
Mono.Data.Sqlite.SQLite3.Prepare (Mono.Data.Sqlite.SqliteConnection cnn, System.String strSql, Mono.Data.Sqlite.SqliteStatement previous, UInt32  timeoutMS, System.String& strRemain)
Mono.Data.Sqlite.SqliteCommand.BuildNextCommand ()

I have no idea how the token is unrecognized, In SQLite the Token field is a STRING and the Expire field is an INTEGER.

IncomingTokenData data = IncomingTokenData.CreateFromJSON(www.text);

string conn = "URI=file:" + Application.dataPath + "/MyDataBase.s3db"; //Path to database.
var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES(" + data.token +", " + data.expire + ")";

if(!string.IsNullOrEmpty(www.error)) {
    ErrText.text = "Error: " + www.error;
}else{
    if(data.pass == "1"){
        IDbConnection dbconn;
        dbconn = (IDbConnection) new SqliteConnection(conn);
        dbconn.Open(); //Open connection to the database.
        IDbCommand dbcmd = dbconn.CreateCommand();
        dbcmd.CommandText = sqlQuery;
        dbcmd.ExecuteNonQuery();

Upvotes: 1

Views: 1790

Answers (1)

Serlite
Serlite

Reputation: 12258

In SQL queries, you should enclose string values in single quotes (in this case, place quotes around data.token):

var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES('" + data.token +"', " + data.expire + ")";

Note that string concatenation isn't the best way to build up SQL queries - a more robust way to avoid these problems is to use placeholders, like the built-in functionality IDbCommand has for adding parameters:

var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES(@token, @expire)";

if(!string.IsNullOrEmpty(www.error)) {
    ErrText.text = "Error: " + www.error;
}else{
    if(data.pass == "1"){
        IDbConnection dbconn;
        dbconn = (IDbConnection) new SqliteConnection(conn);
        dbconn.Open(); //Open connection to the database.
        IDbCommand dbcmd = dbconn.CreateCommand();
        dbcmd.Parameters.Add("@token", SqlDbType.VarChar).Value = data.token;
        dbcmd.Parameters.Add("@expire", SqlDbType.Int).Value = data.expire;
        dbcmd.CommandText = sqlQuery;
        dbcmd.ExecuteNonQuery();

Using this method, the values are properly formatted according to their data type.

Upvotes: 2

Related Questions