unable to get use where execute in sql - python

the program is just to get the phone number based on the carplate number.
i keep an error of could not process parameter,it must be of type list,tuple or dict.
import mysql.connector as mysql
def get_number(carplatenum):
# Connect to the database
conn = mysql.connect(
host = "127.0.0.1",
user = "root",
passwd = "",
database = "py")
print(conn)
# Create a cursor
cursor = conn.cursor()
sql="SELECT number FROM gov_info WHERE carplate=col1=%s"
params=(carplatenum)
# Execute the SQL query
cursor.execute(sql,params)
# Fetch and save the result
result = cursor.fetchone()
# Close the cursor and connection
cursor.close()
# return the number if match is found, otherwise return None
if result:
return result[0]
else:
return None
# Example usage:
carplate = 'SJJ4649G'
number = get_number(carplate)
if number:
print(f"The number for carplate {carplate} is {number}")
else:
print(f"No match found for carplate {carplate}.")
if i run it with the normal sql query with such as"SELECT number FROM gov_info WHERE carplate='SJJ4649G'"it would give the correct output.
the changes that fixed it
sql = "SELECT number FROM gov_info WHERE carplate=%s"
params = (carplatenum,)
cursor.execute(sql,params)

Related

Operational Error when running SQL statements in Python

I am trying to run some SQL statements in a Python environment in Visual Studio Code. The database that I am querying is in MySQL Workbench 8.0. My program runs smoothly until it reaches the querying part. It connects to the database fine. Here is my code:
from gettext import install
import pymysql
con = pymysql.Connect( #Creating connection
host = 'localhost', #
port = 3306, #
user = 'root', #
password = 'Musa2014', #
db = 'referees', #
charset = 'utf8' #
)
Ref_Info = input("Enter referee details: ") #First input statement
Ref_First_Name, Ref_Last_Name, Ref_Level = Ref_Info.split()
Ref_Info_Table = []
RefID = 1 #Setting the value of the RefID
while Ref_Info != '': #Creating loop to get referee information
Ref_Info = Ref_Info.split()
Ref_Info.insert(0, int(RefID))
Ref_Info_Table.append(Ref_Info) #Updating Ref_Info_Table with new referee data
print(Ref_Info_Table) #Printing values #
print(Ref_Info) #
print('Referee ID:', RefID) #
print('Referee First Name:', Ref_First_Name) #
print('Referee Last Name:', Ref_Last_Name) #
print('Referee Level:', Ref_Level) #
Ref_First_Name = Ref_Info[1]
Ref_Last_Name = Ref_Info[2]
Ref_Level = Ref_Info[3]
RefID = RefID + 1 #Increasing the value of RefID
Ref_Info = input("Enter referee details: ") #Establishing recurring input again
cur = con.cursor()
sql_query1 = 'INSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)'
sql_query2 = 'SELECT * FROM ref_info'
cur.execute(sql_query1)
cur.execute(sql_query2)
data = cur.fetchall()
con.commit()
cur.close()
con.close()
This is the error that I recieved:
Exception has occurred: OperationalError
(1054, "Unknown column 'MuhammadMahd' in 'field list'")
File "C:\Users\mahd_.vscode\Code Folders\Testing\test2.py", line 44, in
cur.execute(sql_query1)
It would be helpful if you could explain the error and tell me how to resolve it.
Thank you.
The statement in sql_query1
sql_query1 = 'INSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)'
miss the " quoting character for string literal; this statement would be sent to your mysql server as
INSERT INTO ref_info VALUES(1, MuhammadMahd, Ansari, B&W)
in which MuhammadMahd and Ansari and B&W do not refer to any column or expression, and are not string literals either. You have to add " to make them string literals:
sql_query1 = 'INSERT INTO ref_info VALUES(1, "MuhammadMahd", "Ansari", "B&W")'
And, to not have to deal to special character escape, you could use python's """ to start and end a string, which is better when you are writing sql in python:
sql_query1 = """INSERT INTO ref_info VALUES(1, "MuhammadMahd", "Ansari", "B&W")"""

Can I select just one specific element in a sql query(select statement)?

