sqlite - how to check if table exists before completing inserts? [duplicate] - sqlite

This question already has answers here:
How do I check in SQLite whether a table exists?
(30 answers)
Closed 3 years ago.
What is the best SQL for a SQLite database to effectively do:
If Database Table Exists then
- create table
- insert row
- insert row (i.e. for startup data)
end

To check that your table exists or not, you can use:
SELECT * FROM sqlite_master WHERE name ='myTable' and type='table';

You can let Sqlite itself check this out for you:
CREATE TABLE IF NOT EXISTS <table_name> ...;
Follow link for documentation:
https://sqlite.org/lang_createtable.html

Use this code
SELECT name FROM sqlite_master WHERE type='table' AND name='yourTableName';
if returning array count is equal to 1 its means table exist else not exist.

Related

Add constraints to tables in Sqlite [duplicate]

This question already has an answer here:
Add ON DELETE CASCADE behavior to an sqlite3 table after it has been created
(1 answer)
Closed 5 years ago.
I am adding constraints to tables in Sqlite as following:
alter table TagsI18N
add constraint FK_TagsI18N_TagId foreign key (TagId) references Tag(Id) on delete cascade on update cascade,
constraint FK_TagsI18N_LanguageCode foreign key (LanguageCode) references [Languages](Code) on delete cascade on update cascade;
I was using this code in SQL Server database but is not being accepted in SQLite.
How can I create such a constraint in Sqlite?
The ALTER command in SQLite3 is limited to adding columns or renaming tables, so you cannot do this. Instead, you must re-create the table with the desired constraints.

How to know last id of SQLite database [duplicate]

This question already has answers here:
Predict next auto-inserted row id (SQLite)
(11 answers)
Closed 6 years ago.
I have a database in SQLite that I'll be using to store restaurants information for a website.
The website will allow users to insert new restaurants in the dabase (through php).
My question is, given that each row in a table in the database has its id attribute (which is the primary key), how can I know what id should the next item I'm going to store in the database have?
If the last item added to the database has the id 50, then the next restaurant a user tries to add should have the id 51, but how can I have access to this?
Here's my SQLite Restaurant table:
CREATE TABLE Restaurant (
id NUMBER PRIMARY KEY NOT NULL,
name NVARCHAR2(20) NOT NULL,
description NVARCHAR2(20),
address NVARCHAR2(20) NOT NULL,
priceRange NUMBER NOT NULL REFERENCES PriceRange(id) ON DELETE SET NULL ON UPDATE CASCADE
);
Thanks in advance!
Since you've tagged the question with php, you should be able to use SQLite3::lastInsertRowID().
Alternatively, a pure SQLite solution is the last_insert_rowid() function.

Dropping Referencing and Referenced tables in SQLite [duplicate]

This question already has an answer here:
Error when trying to update sqlite database in android
(1 answer)
Closed 6 years ago.
Working with the artist/tracks example at https://www.sqlite.org/foreignkeys.html
I'd like to drop both tables. I would think that if I first drop tracks (which References artist) I could then drop artists:
stat_5.executeUpdate("drop table if exists tracks;");
stat_6.executeUpdate("drop table if exists artist;");
But this issues an exception "SQLException: foreign key constraint failed"
What am I missing?
The documentation says:
If foreign key constraints are enabled, a DROP TABLE command performs an implicit DELETE FROM command before removing the table from the database schema. [...] If the implicit DELETE FROM executed as part of a DROP TABLE command violates any immediate foreign key constraints, an error is returned and the table is not dropped.
Remove the data in the correct order so that all intermediate steps are valid.
Or just disable foreign constraint checking.

InnerJoin Query giving "Failed to enable constraints" error [duplicate]

This question already has answers here:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
(26 answers)
Closed 8 years ago.
I have this query running against 2008R2. tblJoin is the table in between two tables(tblIncident and tblPatron) for many-to-many relationship.
While I am building the query in VS2012, in the Query Builder window when I execute the query it runs fine and gives me the desired results. However in the last step when I click on TestQuery and enter the parameter it gives an error:
"Failed to enable constraints.."
I checked the datatype and they all match against each other against the tables,
SELECT tblIncident.Inci_ID,
_tblJoin.PatronID,
_tblJoin.LName,
_tblJoin.FName,
_tblJoin.MI
FROM tblJoin INNER JOIN
tblIncident ON tblJoin.InciID = tblIncident.Inci_ID AND tblJoin.InciID = tblIncident.Inci_ID
WHERE (tblIncident.Inci_ID = #Inci_ID)
You need Check all the MaxLength property of the columns in your DataTable.
The column that I changed from "nvarchar(512)" to "nvarchar(MAX)" still had the 512 value on the MaxLength property so I changed to "-1" and it works!!.
You can solve this issue from this discussion
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints
There have many answers ....
Thanks Ramesh and Vignesh. Vignesh's comment made me think about the duplicate foreign key. So I kept the query but removed the foreign key (Incident ID), that made it worked. This is how my query looks like:
SELECT tblJoin.PatronID, tblJoin.LName, tblJoin.FName, tblJoin.MI FROM tblJoin
INNER JOIN tblIncident ON tblJoin.InciID = tblIncident.Inci_ID
WHERE (tblIncident.Inci_ID = #Inci_ID)

Is it safe to run 'create table ...' multiple times?

I have a parser that parses XML file into SQLite database, and the current implementation generates the 'create table xyz ...' even the table is already existed.
Is this OK? I mean, is this OK to run 'create table' even when the table exists in db?
If not, is there easy way to check the names of tables (and its contents) that SQLite db has?
What you are searching for is CREATE TABLE IF NOT EXISTS and the FAQ entry How do I list all tables/indices contained in an SQLite database.
Creating a table without the "IF NOT EXISTS" option will lead to an error.
You can DROP TABLE before CREATE TABLE, you can safety DROP TABLE who don't exists then you don't must checking for TABLE existence before DROP.
SQLite has a "IF NOT EXISTS" clause so that you can throw a "CREATE TABLE" at the database and it will ignore it if it already exists. For example:
CREATE TABLE IF NOT EXISTS mytable ( id INTEGER );
The URL to the documentation about this is at: http://www.sqlite.org/lang_createtable.html

Resources