sqlite3 creating trigger in android - android

I created table using this command :
CREATE TABLE projects( p_id integer primary key autoincrement, p_name text not null , p_desc text ,p_created_at datetime null , p_updated_at datetime null );
now i want to create a trigger on which the p_created_at and p_updated_at field will be updated,,,so i wrote
This is before insert query i wrote but gives me error
create trigger trigger_project before insert on projects
for each row begin
set new.p_created_at=now();
set new.p_updated_at=now();
end;
This gives me error
Error: near "set": syntax error
Any help is appreciated,, thnks
instead of now(); also tried datetime('now');
but still no luck :(

According to the doc you can't use just set, you need to write a statment, like
UPDATE myTable set column1 = value1

Related

SQLIte how to insert unique data on change of column value

I am using SQLite Database for my application. I have 4 columns- Student_Name,Student_Enroll, Student_Mob, Student_Address in my database. Now I can add new record if and only if one of four column value is different or all values are different. If all column values are same then no new record should be generated.
Can you please guide me to solve this issue?
To enforce that a set of columns must be unique, add a UNIQUE constraint:
create table Students (
/* ID INTEGER PRIMARY KEY, */
Student_Name TEXT,
Student_Enroll TEXT,
Student_Mob TEXT,
Student_Address TEXT,
UNIQUE (Student_Name, Student_Enroll, Student_Mob, Student_Address)
);
This allows new rows only if at least one of the four columns has a different value.
With a plain INSERT, attempting to insert a duplicate row will result in an error. If you simply want to ignore it instead, use INSERT OR IGNORE:
INSERT OR IGNORE INTO Students ...;
Despite of set your column as UNIQUE you also need to resolve the conflict created on each column when you try to insert new data.
To do so, define the behavior to solve the conflict:
"CREATE TABLE table (your columns here...(UNIQUE unique colums here...) ON CONFLICT REPLACE);"
During Create Database line insert UNIQUE ...for each column to insert only unique record.
Solution 1: (Simple)
Define all columns as unique:
create table TableName (id integer primary key autoincrement,
Student_Name text not null unique,
Student_Enroll text not null unique,
Student_Mob text not null unique);
You can add Student_Address as well, if you need to
Solution 2: (bit complex)
Use AND Operator with WHERE clause
INSERT INTO TableName (Student_Name, Student_Enroll, Student_Mob)
SELECT varStudentName, varStudentEnroll, varStudentMob
WHERE NOT EXISTS(SELECT 1 FROM TableName WHERE Student_Name = varStudentName OR Student_Enroll = varStudentEnroll OR Student_Mob = varStudentMob );
//If a record already contains a row, then the insert operation will be ignored.
You can find more information at the sqlite manual.
Live Example:
Open SQLite Online
Paste following code:
INSERT INTO demo (id,name,hint)
SELECT 4, 'jQuery', 'is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML'
WHERE NOT EXISTS(SELECT 1 FROM demo WHERE name = 'jQuery' OR hint = 'is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML' );
SELECT * from demo
Hit RUN
This won't insert 4th record and if you modify both values of WHERE clause then record will be inserted.

Is the sequence on how we type a Sqlite query to Create a column with attributes really matters

I'm new to coding android apps with Sqlite
I have three questions
I created this Sqlite table with columns with attributes like
TEXT
NOT NULL
UNIQUE
DEFAULT regular
Q1) I'm skeptical to know whether is there any order on how to delare attributes for a row
Q2) If I declare any row to have a default value like will the text be still inserted even though the user inserts something in that row, if yes, then how to insert a default value if the user dosen't inset any value in a specific Row
Q3)Is my code below correct ? What I desire is the row KEY_TAGNAME to be unique, not null and to have a value if the row doesn't get any data while a insert statement occurs for that table.
private static final String CREATE_TAGTABLE_SQL=
"CREATE TABLE " + DATABASE_TABLE_TAG
+ " ("
+ KEY_TAGROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_TAGNAME + " TEXT NOT NULL UNIQUE DEFAULT regular"
+ ");";
A1: I couldn't find anything in the documentation that clearly says anything about the order of the attributes but I tried to create a couple of tables in a test database I created to check this and it seems that if you do not follow the proper order you will get a syntax error.
(tried with create table test (key1 integer primary key autoincrement) which works correctly but create table test1 (key1 primary key integer autoincrement) gives a near "integer": syntax error:
A2: You can have a default value inserted that will be put if the user does not input anything there. The keyword is default and you will find more info here on how to use it (TL;DR upon table's creation you will create the row as usual and in the end put a DEFAULT and next to it the value. Please check the link on this)
A3 Your query is correct and will do the things you mention.

Sql query not giving desire result for android application?

I have two tables naming :
Custom_fields -->(id,name,sequence)
Custom_field_value -->(id,user_id,custom_field_id,custom_field_value)
The primary key of Custom_fields table is present in Custom_field_value table.Every user will have data associated with custom fields but not for all the fields.I need to make a query to find out the values of custom fields for a particular user id.For every user I need all custom field and their values(even if value is not present).I created the following query:
"SELECT alumni_custom_fields. _id,
alumni_custom_fields.field_label as key ,
alumni_custom_field_data.custom_field_value as value
FROM alumni_custom_fields LEFT JOIN alumni_custom_field_data
ON alumni_custom_fields._id=alumni_custom_field_data.custom_field_id " +
"WHERE alumni_id ='"+alumniId+"' order by sequence";
But its only giving the custom fields which has value and not giving me the custom fields whose value is none or empty.
Please help me fix this query.
Please try this.....
SELECT alumni_custom_fields. _id,alumni_custom_fields.field_label as key ,alumni_custom_field_data.custom_field_value as value FROM alumni_custom_fields LEFT JOIN alumni_custom_field_data ON alumni_custom_fields._id=alumni_custom_field_data.custom_field_id and alumni_id ='"+alumniId+"' order by sequence
This will surely solve your problem...

SQliteException:no such table [duplicate]

I have created one Member_Master table whose primary key is member_id in sqlite manager for android and creating foreign key in child table e.g Event_Master for member_id from Member_Master. I was getting no such table found:Member_Master error
But now I am getting the following error :
SQLiteManager: CREATE TABLE "main"."Events_Master" ("event_id" NUMERIC PRIMARY KEY NOT
NULL ,"event_name" TEXT NOT NULL ,"event_details" TEXT NOT NULL ,"event_start_date"
DATETIME NOT NULL ,"event_end_date" DATETIME NOT NULL ,"event_time" DATETIME NOT NULL
,"event_venue" TEXT NOT NULL ,"min_level" NUMERIC,"status_id" NUMERIC,"member_id"
NUMERIC, foriegn key(member_id) references Member_Master(member_id)ON DELETE CASCADE ON
UPDATE CASCADE) [ near "member_id": syntax error ]
Exception Name: NS_ERROR_FAILURE
Exception Message: Component returned failure code: 0x80004005 (NS_ERROR_FAILURE)
[mozIStorageConnection.createStatement]
Please give me the solution. Since Member_Master table is already created and field name is member_id only.
If you are getting no such table exception, the reason for this is that the table is not created.There can be few reasons like
1 ) The command you have used to create the table is is wrong (and could be a typing error also).
2 ) You are adding a table in an already existing database
When Database is created with specific number of tables you can not add more tables to it .
If you want to add more tables, you need to uninstall the application from your emulator and install the application again only then it shall create the new tables by re creating the database.
Or upgrade the database version , it shall drop all the tables once and then recreate the database.
Try uninstalling the app and reinstall it again. it works most of the times.
If you are getting no such table exception, then It is sure that the tables are not getting created.Have You written create Table query in your DatabaseAdapter class or simply adding a table from SqliteManager.
If you are creating tables dynamically, please write CREATE TABLE query and execute Query.

