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',))
Related
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)
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")"""
I am trying to update an array in an array in a column. However, psycopg2 keeps erroring, and I have no clue as to why this statement errors like this.
The Code:
lastUpload = "tgpx60236wa"
print(search.execute()["items"][0]["contentDetails"]["upload"]["videoId"])
connect = psycopg2.connect(host = loadConfig()["host"], database = loadConfig()["database"], user = loadConfig()["user"], password = loadConfig()["password"])
cursor = connect.cursor()
cursor.execute(f"SELECT youtube_channels[{channels.index(channel)}][1] FROM youtubeChannels WHERE guild_id = {guild[0]}")
print(cursor.fetchone()[0])
cursor.execute(f"UPDATE youtubeChannels SET youtube_channels[{channels.index(channel)}] = {lastUpload} WHERE guild_id = {guild[0]} RETURNING youtube_channels;")
connect.commit()
print(cursor.fetchone()[0])
cursor.close()
connect.close()
The Output:
cursor.execute(f"UPDATE youtubeChannels SET youtube_channels[{channels.index(channel)}] = {lastUpload} WHERE guild_id = {guild[0]} RETURNING youtube_channels;")
psycopg2.errors.UndefinedColumn: column "tgpx60236wa" does not exist
LINE 1: UPDATE youtubeChannels SET youtube_channels[0] = tgpx60236wa...
I don't even know what this error is supposed to mean, but I just don't know what I'm doing wrong here.
That's because you're not supposed to inform parameters on psycopg2 queries using f-Strings. The query parameters supposed to be passed as arguments of the execute method and using placeholders for the substitution, something like this:
lastUpload = "tgpx60236wa"
print(search.execute()["items"][0]["contentDetails"]["upload"]["videoId"])
connect = psycopg2.connect(host = loadConfig()["host"], database = loadConfig()["database"], user = loadConfig()["user"], password = loadConfig()["password"])
cursor = connect.cursor()
cursor.execute("SELECT youtube_channels[%s][1] FROM youtubeChannels WHERE guild_id = %s", channels.index(channel), guild[0])
print(cursor.fetchone()[0])
cursor.execute("UPDATE youtubeChannels SET youtube_channels[%s] = %s WHERE guild_id = %s RETURNING youtube_channels;", channels.index(channel), lastUpload, guild[0])
connect.commit()
print(cursor.fetchone()[0])
cursor.close()
connect.close()
Note that this isn't the only way you can pass parameters to a sql query. I suggest you take a dive in the documentation to understand better.
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 need to process mysql data one row at a time and i have selected all rows put them in a tuple but i get the error above.
what does this mean and how do I go about it?
Provide some code.
You probably call some function that should update database, but the function does not return any data (like cursor.execute()). And code:
data = cursor.execute()
Makes data a None object (of NoneType). But without code it's hard to point you to the exact cause of your error.
It means that the object you are trying to iterate is actually None; maybe the query produced no results?
Could you please post a code sample?
The function you used to select all rows returned None. This "probably" (because you did not provide code, I am only assuming) means that the SQL query did not return any values.
Try using the cursor.rowcount variable after you call cursor.execute(). (this code will not work because I don't know what module you are using).
db = mysqlmodule.connect("a connection string")
curs = dbo.cursor()
curs.execute("select top 10 * from tablename where fieldA > 100")
for i in range(curs.rowcount):
row = curs.fetchone()
print row
Alternatively, you can do this (if you know you want ever result returned):
db = mysqlmodule.connect("a connection string")
curs = dbo.cursor()
curs.execute("select top 10 * from tablename where fieldA > 100")
results = curs.fetchall()
if results:
for r in results:
print r
This error means that you are attempting to loop over a None object. This is like trying to loop over a Null array in C/C++. As Abgan, orsogufo, Dan mentioned, this is probably because the query did not return anything. I suggest that you check your query/databse connection.
A simple code fragment to reproduce this error is:
x = None
for each i in x:
#Do Something
pass
This may occur when I try to let 'usrsor.fetchone' execute twice. Like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
if cursor.fetchone() is not None:
username, password = cursor.fetchone()
print username, password
I don't know much about the reason. But I modified it with try and except, like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
try:
username, password = cursor.fetchone()
print username, password
except:
pass
I guess the cursor.fetchone() can't execute twice, because the cursor will be None when execute it first time.
I know it's an old question but I thought I'd add one more possibility. I was getting this error when calling a stored procedure, and adding SET NOCOUNT ON at the top of the stored procedure solved it. The issue is that earlier selects that are not the final select for the procedure make it look like you've got empty row sets.
Try to append you query result to a list, and than you can access it. Something like this:
try:
cursor = con.cursor()
getDataQuery = 'SELECT * FROM everything'
cursor.execute(getDataQuery)
result = cursor.fetchall()
except Exception as e:
print "There was an error while getting the values: %s" % e
raise
resultList = []
for r in result:
resultList.append(r)
Now you have a list that is iterable.