I'm trying to test a small piece of code I wrote to search a column of a table for a specific string. The code should search the Users column of the LoginInfo table and print out the result. I have tried two versions of this code but both get different errors.
VERSION ONE:
import sqlite3
import sys
Username = "('Hello1',)"
print(Username)
connection= sqlite3.connect("Logininfo.db")
c = connection.cursor()
c.execute('''SELECT Username FROM LoginInfo WHERE Username=Hello1''')
for row in c :
print(row)
VERSION ONE ERROR:
c.execute('''SELECT Username FROM LoginInfo WHERE Username=Hello1''')
sqlite3.OperationalError: no such column: Hello1
VERSION TWO:
import sqlite3
import sys
Username = "('Hello1',)"
print(Username)
connection= sqlite3.connect("Logininfo.db")
c = connection.cursor()
c.execute("SELECT Username FROM LoginInfo WHERE Username="Hello1"")
for row in c :
print(row)
VERSION TWO ERROR:
Invalid syntax error pop up highlighting Hello1
Any help would be appreciated as I'm really new at this.
You have problems with your syntax in both cases. When you send a string into cursor.execute you are sending the DB a complete command. This means strings need to be quoted correctly, SQL syntax needs to be correct, etc.
This command: SELECT Username FROM LoginInfo WHERE Username=Hello1 means:
"Give me the Username column from the LoginInfo table where Username matches the Hello1 column"
On the other hand this command: SELECT Username FROM LoginInfo WHERE Username='Hello1' (note the quotes) means:
"Give me the Username column from the LoginInfo table where Username = Hello1"
Your second attempt is simply invalid Python. You should be using triple quotes on the outside or escaping the quotes that are part of the query.
Related
I have a Db from where I have to display all the columns which match the substring of the column given by user.
The following code works:
c.execute("select *from Transactions where Description like '%sh%' ")
conn.commit()
print(c.fetchall())
conn.close()
But when I try to run this code it returns me an empty list:
def search(col,val):
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("Select *from Transactions where ? Like ? ",(col,'%'+val+'%'))
print(c.fetchall())
search('description',"sh")
Also the result will always be a blank list even if the col name is wrong. as opposed the usual error which says column not found.
Please Help
I have been reading a number of threads on how to accomplish this but for some reason it is not working.
I need to delete a Row from a database using a string variable from an entry widget as the "WHERE (variable name)=" is used in the DB query.
The entry widget data is stored as Snippet_Name and the same name is being used as a column name in the DB.
The database has 7 columns but I am only using the 1 column for the query and I want to delete the complete row which contains the entry variable. I have tried variations of DELETE with no success.
The code being used is:
def delete_code():
try:
snippetname = Snippet_Name.get()
sql_delete_query = ('DELETE FROM Code WHERE Snippet_Name = "?"', (snippetname))
c.execute(sql_delete_query)
conn.commit()
except:
messagebox.showerror('PYSnippet', 'Failed to delete record')
A little help and hint would be appreciated.
I went over the query and found 2 errors that needed to be address to correct the problem. The first problem was I had the ? enclosed in quotations which should not be there. Second problem was forgetting to a comma to the variable.
def delete_code():
try:
snippetname = Snippet_Name.get()
sql_delete_query = ('DELETE FROM Code WHERE Snippet_Name = ?' (snippetname,))
c.execute(sql_delete_query)
conn.commit()
except:
messagebox.showerror('PYSnippet', 'Failed to delete record')
I'm trying to insert the value of the variable test_text into a Postgres 9.6 database, each time the database_insert function is triggered.
I'm using Python 3.6 and psycopg2 v 2.7
If I use the below code without the placeholder: e.g replace %s with 'test' and remove , (test_text) - it works as I would expect...
def database_insert(update):
test_text = 'This is some test text'
with psycopg2.connect("DB CONNECTION DETAILS ARE HERE'") as conn:
cur = conn.cursor()
cur.execute("INSERT INTO test VALUES(%s);", (test_text))
conn.commit()
cur.close()
conn.close()
However when the function trys to insert the value of the test_text variable using the %s placeholder, I get the error below...
cur.execute("INSERT INTO test VALUES(%s);", (test_text))
TypeError: not all arguments converted during string formatting
Any help on where I am going wrong with this will be much appreciated!
There's a subtle issue here.
You need a comma to make a tuple not just the parens/brackets.
So simply change to:
cur.execute("INSERT INTO test VALUES(%s);", (test_text,))
And you should be good!
I have this code that simply creates a list from user input. I want to load this into sqlite Db instead of list shown but am not conversant with Sqlite. please help
HERE IS THE CODE
listQ = []
while True:
read = input("Type in a line. ").lower().split()
for item in read:
listQ.append( input("Type in a line. ") )
for line in listQ:
import sqlite3
conn = sqlite3.connect('/C/project/new/sqlite_file.db')
c = conn.cursor()
for item in listQ:
c.execute('insert into tablename values (?,?,?)', item)
#print(line)
I have small code like below :
#!/usr/bin/python
import psycopg2, sys
try:
conn = psycopg2.connect("dbname='smdr' user='bino'");
except:
print "I am unable to connect to the database"
cur = conn.cursor()
v_num = '1'
cur.execute("SELECT * from genctr WHERE code = %(num)s", dict(num=v_num))
rows = cur.fetchall()
print "\nShow me the databases:\n"
ctrnum =0
for row in rows:
print row[0]+","+row[1]
when i run it, i got
bino#erp:~/mydoc/openerp/smdr$ ./genctr.py
Show me the databases:
1,Bahamas
1,Barbados
1,Canada
1,Cayman Islands
1,United States
1,Virgin Islands U.S.
I try to replace "v_num = '1' " with "v_num = sys.stdin.read()"
#!/usr/bin/python
import psycopg2, sys
try:
conn = psycopg2.connect("dbname='smdr' user='bino'");
except:
print "I am unable to connect to the database"
cur = conn.cursor()
#v_num = '1'
v_num = sys.stdin.read()
cur.execute("SELECT * from genctr WHERE code = %(num)s", dict(num=v_num))
rows = cur.fetchall()
print "\nShow me the databases:\n"
ctrnum =0
for row in rows:
print row[0]+","+row[1]
But when I run it , I only got this :
bino#erp:~/mydoc/openerp/smdr$ echo 1 |./genctr.py
Show me the databases:
Kindly please give me your enlightment on how to fix it
Sincerely
-bino-
echo 1 is going to give "1\n" to your program (that is, "1" with a newline character afterward). sys.stdin.read() is going to return that exact string, and then psycopg2 is going to prepare the SQL statement as SELECT * from genctr WHERE code = '1\n'. The result is going to be no matching results, so the code inside the for loop will never execute, which is why you don't see any extra output.
Try doing either echo -n 1 to suppress the newline, or sys.stdin.read().strip() to remove any leading and trailing whitespace from the string. If the code field is an integer, it might be a good idea to cast the result of sys.stdin.read() to an int, too, like so:
int(sys.stdin.read().strip())