Continue executing sql statements if error found python sqlite3 - python

I have a file containing sql commands and I want to execute the commands given in the file and if any command throws any error then ignore the error and execute the next command.
Here is a sample file:
drop table department;
drop table classroom;
create table classroom
(building varchar(15),
room_number varchar(7),
capacity numeric(4,0),
primary key (building, room_number)
);
create table department
(dept_name varchar(20),
building varchar(15),
budget numeric(12,2) check (budget > 0),
primary key (dept_name)
);
For eg. if the classroom table doesn't exists then the drop table command will produce an error and the program will terminate. I want that the program keep running and execute all commands in the file.
The problem I'm facing is that the create table command is in multiple lines so I don't know how to execute that.

Take a look at the sqlite3 manual:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
with open('PATH_TO_SQL_FILE', 'r') as fp:
text = fp.read().split(';')
for command in text:
try:
cur.execute(command)
except sqlite3.Error:
pass

import sqlite3
#define connection and cursor
connection = sqlite3.connect ('test_db')
cursor =connection.cursor()
command1 ="""create table classroom
(building varchar(15),
room_number varchar(7),
capacity numeric(4,0),
primary key (building, room_number)
)"""
cursor.execute(command1)
command2 ="""create table department
(dept_name varchar(20),
building varchar(15),
budget numeric(12,2) check (budget > 0),
primary key (dept_name)
)"""
cursor.execute(command2)

Related

Storing information in a file, Python

I'm making a car rental console base program in Python where I need to save data about cars I store (such as brand, registration number etc).
What would be the ideal type of file for such a thing, and how to iniciate it?
You can use sqlite3 to store the information.
You can create a table with columns such as brand,registration number etc.
If the registration number is unique to single type of car you can also take care of that condition in sqlite3
syntax is as simple as:
For creating table:
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute('''CREATE TABLE COMPANY
(REGISTRATION_NO INT PRIMARY KEY NOT NULL,
BRAND TEXT NOT NULL
);''')
print "Table created successfully";
conn.close()
For insertion:
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.execute("INSERT INTO COMPANY (REGISTRATION_NO,BRAND) \
VALUES (1, 'PAGANI')");
conn.commit()
conn.close()
For more information:
https://docs.python.org/2/library/sqlite3.html

Running a entire SQL script via python

I'm looking to run the following test.sql located in a folder on my C: drive. I've been playing with cx_Oracle and just can't get it to work.
test.sql contains the following.
CREATE TABLE MURRAYLR.test
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50)
);
CREATE TABLE MURRAYLR.test2
( customer_id number(10) NOT NULL,
customer_name varchar2(50) NOT NULL,
city varchar2(50)
);
This is my code:
import sys
import cx_Oracle
connection = cx_Oracle.connect('user,'password,'test.ora')
cursor = connection.cursor()
f = open("C:\Users\desktop\Test_table.sql")
full_sql = f.read()
sql_commands = full_sql.split(';')
for sql_command in sql_commands:
cursor.execute(sql_command)
cursor.close()
connection.close()
This answer is relevant only if your test.sql file contains new lines '\n\' characters (like mine which I got from copy-pasting your sql code). You will need to remove them in your code, if they are present. To check, do
print full_sql
To fix the '\n's,
sql_commands = full_sql.replace('\n', '').split(';')[:-1]
The above should help.
It removes the '\n's and removes the empty string token at the end when splitting the sql string.
MURRAYLR.test is not acceptable table name in any DBMS I've used. The connection object the cx_oracle.connect returns should already have a schema selected. To switch to a different schema set the current_schema field on the connection object or add using <Schemaname>; in your sql file.
Obviously make sure that the schema exists.

SQLite-Manager on Firefox and Python

