Can't insert single column value in python using MySQL - python

I have a single column table. I need to insert values in this column. The program runs correctly without errors. But when I check the database, nothing gets inserted. When I added another column to the code and table, the program inserts data correctly. Can you tell me how to insert data for a single column table?
This is the single column code that does not insert anything to the table.
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="123",
db="dbname")
cursor = conn.cursor()
x=100
try:
sql="""INSERT INTO table (col1) VALUES ('%s')"""
cursor.execute(sql, (x))
conn.commit()
except:
conn.rollback()
conn.close()
This is the two columns code.
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="123",
db="dbname")
cursor = conn.cursor()
x=100
y=2
try:
sql="""INSERT INTO table (col1,col2) VALUES ('%s','%s')"""
cursor.execute(sql, (x,y))
conn.commit()
except:
conn.rollback()
conn.close()

You need to lose the quotes around %s, after that you need to know that the second argument to cursor.execute() is a tuple, and that a one-tuple is written:
(item,)
note the comma. The solution is then:
sql="""INSERT INTO table (col1) VALUES (%s)"""
cursor.execute(sql, (x,))

You can try either of these:
Don't use '%s', you can use ? instead
Instead of '%s', just use %s without quotes

try this:
sql="""INSERT INTO table (col1) VALUES ({});""".format(x)
cursor.execute(sql)

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.

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()

Insert Python string or dictionary into MySQL

I have a Python string (or potentially a Python dictionary) that I'd like to insert to MySql table.
My String is the following:
{'ticker': 'BTC', 'avail_supply': 16479075.0, 'prices': 2750.99, 'name': 'Bitcoin', '24hvol': 678995000.0}
I have the same kind of error if I want to insert the Dict format.
I really don't understand this kind of error (i.e. the '\' in-between the components of the string).
How can I deal with this error? Any why to properly insert a whole string to a particular TEXT cell in SQL?
Many thanks !!
Here is how to connect, make a table, and insert in the table.
import MySQLdb as mdb
import sys
#connect
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
#need the cursor object so you can pass sql commands, also there is a dictionary cursor
cur = con.cursor()
#create example table
cur.execute("CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
#insert what you want
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
Example above will make a table with 2 cols, one ID and one name
look here on an example on how to insert stuff from dictionary with keys and list as value to sql, basically you need place holders
sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}
conn = MySQLdb.connect(**params)
cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()
conn.close()
or you can go with this as an example for a simple straight forward dict
placeholders = ', '.join(['%s'] * len(myDict))
columns = ', '.join(myDict.keys())
sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
cursor.execute(sql, myDict.values())

Python 3.4 transmiting table, columns and values as variables using MySQLdb

I am using Python 3.4
I have this piece of code:
import MySQLdb
table = "my_table"
columns = ("column1", "column2")
values = ("value1", "value2")
conn = MySQLdb.connect (host = "localhost",
user = "user",
passwd = "password",
db = "my_database")
cursor = conn.cursor()
# execute an insert
cursor.execute("INSERT INTO my_table column1, column2 VALUES (value1, value2)")
cursor.commit()
cursor.close()
conn.close()
Q: How can I pass the table name, columns and the values all as variables?
I would like to do something like this:
sql = "INSERT INTO %s %s VALUES %s" % (my_table, columns, values)
cursor.execute(sql)
You will have to do it as a 2 step process as the execute method will escape strings.
sql = "INSERT INTO {} ({}) VALUES ({})".format(table, ','.join(columns), ','.join('[%s]' * len(columns)))
# Generates: INSERT INTO my_table (column1,column2) VALUES (?,?)
cursor.execute(sql, values)

python to mysql unknown column in try exception

i just want to select or insert into mysql using python 3.2 and mysql.connector..
import mysql.connector
filename = "t1.15231.0337.mod35.hdf"
try:
cnx = mysql.connector.connect(user='root', password='', database='etl')
cursor = cnx.cursor()
cursor.execute('SELECT * FROM hdf_file WHERE NAMA_FILE = %s',filename)
rows = cursor.fetchall ()
if rows == []:
insert_hdf = cursor.execute('INSERT INTO hdf_file VALUES(%s,null,NOW(),null,null,NOW())',filename)
cursor.execute(insert_hdf)
cnx.commit()
cursor.close()
cnx.close()
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
but it said that: unknown column 'filename' in where clause
i have tried to put something like this:
cursor.execute('SELECT * FROM hdf_file WHERE NAMA_FILE = filename')
but i got the same error...
When using cursor.execute() with parameterised queries the query arguments are passed as a sequence (e.g. list, tuple) or as a dictionary if using named parameters. Your code passes only the string filename.
Your queries could be written like this:
cursor.execute('SELECT * FROM hdf_file WHERE NAMA_FILE = %s', (filename,))
Here the tuple (filename,) is passed to execute(). Similarly for the insert query:
cursor.execute('INSERT INTO hdf_file VALUES (%s, null, NOW(), null, null, NOW())',
(filename,))
execute() will return None, so there is no use in storing the result in the insert_hdf variable. It also makes no sense, and will cause an error, if you attempt cursor.execute(insert_hdf).

Categories

Resources