I am trying to create a command line tool that generates a random string(password) of a given length, stores it in a sql db, and can be queried by name. The password generation and storing of it's output by a given name works beautifully, but trying to select only the password element is giving me trouble. I was able to select all from the table but that returns the name and the password. I only want the password returned. I thought about just splicing the output or even using the linux cut command, but I'd rather just get it from the select statement. Is this possible? My current SELECT statement returns: operation parameter must be a str. When I try it without the call to (name) at the end of the SELECT statement like this: query_password = """SELECT * FROM password_table WHERE name = ?"""
I get this error:
File "passbox.py", line 44, in <module>
query_pswd_by_name(name)
File "passbox.py", line 39, in query_pswd_by_name
c.execute(query_password)
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 0 supplied.
BTW I'm sure my query_pswd_by_name function is all wrong, I've been experimenting. When I just create a connection and SELECT statement outside of a function it does return the name and password.
Also note that I've disguised my database file's name with asterisks for the purpose of this post. I am using an actual working db file in practice.
Here is all the code I've written so far:
import secrets
import string
import sqlite3
#CREATE PASSWORD OF GIVEN LENGTH
def get_pass(length):
return "".join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation) for x in range(length))
length = int(input("Enter the length of password: "))
password= get_pass(length)
print(password)
name = str(input("Enter name for password: "))
#CREATE DATABASE CONNECTION
conn = sqlite3.connect("****.db")
#CREATE CURSOR OBJECT
c = conn.cursor()
#CREATE TABLE IN DISK FILE BASED DATABASE
c.execute("""CREATE TABLE IF NOT EXISTS password_table (
name TEXT,
pswd TEXT
)""")
c.execute("INSERT INTO password_table (name, pswd) VALUES (?, ?)", (name, password))
#COMMIT CHANGES
conn.commit()
conn.close()
def query_pswd_by_name(name):
conn = sqlite3.connect('****.db')
c = conn.cursor()
query_password = """SELECT * FROM password_table WHERE name = ?""", (name)
c.execute(query_password)
result = c.fetchall()
for row in result:
print(row[1])
conn.commit()
query_pswd_by_name(name)
#CLOSE CONNECTION
conn.close()```
You need to break up the argument to the execute call.
c.execute(*query_password)
Or
c.execute("""SELECT * FROM password_table WHERE name = ?""", (name))

How get a row by 4 first chars?

I need to get a row by condition 4 first chars. I try to input manually, its work. but, when i use format. it got You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%s' at line 1.
in fruits field. there're banana, labanana, lobanana. i need to retrieve banana. then let labanana and lobanana not get retrieve.
con = mysql.connect(
host="127.0.0.1",
user="localhost",
passwd="localhost",
database='foods'
)
cursor = con.cursor()
cursor.execute("SELECT * FROM `eat` WHERE SUBSTR(fruits, 1, 4) = %s", ('bana'))
You are correctly using a prepared statement, but your need to obtain a cursor with statement mode enabled. Try this version:
con = mysql.connect(
host = "127.0.0.1",
user = "localhost",
passwd = "localhost",
database = 'foods'
)
cursor = con.cursor(prepared=True)
cursor.execute("SELECT * FROM `eat` WHERE SUBSTR(fruits, 1, 4) = %s", ('bana',))

Python2.4- check if there is a MySQL query result or not

cmd_connection1 = ("mysql -uuser -ppw -h127.0.0.1 mydatabase -s"
" -N -e \'select * from mytable where ID=\""+ID+"\";\'")
Using Python 2.4, I want to check if there is any result(as a row)
I used :
if not line1 :
...
if line1 == "Empty" :
...
But there is no result.
A working example I use every day.
Im using mysql connector:
You can download from:
https://dev.mysql.com/downloads/connector/python/
import mysql.connector
# impor mysql connector
cnx = mysql.connector.connect(user='your_user', password='your_pwd', host='you_host',database='your_database')
#create a conecction to mysql server
# change user, password, host and database according your needs
id_a_buscar =15
# i will search this value in my database
cursor = cnx.cursor()
# create a cursor
cursor.execute("""SELECT
titulo,
clave
FROM
historico
WHERE
libro_pk =%s""", (id_a_buscar,))
# execute a query
# %s stores a variable
# id_a_buscar is assigned to s
# so the REAL query is SELECT titulo, clave FROM historico WHERE libro_pk = 15
resultados = cursor.fetchall()
# store query results in resultados
count = cursor.rowcount
# count how many rows return after the query
if count > 0:
# if there are records
else:
# if there are NO records
You should use python 3

pyodbc the sql contains 0 parameter markers but 1 parameters were supplied' 'hy000'

I am using Python 3.6, pyodbc, and connect to SQL Server.
I am trying make connection to a database, then creating a query with parameters.
Here is the code:
import sys
import pyodbc
# connection parameters
nHost = 'host'
nBase = 'base'
nUser = 'user'
nPasw = 'pass'
# make connection start
def sqlconnect(nHost,nBase,nUser,nPasw):
try:
return pyodbc.connect('DRIVER={SQL Server};SERVER='+nHost+';DATABASE='+nBase+';UID='+nUser+';PWD='+nPasw)
print("connection successfull")
except:
print ("connection failed check authorization parameters")
con = sqlconnect(nHost,nBase,nUser,nPasw)
cursor = con.cursor()
# make connection stop
# if run WITHOUT parameters THEN everything is OK
ask = input ('Go WITHOUT parameters y/n ?')
if ask == 'y':
# SQL without parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN '2017-03-01T00:00:00.000' AND '2017-03-01T01:00:00.000'
''')
# SQL without parameters stop
# print result to console start
row = res.fetchone()
while row:
print (row)
row = res.fetchone()
# print result to console stop
# if run WITH parameters THEN ERROR
ask = input ('Go WITH parameters y/n ?')
if ask == 'y':
# parameters start
STARTDATE = "'2017-03-01T00:00:00.000'"
ENDDATE = "'2017-03-01T01:00:00.000'"
# parameters end
# SQL with parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN :STARTDATE AND :ENDDATE
''', {"STARTDATE": STARTDATE, "ENDDATE": ENDDATE})
# SQL with parameters stop
# print result to console start
row = res.fetchone()
while row:
print (row)
row = res.fetchone()
# print result to console stop
When I run the program without parameters in SQL, it works.
When I try running it with parameters, an error occurred.
Parameters in an SQL statement via ODBC are positional, and marked by a ?. Thus:
# SQL with parameters start
res = cursor.execute('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN ? AND ?
''', STARTDATE, ENDDATE)
# SQL with parameters stop
Plus, it's better to avoid passing dates as strings. Let pyodbc take care of that using Python's datetime:
from datetime import datetime
...
STARTDATE = datetime(year=2017, month=3, day=1)
ENDDATE = datetime(year=2017, month=3, day=1, hour=0, minute=0, second=1)
then just pass the parameters as above. If you prefer string parsing, see this answer.
If you're trying to use pd.to_sql() like me I fixed the problem by passing a parameter called chunksize.
df.to_sql("tableName", engine ,if_exists='append', chunksize=50)
hope this helps
i tryied and have a lot of different errors: 42000, 22007, 07002 and others
The work version is bellow:
import sys
import pyodbc
import datetime
# connection parameters
nHost = 'host'
nBase = 'DBname'
nUser = 'user'
nPasw = 'pass'
# make connection start
def sqlconnect(nHost,nBase,nUser,nPasw):
try:
return pyodbc.connect('DRIVER={SQL Server};SERVER='+nHost+';DATABASE='+nBase+';UID='+nUser+';PWD='+nPasw)
except:
print ("connection failed check authorization parameters")
con = sqlconnect(nHost,nBase,nUser,nPasw)
cursor = con.cursor()
# make connection stop
STARTDATE = '11/2/2017'
ENDDATE = '12/2/2017'
params = (STARTDATE, ENDDATE)
# SQL with parameters start
sql = ('''
SELECT * FROM TABLE
WHERE TABLE.TIMESTAMP BETWEEN CAST(? as datetime) AND CAST(? as datetime)
''')
# SQL with parameters stop
# print result to console start
query = cursor.execute(sql, params)
row = query.fetchone()
while row:
print (row)
row = query.fetchone()
# print result to console stop
say = input ('everething is ok, you can close console')
I fixed this issue with code if you are using values through csv.
for i, row in read_csv_data.iterrows():
cursor.execute('INSERT INTO ' + self.schema + '.' + self.table + '(first_name, last_name, email, ssn, mobile) VALUES (?,?,?,?,?)', tuple(row))
I had a similar issue. Saw that downgrading the version of PyODBC to 4.0.6 and SQLAlchemy to 1.2.9 fixed the error,using Python 3.6

Categories

Resources