I have written a small test application using SQLite with Python 3.3:
import sqlite3
MDB = sqlite3.connect('D:\MDB.db') # create the db object
cursor = MDB.cursor() # assign a cursor
cursor.execute('''CREATE TABLE IF NOT EXISTS section (
Code INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
Description TEXT )
''')
cursor.execute('''DELETE FROM section''') # delete contents for reruns
cursor.execute('''INSERT INTO section
(Description)
VALUES (?)
''', ('Abdul, Paula',))
cursor.execute('''INSERT INTO section
(Description)
VALUES (?)
''', ('ABWH',))
print('Results:\n')
cursor.execute('''SELECT * FROM section''')
selection = cursor.fetchall()
for row in selection:
print('\t', row)
The SELECT statement shows the results expected (seeming to indicate that the row exists), but if I connect to the database with SQLite-Manager, the table exists but is empty, and if I try the same query with another script connected to the database, nothing is returned. Can anyone please explain what I am doing wrong?
You're not saving changes (calling MDB.commit).

Psycopg2 command hangs, possibly because of table name?

The code below hangs (even ctrl-C won't stop it, I have to close the terminal) when it tries to create the second table, and I'm not sure why. The first table is created successfully (I can see it in psql with \dt cyanobacteria.*). A simple solution would be to rename the table, but I'm trying to restore someone else's code to working order and I'd have to go through changing lots of stuff. And he had it working once, so it ought to work for me!
I've created a database called 'genomes', a user called 'genomes_admin' and a schema called 'cyanobacteria'. Then I try to make some tables:
#!/usr/bin/python
import psycopg2
psql = "dbname='genomes' user='genomes_admin'"
schm = 'cyanobacteria'
conn = psycopg2.connect(psql)
cur = conn.cursor()
cur.execute('''SET search_path TO %s''', (schm,))
conn.commit()
cur.execute('''CREATE TABLE IF NOT EXISTS testnm(blah text, length int) ''')
print 'created testnm'
conn.commit()
print 'committed'
cur.execute('''CREATE TABLE IF NOT EXISTS genomes(blah text, length int) ''') # hangs here
print 'created genomes' # this line never executes
conn.commit()
print 'committed'
cur.close()
conn.close()

How do I insert data into table?

I have created table using this create command as:
CREATE TABLE test_table(id INT PRIMARY KEY,name
VARCHAR(50),price INT)
i want to insert into this table wherein values are stored already in variable
bookdb=# name = 'algorithms'
bookdb-# price = 500
bookdb-# INSERT INTO test_table VALUES(1,'name',price);
I get the following error:
ERROR: syntax error at or near "name"
LINE 1: name = 'algorithms'
Can anyone point out the mistake and propose solution for the above?
Thanks in advance
Edit:
import psycopg2
import file_content
try:
conn = psycopg2.connect(database='bookdb',user='v22')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS book_details")
cur.execute("CREATE TABLE book_details(id INT PRIMARY KEY,name VARCHAR(50),price INT)")
cur.execute("INSERT INTO book_details VALUES(1,'name',price)")
conn.commit()
except:
print "unable to connect to db"
I have used the above code to insert values into table,variables name and price containing the values to be inserted into table are available in file_content python file and i have imported that file.The normal INSERT statement takes values manually but i want my code to take values which are stored in variables.
SQL does not support the concept of variables.
To use variables, you must use a programming language, such as Java, C, Xojo. One such language is PL/pgSQL, which you can think of as a superset of SQL. PL/PgSQL is often bundled as a part of Postgres installers, but not always.
I suggest you read some basic tutorials on SQL.
See this similar question: How do you use script variables in PostgreSQL?
don't have postgres installed here, but you can try this
import psycopg2
import file_content
try:
conn = psycopg2.connect(database='bookdb',user='v22')
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS book_details")
cur.execute("CREATE TABLE book_details(id INT PRIMARY KEY,name VARCHAR(50),price INT)")
cur.execute("INSERT INTO book_details VALUES(1, '%s', %s)" % (name, price))
conn.commit()
except:
print "unable to connect to db"
If you are using PSQL console:
\set name 'algo'
\set price 10
insert into test_table values (1,':name',:price)
\g

Categories

Resources