peace
peace

Reputation: 53

insert variable into sql value

String ans1= "Apple";

myDb.execSQL("INSERT INTO " +
               TABLE_NAME + " Values (ans1);");

It just doesn't work this way.. why?? I need a simple way to do this, I don't want use class that's confusing for a beginner like me, possible?

Upvotes: 0

Views: 19247

Answers (6)

Bercove
Bercove

Reputation: 1175

For me i wanted to have last inserted id using select from database and then insert new data into database, the select query is used that function

pagesClass.getLastID('users', function(err, id){var id = id}

or you can use direct id which was returned by function

User.createUser = function (result){
var pagesClass = new PagesClass();
pagesClass.getLastID('users', function(err, id){
    conn.query("INSERT INTO users(id, name, email, password) VALUE('"+id+"', 'djsk"+id+"', '[email protected]"+id+"', 'bercove') ", function (err, res){
        if(err)
            result(null, err);
        else
            result(null, res);
    });
});
};

those id into name column and email column was showing how you can also add the variable to the other columns

Upvotes: 0

Lucifer
Lucifer

Reputation: 29632

You are inserting variable's value in to table, hence you have to use variable ANS out of the " ( double cots ), like below,

String ans1= "Apple";

myDb.execSQL("INSERT INTO " + TABLE_NAME + " Values ( '" + ans1 + "' );");

It is same as your have not use TABLE_NAME variable inside the ".

Upvotes: 0

Kevin Morrissey
Kevin Morrissey

Reputation: 179

Your insert statement should read something like

"INSERT INTO " + TABLE_NAME + " VALUES ('" + ans1 + "');"

Notice the single quotes that wrap ans1, if you are inserting a string value into an SQL table it should be wrapped in single quotes.

Upvotes: 5

Jason Hessley
Jason Hessley

Reputation: 1628

To inject the VALUE of variable into a sql statement you need to end your quotes before the variable + the variable + open your quotes again. For a String value you will also need to add single quotes around the variable.

myDb.execSQL("INSERT INTO " +
           TABLE_NAME + " Values ('" + ans1 + "');");

Upvotes: 0

Sieryuu
Sieryuu

Reputation: 1521

Try this example :

public long insertValue(String value1, String value2) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_VALUE1, value1);
        initialValues.put(KEY_VALUE2, value2);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

Upvotes: 4

kosa
kosa

Reputation: 66637

values should be something like

values("+ans1+");

observe ans1 is inside quote.

Note: raw sql statements are prone to sql injection attacks.

Upvotes: 0

Related Questions