Im getting this error when i try to access my View
I've built my database/View using this
CREATE TABLE Boxer(
BoxerId INTEGER PRIMARY KEY AUTOINCREMENT,
Firstname NVARCHAR(50) NOT NULL,
Lastname NVARCHAR(50) NOT NULL
);
CREATE TABLE Match(
MatchId INTEGER PRIMARY KEY AUTOINCREMENT,
BoxerA INTEGER NOT NULL FOREIGN KEY REFERENCES Boxer(BoxerId),
BoxerB INTEGER NOT NULL FOREIGN KEY REFERENCES Boxer(BoxerId),
MatchDate date NOT NULL DEFAULT GETDATE(),
NumberOfRounds INTEGER NOT NULL DEFAULT 12
);
CREATE TABLE Round(
RoundId INTEGER PRIMARY KEY AUTOINCREMENT,
MatchId INTEGER NOT NULL FOREIGN KEY REFERENCES Match(MatchId),
BoxerA INTEGER NOT NULL DEFAULT 0,
BoxerB INTEGER NOT NULL DEFAULT 0,
Position INTEGER NOT NULL
);
/*
Building a view which dislpays matches with boxers names and total scores
*/
CREATE VIEW MatchDetail AS
SELECT Match.MatchId, A.BoxerId AS IdA, B.BoxerId AS IdB, A.Firstname + ' ' + A.Lastname AS NameA, B.Firstname + ' ' + B.Lastname AS NameB,
(SELECT SUM(R.BoxerA) AS Score FROM Round AS R WHERE (R.MatchId = Match.MatchId)) AS ScoreA,
(SELECT SUM(R.BoxerB) AS Score FROM Round AS R WHERE (R.MatchId = Match.MatchId)) AS ScoreB,
Match.MatchDate, Match.NumberOfRounds
FROM Boxer AS A INNER JOIN Match ON A.BoxerId = Match.BoxerA INNER JOIN Boxer AS B ON Match.BoxerB = B.BoxerId
I've pretty much built my app so far using the notepad example so I then call my DbHelper
Cursor MatchesCursor = mDbHelper.fetchAllMatchDetails();
This then calls the query
public Cursor fetchAllMatchDetails(){
return mDb.query(VIEW_MATCHDETAIL, new String[] {
"MatchId"
}, null, null, null, null, null);
}
VIEW_MATCHDETAIL is defined as a string = "MatchDetail"
and it's here where it crashes saying
no such table MatchDetail: while compiling SELECT MatchId FROM MatchDetail
anyone had this problem before?
You have some beautiful SQL there. Unfortunately only the first line of sql will be executed in SQLiteDatabase.execSQL. The rest will be ignored silently (convenient eh?). Split up the statements manually like this:
https://github.com/browep/fpt/blob/master/src/com/github/browep/nosql/NoSqlSqliteOpener.java
or if you like to keep your sql in a separate file, try this:
String sqlText = getSqlText();
for(String sqlStmt : sqlText.split(";"))
myDb.execSQL(slqStmt + ";");
What stands out to me is the use of datatypes like NVARCHAR(50). SQLite only has a very simple set of datatypes. I'm surprised it doesn't throw an exception when you install the app. Try using simply TEXT instead.
If you cannot access a database that you know you have initialized, try passing the Context from the Activity that created the table to the class trying to query the table. Use that Context as part of your connection initialization.
Related
I have one table:
CREATE TABLE People
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name
);
I wanted to delete some rows from the table by using its id as condition. So I tried to use this one but it was not working at all. So have a look:
//idd is int
SQLiteDatabase.delete
(
"People",
"id" + " = ?",
new String[]{String.valueOf(idd)}
);
I dont know why it not working. It may because the String and int datatype. I figure it out something and it may work. But it use only two parameters instead of three. And I want to use three instead. So below is what I have figured out:
SQLiteDatabase.delete
(
"People",
"id" + " = ?" + idd,
null
);
So does anyone have any idea and help me out of this problem? I want to delete some rows from my table by using id as whereClause(second parameter) and idd variable which is integer as whereArg(3rd param) with delete function from SQLiteDatabase class.
SQLiteDatabase.delete("People", "id = " + idd, null);
Try this code
public boolean deleteTitle(Integer idd)
{
return db.delete(DATABASE_TABLE, id + "=" + idd, null) > 0;
}
I have a problem to create a table. If I try to get a value from the second column, android writes a empty space in the toast. But if I try to get a value from the first column, android writes the value of the column correctly. The query functions to write the first column and to write the second column are equal. So I think the Creation of the Table is the problem. But look yourself:
public SQLiteDatabase tabelleerstellen(){
SQLiteDatabase leveldatabase = openOrCreateDatabase("leveldata.db",SQLiteDatabase.CREATE_IF_NECESSARY, null);
leveldatabase.setVersion(1);
final String CREATE_TABLE_LEVEL =
"CREATE TABLE IF NOT EXISTS tbl_level ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "ME1 TEXT, "
+ "ME2 TEXT, "
+ "ME3 TEXT, "
+ "ME4 TEXT, "
+ "ME5 TEXT, "
+ "ME6 TEXT, "
+ "ME8 TEXT, "
+ "GESCHAFFT INTEGER);";
leveldatabase.execSQL(CREATE_TABLE_LEVEL);
return leveldatabase;
}
public void tester(SQLiteDatabase leveldata){
ContentValues cursortester = new ContentValues();
cursortester.put("ME2","25");
leveldata.insert("tbl_level",null,cursortester);
String[] testerpr = {"ME2"};
Cursor testerprüfen = leveldata.query("tbl_level",testerpr,null,null, null, null,null,null);
testerprüfen.moveToFirst();
String dada = testerprüfen.getString(testerprüfen.getColumnIndex("ME2"));
Toast testertoast = Toast.makeText(getApplicationContext(),dada,Toast.LENGTH_SHORT);
testertoast.show();
}
Please check the following things:
Please make sure the table is up to date .. so try to call DROP TABLE IF EXISTS tbl_level; and recreate the table.
If you run a test make sure the table is completely empty ... so delete everything at the beggining of the test.
If the table can contain elements during the test then make sure you check the last inserted element. Please note that calling testerprüfen.moveToFirst(); moves the cursor to the first row in the table so checking that row every time is even if the table contains 50 elements is not a good thing. In this case you either use a sorting option in your query of uese while (testerprüfen != null && testerprüfen.moveToNext()) {// Your code here}
All in all I think your problem is that you already inserted more that one element in the able but you always check only the first element (with testerprüfen.moveToFirst();). Please not that there is a cursor.moveToLast() method that you can also call. This method moves the cursor to the last row in the table.
I'm trying to make a new table for my database with sqlite:
String CREATE_ARCHIVE_TABLE =
"CREATE TABLE {0} ({1} INTEGER PRIMARY KEY AUTOINCREMENT," +
" {2} TEXT NOT NULL, {3} TEXT NOT NULL, {4} TEXT NOT NULL, {5} INTEGER);";
db.execSQL(MessageFormat.format(CREATE_ARCHIVE_TABLE,AItext.TABLE_NAME,AItext._ID,
AItext.TITLE,AItext.MESSAGE,AItext.DATE,AItext.TYPE));
with the interface:
public interface AItext extends BaseColumns {
String TABLE_NAME = "table_name";
String TITLE = "title";
String MESSAGE = "message";
String DATE = "date";
String TYPE = "type";
String[] COLUMNS = new String[]
{ _ID, TITLE, MESSAGE, DATE, TYPE };
}
but I have the following exception and I can't see the error
android.database.sqlite.SQLiteException: near "INTEGER": syntax error: ,
while compiling: CREATE TABLE archive_contacts_name (_id INTEGER PRIMARY KEY
AUTOINCREMENT, message INTEGER, name TEXT NOT NULL, phone TEXT NOT NULL,
check INTEGER, note TEXT NOT NULL);
As #aim has said, CHECK is in fact a SQLite Keyword that cannot be used as a column name.
A CHECK constraint may be attached to a column definition or specified as a table constraint. In practice it makes no difference. Each time a new row is inserted into the table or an existing row is updated, the expression associated with each CHECK constraint is evaluated and cast to a NUMERIC value in the same way as a CAST expression. If the result is zero (integer value 0 or real value 0.0), then a constraint violation has occurred. If the CHECK expression evaluates to NULL, or any other non-zero value, it is not a constraint violation. The expression of a CHECK constraint may not contain a subquery.
CHECK constraints have been supported since version 3.3.0. Prior to version 3.3.0, CHECK constraints were parsed but not enforced.
I havea weird problem in my android application which is related to database relations on foreign keys. The following codes describe my simple database's structure,
i have used SQLiteOpenHelper as a super class for handle database operation
private static final String CATEGORIES_TABLE = "CREATE TABLE __CATEGORIES_TBL(_id INTEGER PRIMARY KEY AUTOINCREMENT, _name TEXT NOT NULL, _desc TEXT NULL,"
+ "_create_date INTEGER NOT NULL, _update_date INTEGER NULL"
+ ", _parent_id INTEGER NULL, FOREIGN KEY(_parent_id) REFERENCES __CATEGORIES_TBL(_id) ON DELETE RESTRICT);";
private static final String CARDS_TABLE = "CREATE TABLE __CARDS_TBL(_id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "_value TEXT NOT NULL, _play_count INTEGER NULL, "
+ "_category_id INTEGER NOT NULL, FOREIGN KEY(_category_id) REFERENCES __CATEGORIES_TBL(_id) ON DELETE RESTRICT);";
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("PRAGMA foreign_keys = ON;");
db.execSQL(CATEGORIES_TABLE);
db.execSQL(CARDS_TABLE);
Logger.i("DB-INIT-DONE!");
} catch (Exception ex) {
Logger.e("Database on create error", ex);
}
}
as you see everything seems to be O.K and it is; I can insert, edit , select row(s) to/from both tables but unfortunately i can delete rows which they have child rows.
as i expected. because i set the FK (foreign-key) relation between the tow tables with ON DELETE RESTRICT mode therefore i expect to get an exception when i try to delete a row from parent table (__CATEGORIES_TBL) , actually the parent record is deleting and no exception happens,
by theory sqlite must prevent deleting any row in __CATEGORIES_TBL when it has one or more child row(s) in __CARDS_TBL or any child row(s) in __CATEGORIES_TBL but in my application i can delete rows when it has a parent-child relationship rows,
consider the following code (this is the deleting code)
private SQLiteDatabase db;
public long delete(long objId) {
try {
// TABLE_NAME can be __CATEGORIES_TBL or __CARDS_TBL based on program flow
return db.delete(TABLE_NAME, COLUMN_ROWID + "=" + objId, null);
} catch (Exception e) {
Logger.d("Unable to delete category <" + objId + ">.", e);
return -123456;
}
}
every call to db.delete returns 1 (means 1 row is deleted by this command) this code is executing under android 2.3 ;
Thanks in advance.
I get the behavior I'd expect from SQLite 3.7.9.
sqlite> CREATE TABLE __CATEGORIES_TBL (
...> _id INTEGER PRIMARY KEY AUTOINCREMENT,
...> _name TEXT NOT NULL,
...> _desc TEXT NULL,
...> _create_date INTEGER NOT NULL,
...> _update_date INTEGER NULL,
...> _parent_id INTEGER NULL,
...> FOREIGN KEY(_parent_id)
...> REFERENCES __CATEGORIES_TBL(_id) ON DELETE RESTRICT
...> );
sqlite>
sqlite> CREATE TABLE __CARDS_TBL(
...> _id INTEGER PRIMARY KEY AUTOINCREMENT,
...> _value TEXT NOT NULL,
...> _play_count INTEGER NULL,
...> _category_id INTEGER NOT NULL,
...> FOREIGN KEY(_category_id)
...> REFERENCES __CATEGORIES_TBL(_id) ON DELETE RESTRICT
...> );
sqlite>
sqlite> insert into __categories_tbl values
...> (1, 'name', 'desc',current_date,current_date,1);
sqlite> insert into __cards_tbl values (1, 'value',3, 1);
sqlite> pragma foreign_keys=on;
sqlite> select * from __categories_tbl;
1|name|desc|2012-08-25|2012-08-25|1
sqlite> delete from __categories_tbl;
Error: foreign key constraint failed
If I were you, I'd try to visually inspect the SQLite database after each step to see whether what you expect to happen is actually happening. IIRC, not every failure will raise an exception.
Foreign key support was introduced in version 3.6.19. There are compile-time settings that allow SQLite to parse foreign key constraints, but don't allow it to actually enforce them. (SQLITE_OMIT_TRIGGER defined, SQLITE_OMIT_FOREIGN_KEY not defined.) You should be able to tell whether your build of SQLite can enforce foreign keys by trying to create a trigger.
If creating a trigger fails with a parse error, then SQLite will parse foreign key statements, but won't enforce them. You'll need to recompile your build of 3.6.19, or upgrade to a newer version. (And check those settings before you compile.)
A column declared NOT NULL can appear to be empty if you've inserted an empty string. By default, NULL and empty strings look identical on output. You can tell whether a column contains nulls by selecting them.
select * from table_name where column_name is null;
about this problem i have put a db.execSQL("pragma foreign_keys=on;"); before delete statement in my app code then the problem solved, but i think this is unnecessary code maybe my phone's installed sqlite configs are wrong and needs to be reconfigured , is it possible to reconfigure the sqlite on phone ?
the test device is a HTC wildfire s (running sqlite version is 3.7.2)
I am trying to figure how to insert a null value into an SQLite table in Android.
This is the table:
"create table my table (_id integer primary key autoincrement, " +
"deviceAddress text not null unique, " +
"lookUpKey text , " +
"deviceName text , " +
"contactName text , " +
"playerName text , " +
"playerPhoto blob " +
");";
I wanted to use a simple Insert command via execSQL but since one of the values is a blob I can't do it (I think).
So, I am using a standard db.Insert command.
How do I make one of the values null?
If I just skip it in the ContentValues object will it automatically put a null value in the column?
You can use ContentValues.putNull(String key) method.
Yes, you can skip the field in ContentValues and db.insert will set it NULL.
Also you can use the other way:
ContentValues cv = new ContentValues();
cv.putNull("column1");
db.insert("table1", null, cv);
this directrly sets "column1" NULL. Also you can use this way in update statement.
I think you can skip it but you can also put null, just make sure that when you first create the Database, you don't declare the column as "NOT NULL".
In your insert query string command, you can insert null for the value you want to be null. This is C# as I don't know how you set up database connections for Android, but the query would be the same, so I've given it for illustrative purposes I'm sure you could equate to your own:
SQLiteConnection conn = new SQLiteConnection(SQLiteConnString());
// where SQLiteConnString() is a function that returns this string with the path of the SQLite DB file:
// String.Format("Data Source={0};Version=3;New=False;Compress=True;", filePath);
try
{
using (SQLiteCommand cmd = conn.CreateCommand()
{
cmd.CommandText = "INSERT INTO MyTable (SomeColumn) VALUES (null)";
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// do something with ex.ToString() or ex.Message
}