How to use rawQuery to insert a record

I need to save the record using the rawQuery method, because I want to insert the current date and time ( datetime() ), but I also need to insert strings containing quotation marks.

So, I wrote this code:

 String sql="INSERT INTO sms VALUES ( null, ?1, ?2, ?3, datetime())"; dbw.rawQuery(sql, new String[]{str1,str2,str3}); 

But he does not store anything ... what is wrong?

[EDIT]

This way I am not getting errors, but the record is not inserted.

 String mitt="mitt", dest="dest", text="text"; String sql="INSERT INTO sms VALUES ( null, ?, ?, ?, datetime('NOW'))"; dbw.rawQuery(sql, new String[]{mitt,dest,text}); 

Currently, the only way that works for inserting a record (with a quotation mark problem) is execSQL(String s) .

+6
source share
4 answers

SQLite does not have its own type of storing date and time data. It can store a string or integer representation of a date instead.

To convert your values, you can use the date-time functions detailed in the documentation for the date and time functions Sqlite

Your initial attempt is almost correct, but the 'NOW' argument is required to call the datetime () function.

 String sql="INSERT INTO sms VALUES ( null, ?, ?, ?, datetime('NOW'))"; 

You should also call execSQL instead of rawQuery , which is waiting for the recordset to return.

 dbw.execSQL(sql, new String[]{str1,str2,str3}); 

You can specify individual columns for inserting data by inserting a list of fields after the table name in your query, if you do not insert all values

 String sql = "INSERT INTO sms(f1, f2, f3, f4)" + "VALUES ( null, ?, ?, ?, datetime('NOW'))"; 

Another option that may be possible is to use the default timestamp in SQLite , although I have not tried to do this in android.

+15
source

I solved the problem this way:

 String sql="INSERT INTO sms VALUES (null,?,?,?,datetime('NOW'))"; dbw.execSQL(sql,new Object[]{mitt,dest,text}); 

Finally, I can store every char without problems !!!

+3
source

Try the following:

 ContentValues values; values=new ContentValues(); // values.put("field_name",value); values.put("id", 5); values.put("name", name); dbw.insert("table_name", null, values); 
-2
source
 String sql="INSERT INTO sms VALUES ( null, '"+str1+"', '"+str2+"', '"+str3+"', datetime())"; dbw.rawQuery(sql, null); 

Mark single quotes.

-2
source

Source: https://habr.com/ru/post/897609/


All Articles