Free Code Snippets in C#, Net Framework, Office 365, ASP.Net,WPF, Visual Studio, SQL Server, Antivirus free
#

SQLite: new ID at Insert Add

 

How do you get the new ID when inserting a record in SQLite?

 

Solution:

The return value of a Sqlite.Insert statement always automatically returns the new ID of a table if there is an integer autoimcrement column.

In case of an error, a -1 is output as

long newID = db.insert("tbl_Notes", null, values);

 

In a dive structure, which has a unique ID field.

To do this, when creating the SQLite table, specify Integer Primary Key Autoincrement

CREATE TABLE tbl_Notes (  IDNote INTEGER PRIMARY KEY AUTOINCREMENT ..

 

 

 

public long add_Note(String sTitle, String sText, Date dtNoteDay) {
   
//--------< add_Note() >--------
    //*add a recordset to the tbl_Notes Table
    //< getDB >
   
SQLiteDatabase db = this.getWritableDatabase();
   
//</ getDB >

    //< set_Values >
   
SimpleDateFormat fmtDate = new SimpleDateFormat("YYYYMMdd");
    String sDate_Note = fmtDate.format(dtNoteDay);
    String sDate_Now = fmtDate.format(
new Date());

    ContentValues values =
new ContentValues();
    values.put(
"Title", sTitle);
   
//values.put("Text", sText);
    //values.put("dtDay", sDate_Note);
    //values.put("dtEdit", sDate_Now);
    //</ set_Values >

    //< add >
   
long newID = db.insert("tbl_Notes", null, values);
   
//</ add >

    //< out >
   
if (newID == -1)
    {
       
//*SQLite Error on Insert: -1
       
return -1;
    }
   
else
   
{
       
//*return value is new ID
       
return newID;
    }
   
//</ out >
    //--------</ add_Note() >--------
}

 

 

 

 

Database on Android

In localhost-> sqlite

Database in SQLite on Android: http://192.168.178.23:8080/# (Android Debug Database)

IDNote

Title

Text

dtDay

dtEdit

5

dfffcName

2018-09-28 17:33:52

11

not online

2018-09-28 18:03:20

12

new Data

2018-09-28 18:05:12

13

924Name

2018-10-01 07:23:11

 

 

Matching table structure:

@Override
public void onCreate(SQLiteDatabase db) {
   
//--------< onCreate() >--------
    //*Create Tables
   
String createTable = "CREATE TABLE tbl_Notes " +
           
"(  IDNote INTEGER PRIMARY KEY AUTOINCREMENT " +
           
" , Title TEXT " +      //*Note of type TEXT
           
" , Text TEXT " +       //*Note of type TEXT
           
" , dtDay DATETIME " +
           
" , dtEdit DATETIME DEFAULT CURRENT_TIMESTAMP " +
           
")"
           
;
    db.execSQL(createTable);
   
//--------</ onCreate() >--------
}

 

 

Mobile
»
SQLite: save date
»
SQLite Database in Android: Complete Code Example
»
Sqlite: change values
»
SQLite: new ID at Insert Add
»
Evaluate SQLite on Android App

.

Contact for Jobs, Project Requests: raimund.popp@microsoft-programmierer.de