import sqlite3
connection = sqlite3.connect("...")
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS ...")
How can I find out, after executing the CREATE TABLE IF NOT EXISTS, whether the table was created or already in place?
The only way to check is by removing the IF NOT EXISTS part of the query and checking for a sqlite3.OperationalError with a message of the form "table $tablename already exists". I wouldn't trust the error message to be stable, but Python apparently does not supply an error code along with the exception.
The safest thing to do would be to begin a transaction and query the sqlite_master table beforehand, create the table if there were no results, then commit the transaction.
Note that none of these solutions will work correctly if the table you are attempting to create has a different schema than the one that exists in the database; database migrations are more complicated and usually require case-by-case handling.
EDIT: Updated answer
It sounds like you don't know beforehand what tables might exist, what those tables have in them (if anything), or have a way to check beforehand if tables exist.
To check if a table was created after using the IF NOT EXISTS clause on a CREATE TABLE command, you could try one of these:
Make the "new" table have at least one column name that is guaranteed to be different from the old table. After the CREATE TABLE command, you select the column guaranteed to be new.
CREATE TABLE newTable IF NOT EXISTS (column1 INTEGER, somethingUnique INTEGER)
SELECT somethingUnique FROM newTable
If you don't get back an error from selecting somethingUnique, then you know that you have created a new table, else the table already existed. If you end up creating a new table and do not want that somethingUnique column anymore, then you can just delete that column.
Even if you don't want to make a somethingUnique column, there is the possibility that if the old table existed, it would have at least one row in it already. All you have to do is select anything from the table. If nothing returned, then you may or may not be dealing with your new table (so go back to suggestion 1). If something does get returned, then you know that you are dealing with an old table.
Old answer
One way to see if the table was created (or exists) is to go into a terminal, navigate to the directory where your database is, and then use sqlite commands.
$ sqlite3
sqlite> .open yourDatabase.db
sqlite> SELECT * FROM theTableYouWantedToCreate;
If the table does not exist, you would get back the following error:
Error: no such table: theTableYouWantedToCreate
If the table did exist, obviously it would return everything that is in the table. If nothing is in the table (since you just created it), sqlite will give you back another prompt, indicating that the table does indeed exist.
Related
I've created a global temporary table in sql developer from Python, using the cx_Oracle package. After creation, the table shows up in my SQL developer application, however INSERT statements produce no records.
I've created a cursor with a working connection(as evidenced by the fact that the tables are successfully created). In addition, I use the standard syntax for the insert.
I've tried a variety of INSERT statements but none work
cur = connection.cursor()
cur.execute("INSERT INTO table(column) VALUES(example)")
con.commit()
I would expect to see the data I've inserted show up. However when I select * from the table, there is no record inserted. I am able to successfully insert directly from the SQL developer application, so I'm not sure what might be causing the discrepancy.
Rows added to a global temporary table are only available to the session that created them. Another session, like your SQL Developer session, cannot see them. You have the option of creating the GTT so that rows are deleted at the end of a transaction, or until the session is closed.
See https://oracle-base.com/articles/misc/temporary-tables
An EXISTS is no good since I need to know whether this particular function was the reason behind a successful Table creation or not, not whether the table exists (since it might already exist from somewhere else). If the function successfully created the table, something will happen. If it didn't (the table already exists, doesn't exist but table creation still failed) then nothing will happen.
It's easy to check if SELECT successfully selected something (eg: c.fetchone()[0] > 0), it's easy to check if UPDATE succesfully updated something (eg: c.rowcount>=1), how to easily check if CREATE TABLE successfully created a table?
Hello I am using my second computer to gather some data and insert it into the SQL database. I set up everything when it comes to reading and writing the database remotely, and I can insert new rows just by using the normal SQL.
With pyodbc I can read tables, but when I insert new data, nothing happens. No error message, but also no new rows in the table.
I wonder if anyone has faced this issue before and knows what the solution is.
The cursor.execute() method only prepares the SQL statement. Then, since this is an INSERT statement, you must use the cursor.commit() method for the records to actually populate your table. Likewise for a DELETE statement, you need to commit, as well.
Without more perspective here, I can only assume that you are not committing the insert.
Notice, similarly, that when you run cursor.execute("""select * from yourTable"""), you need to run cursor.fetchall() or another fetch statement to actually retrieve and view your query.
I am using Python 2.7 and SQLite3.
When I starting work with DB I want to check - does my database is empty or on not. I mean does it already have any tables or not.
My idea is to use the simple SELECT from any table. And wrap this select in try:exception block. So if exception was raised then my DB is empty.
Maybe someone know the better way for checking?
SELECT name FROM sqlite_master
while connected to your database will give you all the tables names. you can then do a fetchall and check the size, or even contents of the list. not try/catch necessary (the list will be empty if the database doesn't contain any tables)
I have a sqlite3 database file with multiple tables, each one with different values, what i want to do now is to check if a value already exists in any table when inserting it to the table and if it already exists returns an error or something.
This is because I'm doing a program t help nurses have a database with their patient and check if a patient has already been inserted into the database, I dont post any code because i'm gathering all the information needed before programming anything to avoid spaghetti code
Try adding a constraint to each or just one of your columns so I doesn't allow duplicates to be added
Like this:
CONSTRAINT <Constraint Name> UNIQUE (<column1>,<column2>)
Then in your code you could catch the SQL exception and return a custom message