SQLite Error: Constraint Failed

I have a common problem, and have looked at several solutions but haven't seen one that fits this case.
I have a temporary table that is defined as follows:
public static final String GROUP_TABLE_CREATE =
"CREATE TEMP TABLE "+GROUP_TABLE_NAME+" ("
+GROUP_ID_COLUMN_NAME+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+GROUP_GROUP_ID_COLUMN_NAME+" INTEGER NOT NULL UNIQUE, "
+GROUP_COLUMN_NAME+" VARCHAR(64) NOT NULL)";
The table is created without any problems. I then download some data to insert into it and use the following query to insert it:
ContentValues contentValues = new ContentValues();
contentValues.put(WhereWolfOpenHelper.GROUP_GROUP_ID_COLUMN_NAME, groupID);
contentValues.put(WhereWolfOpenHelper.GROUP_COLUMN_NAME, groupName);
db.insert(WhereWolfOpenHelper.GROUP_TABLE_NAME, null, contentValues);
And then I get the following error:
08-05 08:52:37.791: ERROR/Database(847): Error inserting group_name=Friends group_id=2
08-05 08:52:37.791: ERROR/Database(847): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
The error appears twice, and the only data in the database is the group named Friends (there should be two more entries).
I have another table with very similar code that works without any problems, so I'm guessing it's just some silly mistake that I haven't spotted. Anyone got any ideas?
If "constraint failed" than something in table scheme should tell us what is wrong.
I see what it show data what it want to insert, this means what NOT NULL constraint is OK.
In this case I've only one assumption what you already inserted some GROUP_GROUP_ID_COLUMN_NAME with value 2 and UNIQUE constraint is failed because of that.
Are you using a temporary table on purpose? A temporary table dies once the DB connection is closed. If this is the case, the table will get created and the insert will not correspond to any table. So the constraint 19 can correspond to 'Table not found'
You shouldn't pass null values in insert method. Pass empty strings.

Categories

Resources