sqlite3.OperationalError: incomplete input on my code - python

Can someone help me understand what's incomplete about my code, no matter what I try I keep getting the sqlite3.OperationalError: incomplete input. My code is
editor = Tk()
editor.title('Edit Record')
editor.geometry('400x400')
#Creating database
conn = sqlite3.connect('Student_info.db')
c = conn.cursor()
record_id = delete_box.get()
#Query the database
c.execute("SELECT * FROM Student_info WHERE oid ="+(record_id))<-----
records = c.fetchall()
The line that sublime is referring to is the one I've drawn an arrow to, if anyone could help that would be great!

Your syntax for execute() is off. You should be using a prepared statement as the first parameter, followed by a tuple of parameters as the second function parameter:
record_id = delete_box.get()
c.execute("SELECT * FROM Student_info WHERE oid = %s", (record_id,))
records = c.fetchall()

Related

Unable to find a column in sqlite 3 database

I saved my data in databse where I created two columns with master_user and master_password.I inserted a value in my database. But somehow I am unable to find that master_user with my current code. error- sqlite3.OperationalError: no such column: animesh7370
def login(self):
conn = sqlite3.connect("master.db")
cur = conn.cursor()
#conn.execute("CREATE TABLE master_database (master_users TEXT NOT #NULL,master_password
#TEXT NOT NULL)")
#cur.execute("INSERT INTO master_database (master_users,master_password)
#VALUES('animesh7370','A#singh7')")
user = self.root.ids.user.text
password = self.root.ids.password.text
print(type(password))
cur.execute(f"SELECT * FROM master_database WHERE master_user = {user}")
#cur.execute("SELECT * FROM master_database ")
c=cur.fetchone()
for items in c:
print(items)
conn.commit()
conn.close()
Naming problem. You forgot the 's' to master_user.
cur.execute(f"SELECT * FROM master_database WHERE master_users = {user}")
HERE --^
cur.execute("SELECT * FROM master_database WHERE master_users =?" ,(user,))
This is because your resulting SQL looks like this (assuming that user is 'animesh7370'):
SELECT * FROM master_database WHERE master_user = animesh7370
Better use command parameters
select_stmt = "SELECT * FROM master_database WHERE master_users = %s"
cur.execute(select_stmt, (user,))
Note that command parameters are not simply inserted as a string concatenation but are passed to the query with the appropriate data type.
See: Passing parameters to SQL queries
You declared the column as master_users but referred to it as master_user in the select statement. It is usual to use column names in singular.

Python Script to get multi table counts

I'm trying to write a python script to get a count of some tables for monitoring which looks a bit like the code below. I'm trying to get an output such as below and have tried using python multi-dimensional arrays but not having any luck.
Expected Output:
('oltptransactions:', [(12L,)])
('oltpcases:', [(24L,)])
Script:
import psycopg2
# Connection with the DataBase
conn = psycopg2.connect(user = "appuser", database = "onedb", host = "192.168.1.1", port = "5432")
cursor = conn.cursor()
sql = """SELECT COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT count(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
result = cursor.fetchall()
print('Counts:',result)
conn.close()
Current output:
[root#pgenc python_scripts]# python multi_getrcount.py
('Counts:', [(12L,)])
('Counts:', [(24L,)])
Any help is appreciated.
Thanks!
I am a bit reluctant to show this way, because best practices recommend to never build a dynamic SQL string but always use a constant string and parameters, but this is one use case where computing the string is legit:
a table name cannot be a parameter in SQL
the input only comes from the program itself and is fully mastered
Possible code:
sql = """SELECT count(*) from appuser.{}"""
tables = ['oltptransactions', 'oltpcases']
for t in tables:
cursor.execute(sql.format(t))
result = cursor.fetchall()
print("('", t, "':,", result, ")")
I believe something as below, Unable to test code because of certificate issue.
sql = """SELECT 'oltptransactions', COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases', COUNT(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
for name, count in cursor:
print ("")
Or
sql = """SELECT 'oltptransactions :'||COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases :'||COUNT(id) FROM appuser.oltpcases"""
sqls = [sql,sql2]
for i in sqls:
cursor.execute(i)
result = cursor.fetchall()
print(result)

Python Sqlite UPDATE multiple values

