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()
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.
A little background I am doing this in python 2.7 for the reason of Alexa Rank through SeoLib but am completely open to updating if that would help this issue or possibly solve future issues.
Now this program sorts through sites that I have in a predetermined csv that looks like the following:
site
00rbt.com
I am specifically getting the following error:
File "igorPanda.py", line 84, in <module>
update_site(site,cur_ip,cur_rank,cur_hash)
File "igorPanda.py", line 30, in update_site
(site))
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied.
Where this error is occuring is:
def update_site(site,cur_ip,cur_rank,cur_hash):
conn = sqlite3.connect('/root/Database/Sites.db')
cursor = conn.cursor()
with conn:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)",
(site))
record = cursor.fetchone()
if record[0] == 1:
cursor.execute("UPDATE sites SET cur_ip = ?, cur_rank = ?, cur_hash = ? WHERE site = ?",
(cur_ip,cur_rank,cur_hash,site))
else:
cursor.execute("INSERT into sites values (?,?,?,?,?,?,?,?)",
(site,cur_ip,None,cur_rank,None,None,cur_hash,None))
My entire code except imports is:
#Updates the DB
def update_site(site,cur_ip,cur_rank,cur_hash):
conn = sqlite3.connect('/root/Database/Sites.db')
cursor = conn.cursor()
with conn:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)",
(site))
record = cursor.fetchone()
if record[0] == 1:
cursor.execute("UPDATE sites SET cur_ip = ?, cur_rank = ?, cur_hash = ? WHERE site = ?",
(cur_ip,cur_rank,cur_hash,site))
else:
cursor.execute("INSERT into sites values (?,?,?,?,?,?,?,?)",
(site,cur_ip,None,cur_rank,None,None,cur_hash,None))
#Moves CSV for Historical Savings
bashmove = "mv top.csv /root/Desktop/scripts/results-igor/top-$(date +%m-%d-%Y).csv"
#Sets file with all sites to variable
filename='/root/Desktop/scripts/sorted.csv'
#Creates hash algorithm for later use
hasher = hashlib.sha256()
sess = requests.Session()
x = datetime.datetime.now()
date = x.strftime('%Y-%m-%d')
regex = r"^(?:https?:)?(?:\/\/)?(?:[^#\n]+#)?(?!www\.)?([^:\/\n]+)\w*\.\b(com|org|co|be|de|br|(\w+\b))" #regex to get stripepd website no https://www. or anything afte$
df = pd.DataFrame()
df = df.append(pd.read_csv(filename), ignore_index=True)
ip = "NOT FOUND"
for i in df.index:
#print(i)
site = df['site'][i]
try :
ip = socket.gethostbyname(site)
page = requests.get('http://' + df['site'][i], timeout=5)
hasher.update((page.text).encode('utf-8'))
except: #ignore errors if the site is bad
pass
try :
alexa_rank = seo.get_alexa('http://{}'.format(site)) #seolib gets the alexa ranking
#alexa_rank = None
except:
pass
site = site
cur_ip = ip
cur_rank = alexa_rank
cur_hash = hasher.hexdigest()
update_site(site,cur_ip,cur_rank,cur_hash)
rd = call(["/root/Desktop/scripts/./rDNSlookup.sh", site, ip]) #call bash script to get reverse DNS of ip
wi = call(["/root/Desktop/scripts/./whois.sh", site]) #call bash script to print host info
with open('/root/Desktop/scripts/IGOR_His/'+ date + 'sites.csv', 'a') as f:
print >> f, 'site: ',site,', ip: ',ip,', rank: ',alexa_rank, ', hash', cur_hash
shutil.copy("/root/Database/Sites.db", "/var/www/html/sites/Sites.db")
The table has the following columns:
site,cur_ip,prev_ip,cur_rank,prev_rank,play,cur_hash,prev_hash
TL;DR: use (site,)
In detail:
cursor.execute expects the second paramter to be an iterable.
When your code says:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)", (site))
Then (site) is not a tuple - you probably meant to convert it to a tuple by wrapping it in ().
So what you meant/want is:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)", (site,))
Notice the extra ,!
To avoid this tuple confusion, you can also use a list:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)", [site])
The issue in even more detail:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)", (site))
is the same as:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)", site)
is the same (in your case) as:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)", "00rbt.com")
The string 00rbt.com is used as iterable, and since it has 9 characters, you get the error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 9 supplied.
You get this error, because here:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)", (site))
you should pass, as the 2nd argumnet of execute() a tuple and not just a string.
This is easily fixed by adding a comma like this:
cursor.execute("SELECT EXISTS(SELECT * from sites WHERE site = ?)", (site,))
But, if your version of SQLite is 3.24.0+, you should consider taking a different approach by choosing UPSERT as the method to do what you want.
You want to insert a new row if the site value does not exist in the table or update the existing row if it does exist.
So, assuming there is already a unique constraint for the column site, you can do it more efficiently with:
sql = """
INSERT into sites values (?,?,?,?,?,?,?,?)
ON CONFLICT(site) DO UPDATE SET
cur_ip = EXCLUDED.cur_ip, cur_rank = EXCLUDED.cur_rank, cur_hash = EXCLUDED.cur_hash
"""
cursor.execute(sql, (site,cur_ip,None,cur_rank,None,None,cur_hash,None))
I want to update one table in mysql which has 3 rows
what i want is to update any row with update command but this has to be happened only when there exists a particular row
i.e.if i update it like updatedata = "update table12 set name='Dhiraj', city='Delhi' where id=25"
then it should give me an error
Here is my code:
import pymysql
db = pymysql.connect('localhost','root','','firstdb')
print("database connected successfully")
cur = db.cursor()
updatedata = "update table12 set name='Dhiraj', city='delhi' where id=25"
if updatedata:
try:
cur.execute(updatedata)
db.commit()
print("Data updated successfully...")
except:
print("Something went wrong!")
else:
print("There is no any data you entered!")
cur.execute() returns the number of affected rows:
https://pymysql.readthedocs.io/en/latest/modules/cursors.html#pymysql.cursors.Cursor.execute
So you should be able to do something like:
updated_rows = cur.execute(updatedata)
if updated_rows > 0:
print("success")
else:
print("no matching rows")
This updates all rows based on a condition over the same table
UPDATE tbl
SET field_to_update = CASE
WHEN (SELECT COUNT(*) FROM (SELECT * FROM tbl) AS copy WHERE copy.field=<condition> HAVING COUNT(*)>0) THEN "this_value_if_true"
ELSE field_to_update
END
db = sqlite3.connect("SQL database")
cursor = db.cursor()
query = 'DELETE FROM Item WHERE ItemID = {}'.format(self.ID)
cursor.execute(query)
db.commit()
cursor.close()
unsure why this error is coming up as my code seems to be correct.
The error is that whatever value self.ID is the error states that that there is no such column that is that value.
For example self.ID = "hello"
The error would be:
no such column: "hello"
Any help would be appreciated, thanks
Your query looks like:
DELETE FROM Item WHERE ItemID = hello
The error message is helpful in this case.
Instead do:
db = sqlite3.connect("SQL database")
cursor = db.cursor()
query = 'DELETE FROM Item WHERE ItemID = ?'
cursor.execute(query, (self.ID,))
db.commit()
cursor.close()
Notes:
The parameter placeholder for sqlite3 is ?.
The parameter value should be the second argument to .execute()
That parameter should be passed to .execute() as a sequence. A tuple is fine.