I have written a code that get information from json file related to specific YouTube video and then stores the information I need in my database.
The parsing from json file has no problem. when I am trying to insert values in my database an error message appears telling me that no such table exists.
Here is the stack-trace:
07-31 08:42:22.451: I/Database(365): sqlite returned: error code = 1,
msg = no such table: youtube_VIDEOS 07-31 08:42:22.471: E/Database(365):
Error inserting video_CommentCount=70 video_CountView=50 video_Name=Badly
Drawn Boy - Disillusion (directed by Garth Jennings)
video_Url=https://www.youtube.com/watch?v=B11msns6wPU&feature=youtube_gdata_player
video_LIKES=60 video_Img=https://i1.ytimg.com/vi/B11msns6wPU/default.jpg
video_Descrption=My new playlist Description 07-31 08:42:22.471:
E/Database(365): android.database.sqlite.SQLiteException:
no such table: youtube_VIDEOS: ,
while compiling: INSERT INTO youtube_VIDEOS(video_CommentCount, video_CountView, video_Name, video_Url,video_LIKES, video_Img, video_Descrption) VALUES(?, ?, ?, ?, ?, ?, ?);
07-31 08:42:22.471: E/Database(365): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
And here is my database code:
package com.example.tstnetconnwithjson.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class youtube_db extends SQLiteOpenHelper {
public static final String dataBase_NAME="YOUTUBE_database";
private static final int dataBase_VERSION=1;
private static final String dataBase_TABLE="youtube_VIDEOS";
public static final String[] COLS_List={"video_Name","video_Descrption","video_Img","video_Url","video_CountView","video_LIKES","video_CommentCount"};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//end of declaring attributes and tables conents
public youtube_db(Context context) {
super(context,dataBase_NAME, null, dataBase_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table" + dataBase_NAME + "(" + COLS_List[0] +" text not null , "+ COLS_List[1]
+" text not null , "+ COLS_List[2]+" text not null , "+COLS_List[3]+" text not null , "+COLS_List[4]+" integer , "+COLS_List[5]
+" integer , "+COLS_List[6]+" integer ) ");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.i("in the upgrade", "ok");
}
}
And here is the function that would insert the information in my database:
package com.example.tstnetconnwithjson.db;
import com.example.tstnetconnwithjson.tables.videos;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class youtubeDataBaseManager {
SQLiteDatabase SQL_db;
youtube_db my_Database;
public youtubeDataBaseManager(Context c){
my_Database=new youtube_db(c);
SQL_db= my_Database.getWritableDatabase();
}//end of costructor
public long insert_Youtube_Info( videos video){
ContentValues contentValues = new ContentValues();
contentValues.put(youtube_db.COLS_List[0], video.getVideoname());
contentValues.put(youtube_db.COLS_List[1], video.getDecscrption());
contentValues.put(youtube_db.COLS_List[2], video.getImageurl());
contentValues.put(youtube_db.COLS_List[3], video.getVediourl());
contentValues.put(youtube_db.COLS_List[4], "50");
contentValues.put(youtube_db.COLS_List[5], "60");
contentValues.put(youtube_db.COLS_List[6], "70");
long addResult ;
addResult= SQL_db.insert(youtube_db.dataBase_TABLE, null, contentValues);
if(addResult==-1)
{
Log.i("add video", "add error.... ");
}
else
{
Log.i("add video", "add:ok.... ");
}
return addResult;
}
Can anyone tell me what is the problem?
"create table" + dataBase_NAME + "("
You are missing space between name and <create table> keyword. You have to change it to:
"create table " + dataBase_TABLE + "("
Otherwise, your DDL statement won't work.
Later, you try and reference a table called "youtube_VIDEOS", which doesn't exist. Because you never created it. It's all about typo.
you should change here:
create table" + dataBase_TABLE+ "(" + COLS_List[0] +" text not null , "+ COLS_List[1]
+" text not null , "+ COLS_List[2]+" text not null , "+COLS_List[3]+" text not null , "+COLS_List[4]+" integer , "+COLS_List[5]
+" integer , "+COLS_List[6]+" integer ) ");
You have that error, because your table in database didn't successfully created. Why ? Because your table hasn't got primary key (id). Add, e.g :
`_id` INT PRIMARY KEY AUTOINCREMENT,
And now every thing should work correctly
Related
I want to save the data from web site in sqlite database
WeatheDbHelper.java
/*sqlite database handler*/
package com.example.admin.sunshine.app.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by admin on 18/02/2016.
*/
public class WeatherDbHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION=2;
static final String DATABASE_NAME="weather.db";
public WeatherDbHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
final String SQL_CREATE_LOCATION_TABLE="CREATE TABLE"+ WeatherContract.LocationEntry.TABLE_NAME+"("+
WeatherContract.LocationEntry._ID+"INTEGER PRIMARY KEY,"+
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING+"TEXT UNIQUE NOT NULL,"+
WeatherContract.LocationEntry.COLUMN_CITY_NAME+"TEXT NOT NULL,"+
WeatherContract.LocationEntry.COLUMN_COORD_LAT+"REAL NOT NULL,"+
WeatherContract.LocationEntry.COLUMN_COORD_LONG+"REAL NOT NULL"+
");";
final String SQL_CREATE_WEATHER_TABLE="CREATE TABLE" + WeatherContract.WeatherEntry.TABLE_NAME+"("+
WeatherContract.WeatherEntry._ID +"INTEGER PRIMARY KEY AUTOINCREMENT,"+
WeatherContract.WeatherEntry.COLUMN_LOC_KEY +"INTEGER NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_DATE +"INTEGER NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC +"TEXT NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID +"INTEGER NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP +"REAL NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP +"REAL NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_HUMIDITY +"REAL NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_PRESSURE +"REAL NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_WIND_SPEED +"REAL NOT NULL,"+
WeatherContract.WeatherEntry.COLUMN_DEGREES +"REAL NOT NULL,"+
"FOREIGN KEY("+ WeatherContract.WeatherEntry.COLUMN_LOC_KEY +")REFERENCES "+
WeatherContract.LocationEntry.TABLE_NAME +"("+ WeatherContract.LocationEntry._ID+"),"+
"UNIQUE ("+ WeatherContract.WeatherEntry.COLUMN_DATE+","+ WeatherContract.WeatherEntry.COLUMN_LOC_KEY+
") ON CONFLICT REPLACE);";
sqLiteDatabase.execSQL(SQL_CREATE_WEATHER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase,int oldVersion, int newVersion)
{
sqLiteDatabase.execSQL("DROP TABLE IF EXIST"+ WeatherContract.LocationEntry.TABLE_NAME);
sqLiteDatabase.execSQL("DROP TABLE IF EXIST"+ WeatherContract.WeatherEntry.TABLE_NAME);
onCreate(sqLiteDatabase);
}
}
TestDb.java for testing the create table
/*creating the SQLite database
package com.example.admin.sunshine.app.data;
/**
* Created by admin on 22/02/2016.
*/
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;
import java.util.HashSet;
public class TestDb extends AndroidTestCase {
public static final String LOG_TAG = TestDb.class.getSimpleName();
// Since we want each test to start with a clean slate
void deleteTheDatabase() {
mContext.deleteDatabase(WeatherDbHelper.DATABASE_NAME);
}
/*
This function gets called before each test is executed to delete the database. This makes
sure that we always have a clean test.
*/
public void setUp() {
deleteTheDatabase();
}
/*
Students: Uncomment this test once you've written the code to create the Location
table. Note that you will have to have chosen the same column names that I did in
my solution for this test to compile, so if you haven't yet done that, this is
a good time to change your column names to match mine.
Note that this only tests that the Location table has the correct columns, since we
give you the code for the weather table. This test does not look at the
*/
public void testCreateDb() throws Throwable {
// build a HashSet of all of the table names we wish to look for
// Note that there will be another table in the DB that stores the
// Android metadata (db version information)
final HashSet<String> tableNameHashSet = new HashSet<String>();
tableNameHashSet.add(WeatherContract.LocationEntry.TABLE_NAME);
tableNameHashSet.add(WeatherContract.WeatherEntry.TABLE_NAME);
boolean b = mContext.deleteDatabase(WeatherDbHelper.DATABASE_NAME);
SQLiteDatabase db = new WeatherDbHelper(
this.mContext).getWritableDatabase();
assertEquals(true, db.isOpen());
// have we created the tables we want?
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
assertTrue("Error: This means that the database has not been created correctly",
c.moveToFirst());
// verify that the tables have been created
do {
tableNameHashSet.remove(c.getString(0));
} while( c.moveToNext() );
// if this fails, it means that your database doesn't contain both the location entry
// and weather entry tables
assertTrue("Error: Your database was created without both the location entry and weather entry tables",
tableNameHashSet.isEmpty());
// now, do our tables contain the correct columns?
c = db.rawQuery("PRAGMA table_info(" + WeatherContract.LocationEntry.TABLE_NAME + ")",
null);
assertTrue("Error: This means that we were unable to query the database for table information.",
c.moveToFirst());
// Build a HashSet of all of the column names we want to look for
final HashSet<String> locationColumnHashSet = new HashSet<String>();
locationColumnHashSet.add(WeatherContract.LocationEntry._ID);
locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_CITY_NAME);
locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_COORD_LAT);
locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_COORD_LONG);
locationColumnHashSet.add(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING);
int columnNameIndex = c.getColumnIndex("name");
do {
String columnName = c.getString(columnNameIndex);
locationColumnHashSet.remove(columnName);
} while(c.moveToNext());
// if this fails, it means that your database doesn't contain all of the required location
// entry columns
assertTrue("Error: The database doesn't contain all of the required location entry columns",
locationColumnHashSet.isEmpty());
db.close();
}
/*
Students: Here is where you will build code to test that we can insert and query the
location database. We've done a lot of work for you. You'll want to look in TestUtilities
where you can uncomment out the "createNorthPoleLocationValues" function. You can
also make use of the ValidateCurrentRecord function from within TestUtilities.
*/
public void testLocationTable() {
String testLocationSetting = "99705";
String testCityName = "North Pole";
double testLatitude = 64.7488;
double testLongitude = -147.353;
// First step: Get reference to writable database
SQLiteDatabase db = new WeatherDbHelper(
this.mContext).getWritableDatabase();
assertEquals(true, db.isOpen());
// Create ContentValues of what you want to insert
// (you can use the createNorthPoleLocationValues if you wish)
ContentValues locationValues = new ContentValues();
locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, testLocationSetting);
locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, testCityName);
locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, testLatitude);
locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, testLongitude);
// Insert ContentValues into database and get a row ID back
long locationRowId;
locationRowId = db.insert(WeatherContract.LocationEntry.TABLE_NAME, null, locationValues);
assertTrue(locationRowId != -1);
// Query the database and receive a Cursor back
Cursor c = db.query(WeatherContract.LocationEntry.TABLE_NAME,
null, //all columns
null, //columns for the "where" clause
null, //values fro the "where" clause
null, //columns to group by
null, //columns to filter by row groups
null //sort order
);
// Move the cursor to a valid database row
assertTrue(" Error: No Records returned from location query", c.moveToFirst());
// Validate data in resulting Cursor with the original ContentValues
// (you can use the validateCurrentRecord function in TestUtilities to validate the
// query if you like)
TestUtilities.validateCurrentRecord("Error: location query validation failed", c, locationValues);
//Move the cursor to demonstrate that there is only one record in the database
assertFalse("Error: More than one record returned from location query", c.moveToNext());
// Finally, close the cursor and database
c.close();
db.close();
}
/*
Students: Here is where you will build code to test that we can insert and query the
database. We've done a lot of work for you. You'll want to look in TestUtilities
where you can use the "createWeatherValues" function. You can
also make use of the validateCurrentRecord function from within TestUtilities.
*/
public void testWeatherTable() {
// First insert the location, and then use the locationRowId to insert
// the weather. Make sure to cover as many failure cases as you can.
long locationRowId = TestUtilities.insertNorthPoleLocationValues(mContext);
// Make sure we have a valid row ID.
assertFalse("Error: Location Not Inserted Correctly", locationRowId == -1L);
// Instead of rewriting all of the code we've already written in testLocationTable
// we can move this code to insertLocation and then call insertLocation from both
// tests. Why move it? We need the code to return the ID of the inserted location
// and our testLocationTable can only return void because it's a test.
// First step: Get reference to writable database
SQLiteDatabase db = new WeatherDbHelper(this.mContext)
.getWritableDatabase();
// Create ContentValues of what you want to insert
// (you can use the createWeatherValues TestUtilities function if you wish)
ContentValues contentValues = TestUtilities.createWeatherValues(locationRowId);
// Insert ContentValues into database and get a row ID back
long weatherRowId = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, contentValues);
assertTrue(weatherRowId != -1);
// Query the database and receive a Cursor back
Cursor cursor = db.query(WeatherContract.WeatherEntry.TABLE_NAME,
null,
null,
null,
null,
null,
null
);
// Move the cursor to a valid database row
assertTrue("Error: No Records Returned from Weather Query", cursor.moveToFirst());
// Validate data in resulting Cursor with the original ContentValues
// (you can use the validateCurrentRecord function in TestUtilities to validate the
// query if you like)
TestUtilities.validateCurrentRecord("Error: weather query validation failed", cursor, contentValues);
// Move the cursor to demonstrate that there is only one record in the database
assertFalse( "Error: More than one record returned from weather query",
cursor.moveToNext() );
// Finally, close the cursor and database
cursor.close();
db.close();
}
/*
Students: This is a helper method for the testWeatherTable quiz. You can move your
code from testLocationTable to here so that you can call this code from both
testWeatherTable and testLocationTable.
*/
public long insertLocation() {
return -1L;
}
}
Following are the error while testing the TestDb in AndroidTest
LOGCAT:
android.database.sqlite.SQLiteException: near "TABLEweather": syntax error (code 1): , while compiling: CREATE TABLEweather(_idINTEGER PRIMARY KEY AUTOINCREMENT,location_idINTEGER NOT NULL,dateINTEGER NOT NULL,short_descTEXT NOT NULL,weather_idINTEGER NOT NULL,minREAL NOT NULL,maxREAL NOT NULL,humidityREAL NOT NULL,pressureREAL NOT NULL,windREAL NOT NULL,degreesREAL NOT NULL,FOREIGN KEY(location_id)REFERENCES location(_id),UNIQUE (date,location_id) ON CONFLICT REPLACE);
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
at com.example.admin.sunshine.app.data.WeatherDbHelper.onCreate(WeatherDbHelper.java:50)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.example.admin.sunshine.app.data.TestUtilities.insertNorthPoleLocationValues(TestUtilities.java:90)
at com.example.admin.sunshine.app.data.TestDb.testWeatherTable(TestDb.java:155)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1837)
You need to put some "spaces" in your Create table scripts especially in the places where you open/close your doublequotes ("). Below I tried to put an empty space in every doublequote, you can check if it is ok or I missed anything.
final String SQL_CREATE_WEATHER_TABLE="CREATE TABLE " + WeatherContract.WeatherEntry.TABLE_NAME+" ( "+
WeatherContract.WeatherEntry._ID +" INTEGER PRIMARY KEY AUTOINCREMENT, "+
WeatherContract.WeatherEntry.COLUMN_LOC_KEY +" INTEGER NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_DATE +" INTEGER NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC +" TEXT NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID +" INTEGER NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP +" REAL NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP +" REAL NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_HUMIDITY +" REAL NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_PRESSURE +" REAL NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_WIND_SPEED +" REAL NOT NULL, "+
WeatherContract.WeatherEntry.COLUMN_DEGREES +" REAL NOT NULL, "+
" FOREIGN KEY( "+ WeatherContract.WeatherEntry.COLUMN_LOC_KEY +" ) REFERENCES "+
WeatherContract.LocationEntry.TABLE_NAME +" ("+ WeatherContract.LocationEntry._ID+" ), "+
" UNIQUE ( "+ WeatherContract.WeatherEntry.COLUMN_DATE+" , "+ WeatherContract.WeatherEntry.COLUMN_LOC_KEY+
" ) ON CONFLICT REPLACE);";
I'm trying to start with SQLite in android but I have some problems..
I took the code from a tutorial which was written in 2012, but it's not working for me now and shows me this error:
E/SQLiteLog﹕ (1) near "Table": syntax error
The problem is with creating/opening the Database.
package db.com.example.kids1.databasetest;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends ListActivity{
private final String DB_NAME = "Database";
private final String TABLE_NAME = "Table";
SQLiteDatabase DB = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> results = new ArrayList<>();
String[] res = {"Red", "Green", "Text"};
try {
DB = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +
TABLE_NAME +
"(Name VARCHAR, Street VARCHAR, Block INT, City VARCHAR, Tel VARCHAR);");
mFillDbsTable();
Cursor c = DB.rawQuery("SELECT Name, Street, Block, City, Tel FROM " +
TABLE_NAME +
" where Blcok == 9 LIMIT 5", null);
if (c!=null){
if (c.moveToFirst()) {
do {
String name = c.getString(c.getColumnIndex("Name"));
String street = c.getString(c.getColumnIndex("Street"));
int block = c.getInt(c.getColumnIndex("Block"));
String city = c.getString(c.getColumnIndex("City"));
String tel = c.getString(c.getColumnIndex("Tel"));
results.add(name + "," + street + "," + block + "," + city + "," + tel);
} while (c.moveToNext());
}
}
ListView list = (ListView)findViewById(android.R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, res);
list.setAdapter(adapter);
} catch (SQLiteException se){
Log.e(getClass().getSimpleName(), "Create/Open Database Problem.");
}
}
private void mFillDbsTable(){
try {
DB.execSQL("INSERT INTO " +
TABLE_NAME +
" Values('Noam', 'Shkolnik', 9, 'Rehovot', '054-4900807');");
DB.execSQL("INSERT INTO " +
TABLE_NAME +
" Values('Eyal', 'Shkolnik', 9, 'Rehovot', '055-4488779');");
DB.execSQL("INSERT INTO " +
TABLE_NAME +
" Values('Yehontan', 'Shkolnik', 9, 'Rehovot', '058-7789547');");
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create records.");
}
}
}
private final String TABLE_NAME = "Table"
You can't create a table named Table, because it's a reserved keyword.
You better create a table named MyTable (or _Table or better give a more talkative name, such as Persons - note the s for plurals).
So:
private final String TABLE_NAME = "MyTable"
For your reference: https://sqlite.org/lang_keywords.html
You could (but it's not recommended) use reserved keywords, but then you have to use special delimiters everytime you refer to that table.
Something like
private final String TABLE_NAME = "[Table]"
And there's also another (double) error in your query:
" where Blcok == 9 LIMIT 5"
Should be
" where Block = 9 LIMIT 5"
Try VARCHAR(100) and remove the trailing ;
You got couple of errors. First, do not name your table Table. Table is reserved word (see docs) and cannot be used directly. It's basically not recommended to use reserved words, so I suggest you change your table name, yet if you insist of using it, you need to quote it first:
If you want to use a keyword as a name, you need to quote it. There are four ways of quoting keywords in SQLite:
'keyword' A keyword in single quotes is a string literal.
"keyword" A keyword in double-quotes is an identifier.
[keyword] A
keyword enclosed in square brackets is an identifier. This is not
standard SQL. This quoting mechanism is used by MS Access and SQL
Server and is included in SQLite for compatibility.
keyword A
keyword enclosed in grave accents (ASCII code 96) is an identifier.
This is not standard SQL. This quoting mechanism is used by MySQL and
is included in SQLite for compatibility.
BTW: your further select query will fail too due to typo in where clause:
where Blcok == 9
I am learning how to create and insert values into SQLite DB. the application has a button and chronometer. clicking the button starts the timer and clicking it again stops it. On stop, the values are to be stored into the DB. I can see from the file explorer in Android Studio that the DB and the table is getting created. There is evidence in the Log to suggest the start and stop time is also getting captured, but the values are not getting inserted into the DB. I am pasting snippet of the code used to create the DB and then to insert the record. I am also pasing snippet of the log where the error is output. Please help.
import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.Context; import android.util.Log; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Feeds.db";
public static String TIMESTAMP_START;
public static String TIMESTAMP_END;
public static int _ID = 0;
public static final String DATABASE_TABLE = "T_FEEDRECORDS";
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE T_FEEDRECORDS ( _ID INTEGER primary key autoincrement, TIMESTAMP_START TEXT, TIMESTAMP_END TEXT)" ;
public DBHelper(Context context)
{
super(context,DATABASE_NAME, null, DATABASE_VERSION );
}
public void onCreate(SQLiteDatabase db)
{
Log.d("onCreate", "before DB Create");
try {
db.execSQL(SQL_CREATE_ENTRIES);
} catch(SQLException ex){ Log.d("onCreate", "DB creation exception:"+ ex.getMessage()); }
Log.d("onCreate", "after DB Create" + db.toString());
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF IT EXISTS " + DATABASE_TABLE);
Log.d("onUpgrade", "dropping table");
onCreate(db);
}
public void createFeedRecord (FeedRecords feedRecord){
ContentValues feedContent = new ContentValues();
feedContent.put(TIMESTAMP_START, feedRecord.getStartTime());
feedContent.put(TIMESTAMP_END, feedRecord.getEndTime());
try {
SQLiteDatabase db = this.getWritableDatabase();
Log.d("createFeedRecord values before insert", "start time : " + feedRecord.getStartTime() + " Timer end:" + feedRecord.getEndTime());
db.insertOrThrow(DATABASE_TABLE,null, feedContent );
db.close();
} catch(SQLException ex) {Log.d("SQL Exdception in create feed record", "" + ex.getLocalizedMessage());}
Log.d("createFeedRecord", "after content values");
}
}
LOG SNIPPET
02-04 09:57:43.287 2213-2213/? D/onClick......﹕ Timer Start time: 150204_095743
....
02-04 10:01:25.738 2213-2213/? D/onClick......﹕ Timer Stop time: 150204_100125
02-04 10:01:25.738 2213-2213/? D/inster Time Record﹕ after create Feed
02-04 10:01:25.754 1239-1293/? W/AudioTrack﹕ AUDIO_OUTPUT_FLAG_FAST denied by client
02-04 10:01:25.763 2213-2213/? D/createFeedRecord values before insert﹕ start time : 150204_095743 Timer end:150204_100125
02-04 10:01:25.763 2213-2213/? E/SQLiteLog﹕ (1) near "null": syntax error
02-04 10:01:25.763 2213-2213/? D/SQL Exdception in create feed record﹕ near "null": syntax error (code 1): , while compiling: INSERT INTO T_FEEDRECORDS(null) VALUES (?)
02-04 10:01:25.763 2213-2213/? D/createFeedRecord﹕ after content values
You need to assign
public static String TIMESTAMP_START="TIMESTAMP_START";
public static String TIMESTAMP_END="TIMESTAMP_END";
OR
Directly provide column name
ContentValues feedContent = new ContentValues();
feedContent.put("TIMESTAMP_START", feedRecord.getStartTime());
feedContent.put("TIMESTAMP_END", feedRecord.getEndTime());
I am trying to insert some data into and SQLite DB on android, but the code below just does not work. Can anyone spot the issue.
db = this.openOrCreateDatabase("data_7.db", 0, null);
db.execSQL("CREATE TABLE IF NOT EXISTS 'group' (my_id TEXT NOT NULL, my_key TEXT NOT NULL)");
db.execSQL("INSERT INTO 'group' (my_id, my_key) VALUES ('abc', '123')");
db.close();
After running the code I extracted the SQLite file off the emulator and opened it using an SQLite GUI viewer, the table was created but no data was inserted.
Note:
I have searched through this site all day and could not find a
suitable answer to this issue
I would like to do this without the aid of helper methods like
.insert(). ie. I need to user pure SQL
Try out this way:
"INSERT INTO group (my_id, my_key) " + "VALUES ('" + field_one + "', '" + field_two + "')";
you have to create the table in the method onCreate() that is found on the Dababase class that you have to build like this:
public class Database extends SQLiteOpenHelper
{
public static final String DB_NAME="YourDBName";
public static final int VERSION=1;
Context context=null;
public Database(Context context)
{
super(context, DB_NAME, null, VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase db)
{
try
{
String sql="CREATE TABLE group(my_id TEXT NOT NULL PRIMARY KEY, my_key TEXT NOT NULL)";
String insert="INSERT INTO group VALUES('abc','123');";
db.execSQL(sql);
db.execSQL(insert);
}
catch(Exception e)
{
Log.d("Exception", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS group");
onCreate(db);
}
}
Make sure that the old database is deleted or change the version to 2 in order to execute the query.
If you need to execute this query you need to write:
Database db=new Database();
SQLiteDatabasse read=db.getReadableDatabase();
I'm making a simple database in Android. I want to add new table after my code has executed once. Now, whenever i try changing my onCreate() method in EventDataSqlHelper class my app crashes.
This is probably because onCreate() associated with SQLiteOpenHelper is executed only when app is first run and we can't make further modifications in it .
I also tried writing a separate function for adding new table. It worked perfectly on first execution.But since on 2nd exection it will overwrite its previous database, hence it causes app to crash.
Is there any way to add new tables to database if database has already been created?
package org.example.sqldemo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
/** Helper to the database, manages versions and creation */
public class EventDataSQLHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
// Table name
public static final String TABLE = "events";
// Columns
public static final String TIME = "time";
public static final String TITLE = "title";
public EventDataSQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table " + TABLE + "( " + BaseColumns._ID
+ " integer primary key autoincrement, " + TIME + " integer, "
+ TITLE + " text not null);";
Log.d("EventsData", "onCreate: " + sql);
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
This is what onUpgrade and DATABASE_VERSION is for.
Example:
You have a table events, and is executed on phone.
Now you decide, you want a new table users.
change DATABASE_VERSION = 2; (this is your version number)
in onCreate() , create all tables (create table events & create table users)
in onUpgrade(), create all tables that changed between version oldVersion and newVersion (create table users)
Later if you want to add new tables, increment DATABASE_VERSION again, and create all tables in onCreate, and changes in onUpgrade
You could use CREATE TABLE IF NOT EXISTS TABLENAME ... as your query, that wouldn't overwrite your existing table.