Is there a way to do these two updates in a single instruction?
cur.execute("UPDATE table_name1 SET email = 'foo#bar.com' WHERE id = 4")
cur.execute("UPDATE table_name1 SET phone = '0400-123-456' WHERE id = 4")
I've tried all sort of variations but can't get it to work.
Edit: I want to pass email, phone and I'd as parameters.
You're solution opens you up to SQL injections. If you read the first section of the documentation, it specifically says not to do it the way you are proposing:
Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
So you should change your code to something along the following lines:
conn = sqlite3.connect('connex.db')
cur = conn.cursor()
mobileval = '0400-123-456'
emailval = 'foo#bar.com'
constrain = 4
q = "UPDATE licontacts310317 SET (?, ?)
WHERE (?)=(?)"
cur.execute(q, (liemailval, limobileval, id, constrain) )
conn.commit()
conn.close()
I haven't tested it, but hopefully you get the idea =)
The following works: Its just standard SQL at this point.
cur.execute("""UPDATE table_name1
SET email = 'foo#bar.com', phone = '0400-123-456'
WHERE id = 4""")
I was facing a similar issue with my own code and was able to get my code working using the following:
cur.execute("UPDATE licontacts310317 SET liemail=?, limobile=? WHERE id=? ", (liemailval, limobileval, constrain))
Someone else already commented this, but it's better to use the ? placeholder and not the string formatting operations because those leave your db vulnerable to SQL injection attacks (basically, hackers).
OK. I made a solution that works with parameters.
First thanks to David for his original answer. It had a small syntax error (corrected in the comments for that answer) but it was enough to help me work out how to get it working without parametising.
(Note:I think David posted his reply before I edited the question to add the need to working with parameters.)
Then this answer helped me parametise the solution.
Here is my solution to the question. I'm poting it in case someone else has the same problem because I did quite a bit of searching before posting the original question and couldn't find the answer.
conn = sqlite3.connect('connex.db')
cur = conn.cursor()
mobileval = '0400-123-456'
emailval = 'foo#bar.com'
constrain = 4
cur.execute("UPDATE licontacts310317 SET liemail=%s, limobile=%s
WHERE %s=?" % (liemailval, limobileval, id), (constrain,))
conn.commit()
conn.close()
Use Dictionaries!
They seem to work well:
cur.execute(
"""UPDATE table_name1
SET email =:email,
phone =:phone
WHERE id = 4
""",
{"email": "foo#bar.com", "phone": '0400-123-456'}
)
So you can just post a dictionary in like so, provided they contain the keys:
cur.execute(
"""UPDATE table_name1
SET email =:email,
phone =:phone
WHERE id = 4
""",
the_dictionary
)
Where the_dictionary = {"email": "foo#bar.com", "phone": "0400-123-456"}. You can put in as many as you'd like. This seems more readable as well I feel.

How do you read individual values from the same row in a database with sqlite?

I am attempting to read 2 values from the same row in a database but I am only good enough to read the entire line at once. I have added all the code that I think will be relevant:
def find(search, term):
# Helper function for the find function.
with connect("GTINb.db") as db:
cursor = db.cursor()
sql = "select * from GTINb where {} = ?".format(search)
cursor.execute(sql,(term,))
db.commit()
results = cursor.fetchall()
new = str(term)
if results:
results = str(results)
temp = open('temp.txt', 'a')
temp.write(results)
temp.write('\n')
temp.close()
with connect("GTINb.db") as db:
cursor.execute("UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8=(?)",(new,))
cur = cursor.execute("SELECT stockcur from GTINb by (?)",(new,))
re = cursor.execute("SELECT restock from GTINb by (?)",(new,))
if cur < re:
cursor.execute("UPDATE GTINb SET stockcur=stockcur+10 WHERE GTIN8=(?)",(new,))
return print('More stock has been ordered in as stocks were low')
else:
return
else:
temp = open('temp.txt', 'a')
temp.write('Product not found')
temp.write('\n')
temp.close()
return
I am currently getting the error sqlite3.OperationalError: near "(": syntax error, and have tried replacing the '(?)' with %s, (%s) and ? with no success, coming up with the following error messages:
sqlite3.OperationalError: near "12345670": syntax error // where 12345670 was the input represented by new
sqlite3.OperationalError: near "(": syntax error
sqlite3.OperationalError: near "?": syntax error
Is there another way of doing this or have I made a simple mistake?
None of the SQL statements you've written are valid SQL. Please consult the SQLite documentation for the valid syntax.
Briefly:
UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8=(?)
SELECT stockcur from GTINb by (?)
SELECT restock from GTINb by (?)
should be
UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8 = ?
SELECT stockcur FROM GTINb WHERE GTIN8 = ?
SELECT restock FROM GTINb WHERE GTIN8 = ?
although the first one will probably execute with the unneeded parentheses.
Once you have your SQL working you will find that the second two statements can be combined into
SELECT stockcur, restock FROM GTINb WHERE GTIN8 = ?
which I believe is what you were asking about.

Python pg8000 SQL, INSERT INTO... doesn`t write Information into table

I am connecting to a SQL-Database (heroku) and I am able to create a table there.
When inserting some information I don`t get any error.
But when I want to read the data it returns "None".
What am I doing wrong?
import pg8000
conn = pg8000.connect(user="username", password="password",
host="hostAddress", port=5432, database="database",
ssl=True)
cursor = conn.cursor()
def createTable():
cursor.execute("create table test (ID INT, TITLE TEXT)")
conn.commit()
def dataEntry():
cursor.execute("INSERT INTO test VALUES(1, 'blablabla')")
conn.commit()
def readTable():
print (cursor.execute("SELECT * FROM test "))
#createTable()
dataEntry()
readTable()
Thanks a lot for any help!
basically the mistake was the projection of the result..
the table was created correctly,
but instead:
print (cursor.execute("SELECT * FROM test "))
doing:
result = (cursor.execute("SELECT * FROM test "))
print (results)
that does the job..

Categories