import sqlite3
def create_table():
connection = sqlite3.connect('lite.db')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS shop (item TEXT, quantity INTEGER, price REAL)') #you write the SQL code in between brackets
connection.commit()
connection.close()
create_table()
def insert(item,quantity,price):
connection = sqlite3.connect('lite.db')
cursor = connection.cursor()
cursor.execute("INSERT INTO shop VALUES (?,?,?)", (item,quantity,price)) # inserting data
connection.commit()
connection.close()
insert('Wine Glass', 10, 5)
insert('Coffe Cup', 5, 2)
insert('Plate', 20, 10)
def view():
connection = sqlite3.connect('lite.db')
cursor = connection.cursor()
cursor.execute('SELECT ALL FROM shop ')
rows = cursor.fetchall()
connection.close()
return rows
def delete_item(item):
connection = sqlite3.connect('lite.db')
cursor = connection.cursor()
cursor.execute("DELETE * FROM shop WHERE item = ?", (item,)) # inserting data
connection.commit()
connection.close()
print(view())
delete_item('Wine Glass')
print(view())
Error Message:
cursor.execute('SELECT ALL FROM shop ')
sqlite3.OperationalError: near "FROM": syntax error
It used to work and then I added the delete function and now it gives me this syntax error, I didn't even make any changes on that function. The code is based on a Udemy tutorial, and with the same changes applied on the video I got this error message but the tutor did not. As you can guess I am pretty new to this stuff and I cant decipher the error message, or at least if it means any more than the obvious. So yeah thanks in advance
SELECT ALL should be SELECT ALL * or just SELECT * to select all columns in all rows. See the syntax here.
DELETE * FROM shop should be DELETE FROM shop. DELETE deletes whole rows, it doesn't need a list of columns. See the syntax here.
Related
I am struggling to establish a connection inside data iteration. Means I am running a select query to postgres and iterating the return data. after some transformation I am writing it to another table. But it is not working. Sample python code is below.
conn = pgconn(------)
cursor = pgconn.Cursor()
query1 = "select * from table"
query2 = "select * from table2 where Id=(%s);"
cursor.execute(query1)
result = query1.fetchall()
for row in result:
If row.a == 2:
cursor.execute(query2, [row.time])
In the above python code I can't able to extract the data by running query2 and passing query1 result as a parameter. It seems cursor is blocked by the query1 so query2 execution is not happening. Please some one help in this issue.
First of all you can write a join statement to do this and can get the data easily
select * from table join table2 where table2.id == table.time
Also why this is not working maybe because the cursor object is getting override inside the for loop and thus the query results get changed.
Use RealDictCursor, and correct the syntax on your inside call to execute():
import psycopg2
import psycopg2.extras
conn = pgconn(------)
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
query1 = "select * from table"
query2 = "select * from table2 where Id=(%s);"
cursor.execute(query1)
result = query1.fetchall()
for row in result:
If row.a == 2:
cursor.execute(query2, (row['time'],))
1. install psycopg2 and psycopg2.extras. ( pip install)
Then set up your Postgres Connection like:
def Postgres_init(self):
try:
conn = psycopg2.connect(host=os.environ['SD_POSTGRES_SERVER'],
user=os.environ['SD_POSTGRES_USER'],
password=os.environ['SD_POSTGRES_PASSWORD'],
port=os.environ['SD_POSTGRES_PORT'],
database=os.environ['SD_POSTGRES_DATABASE'])
logging.info("Connected to PostgreSQL")
except (Exception, psycopg2.Error) as error:
logging.info(error)
2. Connect your Cursor with the defined connection
cursor = conn.cursor()
3. Execute your query:
cursor.execute("""SELECT COUNT (column1) from tablename WHERE column2 =%s""", (
Value,)) # Check if already exists
result = cursor.fetchone()
Now the value is stored in the "result" variable. Now you can execute the next query like:
cursor.execute("""
INSERT INTO tablename2
(column1, column2, column3)
VALUES
(%s, %s, %s)
ON CONFLICT(column1) DO UPDATE
SET
column2=excluded.column2,
column3=excluded.column3;
""", (result, column2, column3)
)
Now the result of query 1 is stored in the second table in the first column.
Now you can close your connection:
conn.close()
I have a problem getting the query results from my Python-Code. The connection to the database seems to work, but i always get the error:
"InterfaceError: No result set to fetch from."
Can somebody help me with my problem? Thank you!!!
cnx = mysql.connector.connect(
host="127.0.0.1" ,
user="root" ,
passwd="*****",
db="testdb"
)
cursor = cnx.cursor()
query = ("Select * from employee ;")
cursor.execute(query)
row = cursor.fetchall()
If your problem is still not solved, you can consider replacing the python mysql driver package and use pymysql.
You can write code like this
#!/usr/bin/python
import pymysql
db = pymysql.connect(host="localhost", # your host, usually localhost
user="test", # your username
passwd="test", # your password
db="test") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
query = ("SELECT * FROM employee")
# Use all the SQL you like
cur.execute(query)
# print all the first cell of all the rows
for row in cur.fetchall():
print(row[0])
db.close()
This should be able to find the result you want
add this to your code
for i in row:
print(i)
you did not print anything which is why that's not working
this will print each row in separate line
first try to print(row),if it fails try to execute using the for the loop,remove the semicolon in the select query statement
cursor = connection.cursor()
rows = cursor.execute('SELECT * FROM [DBname].[dbo].TableName where update_status is null ').fetchall()
for row in rows:
ds = row[0]
state = row[1]
here row[0] represent the first columnname in the database
& row[1] represent the second columnname in the database & so on
I'm trying to insert a large list of English words into a database, and get the results back. However, when I query the database, it is returning nothing. I have omitted the input of the text file into the database for this example, and have only inserted a single string. However this is not showing up in the query either. Here is my code:
import sqlite3
def get_database_connection():
return sqlite3.connect("myDatabase.db")
def commit():
connection = get_database_connection()
connection.commit()
connection.close()
def table_exists(table):
cursor = get_cursor()
cursor.execute(''' SELECT count(name) FROM sqlite_master WHERE type='table' AND name='{0}' '''.format(table))
my_bool = cursor.fetchone()[0]
return my_bool
def get_cursor():
connection = sqlite3.connect("myDatabase.db")
cursor = connection.cursor()
return cursor
def create_table(table):
if table_exists(table):
return
cursor = get_cursor()
cursor.execute("""CREATE TABLE {0}(
word text
)""".format(table))
def insert_english_words():
#english_words = "english.txt"
#words = process_words(english_words)
table = "english"
create_table(table)
cursor = get_cursor()
cursor.execute("INSERT INTO english VALUES ('HELLO')")
#for word in words:
#cursor.execute("INSERT INTO english VALUES ('{0}')".format(word))
commit()
def get_data():
cursor = get_cursor()
cursor.execute("SELECT * FROM english")
rows = cursor.fetchall()
for row in rows:
print(row)
def run():
get_database_connection()
insert_english_words()
get_data()
print("Done")
run()
You have to commit after creation of table.
Maintain one single connection object across your script lifecycle. You are creating a new connection every single time.
I'm learning sqlite3 with python, but I've been facing this error: "sqlite3.OperationalError: no such table: store". How do I get around this?
import sqlite3
def create_table(): #function to create the table
conn = sqlite3.connect('lite.db')
cur = conn.cursor() # creating th cursor object
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(item, quantity, price ): #function to insert into the table
conn = sqlite3.connect('lite.db')
cur = conn.cursor() # creating th cursor object
cur.execute("INSERT INTO store VALUES(?,?,?)", (item, quantity, price))
conn.commit()
conn.close()
insert("biscuits",500,20000)
def view():
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
return rows
conn.close()
print(view())
You forgot to call the create_table method before calling insert. As you haven't called the the create_table method the insert method tries to insert a record to a non existing table.
The solution is simply to call the create_table method before insert as follows:
create_table() # Add this line before the insert
insert("biscuits", 500, 20000)
I tried to fill a table in a database using MySQLdb. It did not give any errors, and once gave the warning
main.py:23: Warning: Data truncated for column 'other_id' at row 1
cur.execute("INSERT INTO map VALUES(%s,%s)",(str(info[0]).replace('\n',''), str(info[2].replace('\n','').replace("'",""))))
so I thought it was working fine. However, when it was finished and I did a row count it turned out that nothing was added. Why was the data not added to the database? The code is below
def fillDatabase():
db = MySQLdb.connect(host="127.0.0.1",
user="root",
passwd="",
db="uniprot_map")
cur = db.cursor()
conversion_file = open('idmapping.dat')
for line in conversion_file:
info = line.split('\t')
cur.execute("INSERT INTO map VALUES(%s,%s)",(str(info[0]).replace('\n',''), str(info[2].replace('\n','').replace("'",""))))
def test():
db = MySQLdb.connect(host="127.0.0.1",
user="root",
passwd="",
db="uniprot_map")
cur = db.cursor()
cur.execute("SELECT COUNT(*) FROM map")
rows = cur.fetchall()
for row in rows:
print row
def main():
fillDatabase()
test()
You need to do a db.commit() after adding all of the entries. Even if the update is not transactional, the DBAPI imposes an implicit transaction on every change.