Unable to fetch results from SQL to Python using mysql.connector - python

I am trying to query a table stored in SQL using python. I am using mysql.connector package to perform the task.
import mysql.connector
#Creating a connection
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="something",
database='mydatabase',
)
print(mydb)
##Creating a table called customers
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
#Inserting records to the table
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345')]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
The problem is when I query the database, there is no output displayed.
query=("SELECT name, address FROM customers")
mycursor.execute(query)
for (name, address) in mycursor:
print("{} {}".format(name, address))
Here is a link to what I tried and where I got the code from.
Link:https://dev.mysql.com/doc/connector-python/en/connector-python-example-cursor-select.html
Here is the confirmation that the query is storing rows in the database.

The code is running fine. The issue seems to be in the line mycursor.executemany(sql, oval) as the variable is defined as val above. Fixing that should give you the expected output.

Related

Mysql table name getting unwanted quotes resulting table does not exist error

import mysql.connector
def add_features_to_db(stockname, timeframe, date, feature):
try:
conn = mysql.connector.connect(
user='root', password='', host='localhost', database='fx003')
cursor = conn.cursor()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO `%s` (date, trend) VALUES ( `%s`, `%s` )"""
record = (dbtable, date, feature)
cursor.execute(mySql_insert_query, record)
conn.commit()
print("Record inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if conn.is_connected():
cursor.close()
conn.close()
print("MySQL connection is closed")
add_features_to_db("aud-cad", "_30mins", "2021-09-24 21:00:00", "Short")
I have the code above and giving me the below error:
Failed to insert into MySQL table 1146 (42S02): Table 'fx003.'aud-cad_30mins'' doesn't exist
aud-cad_30mins table does exist and an insert query like below doing its job:
mySql_insert_query = """INSERT INTO aud-cad_30mins (date, trend) VALUES ( "2021-09-24 21:00:00","Short" )"""
So when I try to use variables in the query, it gives the error. Why the table name getting unwanted quotes? Checked several tutorials but couldn't find a solution, any ideas?
The table name should be hardcoded in the query string instead of having it there as a placeholder %s, which is meant for the values to be inserted. So if you have the table name in the variable, you can replace it via format() before calling cursor.execute()
dbtable = stockname + timeframe
mySql_insert_query = """INSERT INTO {} (date, trend) VALUES ( %s, %s )""".format(dbtable)
see the examples in the docs
edit: as Bill mentioned in the comment, dont add the backticks around the %s placeholders.

Trouble filling MySQL table using Python

I'm am trying to convert a database I had as a txt file into a MySQL database. I found this tutorial and tried to follow it, but every time I run I get the error:
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'Pdf' in 'field list'
Here is the code I wrote
import shutil
import os
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
database="Book"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE IF NOT EXISTS Books (name VARCHAR(255), address VARCHAR(255))")
if os.path.exists("/home/Me/Desktop/Books/INFO.txt"):
#Extract the data from the txt file
f= open("/home/Me/Desktop/Books/INFO.txt","r")
Lines = f.readlines()
Items=[]
for line in Lines:
line=line.replace("\n","")
Items_not_s=line.split(",")
Items_not_s=tuple(Items_not_s)
Items.append(Items_not_s)
#Extracted the data from the txt file
sql = "INSERT INTO Books (Name, Pdf, Image, DegradedImage, Tags, Extra) VALUES (%s, %s, %s, %s, %s, %s)"
val = Items
print(val[20])
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "was inserted.")
else:
print("no file")
An example for the values (val) I want to put in the table is:
[('geekychefcookbook', '/home/Me/Desktop/Books/Food/Quarto Cookbooks/geekychefcookbook/PDF/PDF.pdf', 'None', '/home/Me/Desktop/Books/Food/Quarto Cookbooks/geekychefcookbook/IMAGE/IMAGE_RE.jpg', 'None', 'None'),('wickedgoodburgers', '/home/piotr/Desktop/Books/Food/Quarto Cookbooks/wickedgoodburgers/PDF/PDF.pdf', 'None', '/home/piotr/Desktop/Books/Food/Quarto Cookbooks/wickedgoodburgers/IMAGE/IMAGE_RE.jpg', 'None', 'None')]
Thanks in advance!
The MYSQL table does not have columns named Pdf, Image, DegradedImage, Tags, Extra as you are trying to insert.
The only columns you have are name and address, as defined in this line:
mycursor.execute("CREATE TABLE IF NOT EXISTS Books (name VARCHAR(255), address VARCHAR(255))")
Add all the columns in this line (by separating them with commas after address VARCHAR(255) with their specific data types and then try to insert your rows from the text file.

Failed to insert user input into MySQL database

I have created a database and inserted some value using python manual code but when i tried to taking input from user then inserting that input to my database table,i failed as i tried many ways.
Here is my code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="Adee11ruchi#",
database="hdatabase"
)
mycursor = mydb.cursor()
name= str(input("What is your first name? "))
address=str(input("enter address:"))
#mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
mycursor.execute = ("""INSERT INTO customers (name, address) VALUES (r{}, r{})""".format(name, address))
#val = ('Peter', 'Lowstreet 4')
mydb.commit()
print(mycursor.rowcount, "record inserted.")
It showing me as
What is your first name? diyu
enter address:hiouy
-1 record inserted.
What is the issue,i failed to find out.
You should be using a prepared statement here. Consider this version:
mycursor = mydb.cursor(prepared=True)
name = input("What is your first name? ")
address = input("enter address:")
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
mycursor.execute = (sql, (name, address,))
mydb.commit()
The main takeaways points here are that you leave the values to be bound as parameters %s, and then you bind the values as a tuple in the call to cursor#execute. Note that the prepared statement API will handle the proper formatting of the inputs for you.

Not all parameters were used in the SQL statement when using python and mysql

hi I am doing the python mysql at this project, I initial the database and try to create the table record, but it seems cannot load data to the table, can anyone here can help me out with this
import mysql.connector
mydb = mysql.connector.connect( host="localhost",user="root",password="asd619248636",database="mydatabase")
mycursor = mydb.cursor()
mycursor.excute=("CREATE TABLE record (temperature FLOAT(20) , humidity FLOAT(20))")
sql = "INSERT INTO record (temperature,humidity) VALUES (%d, %d)"
val = (2.3,4.5)
mycursor.execute(sql,val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
and the error shows "Not all parameters were used in the SQL statement")
mysql.connector.errors.ProgrammingError: Not all parameters were used in the SQL statement
Changing the following should fix your problem:
sql = "INSERT INTO record (temperature,humidity) VALUES (%s, %s)"
val = ("2.3","4.5") # You can also use (2.3, 4.5)
mycursor.execute(sql,val)
The database API takes strings as arguments, and later converts them to the appropriate datatype. Your code is throwing an error because it isn't expecting %d or %f (int or float) datatypes.
For more info on this you can look here
simply change insert method to
sql = "INSERT INTO record (temperature,humidity) VALUES (%s, %s)"
then it works fine
This works for me.
# Insert from dataframe to table in SQL Server
import time
import pandas as pd
import pyodbc
# create timer
start_time = time.time()
from sqlalchemy import create_engine
df = pd.read_csv("C:\\your_path_here\\CSV1.csv")
conn_str = (
r'DRIVER={SQL Server Native Client 11.0};'
r'SERVER=Excel-Your_Server_Name;'
r'DATABASE=NORTHWND;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
cursor = cnxn.cursor()
for index,row in df.iterrows():
cursor.execute('INSERT INTO dbo.Table_1([Name],[Address],[Age],[Work]) values (?,?,?,?)',
row['Name'],
row['Address'],
row['Age'],
row['Work'])
cnxn.commit()
cursor.close()
cnxn.close()

PostgreSQL creating table with Python failed

For some unknown reason table in database was not created. How to solve it?
import psycopg2
conn = psycopg2.connect(user='postgres', host='localhost', password='123456')
conn.autocommit = True
cur = conn.cursor()
cur.execute('CREATE DATABASE example;')
cur.execute("""CREATE TABLE HARMKA
(ID INT PRIMARY KEY NOT NULL,
PHARMACY_LICENSE CHAR(100),
STREET CHAR(150),
CITY CHAR(30));""")
cur.execute("INSERT INTO HARMKA VALUES(%s, %s, %s, %s)", (1, '12345', 'street', 'Denwer'))
cur.close()
conn.close()
You need to connect to example database and then create tables and manipulate data.
conn = psycopg2.connect(database='example', user='postgres', host='localhost', password='123456')

Categories

Resources