error using python.connector by select ... where ... command - python

When I run this function some error occurs, but I have no idea what's wrong.
def insertVariblesIntoTable(newepc, newtimestamp):
try:
connection = mysql.connector.connect(host='localhost',
database='myDB',
user='root',
password='root')
cursor = connection.cursor()
mySql_insert_query = """INSERT INTO myTB(epc,time_stamp)
SELECT newepc,newtimestamp
FROM dual
WHERE NOT EXISTS (SELECT * FROM myTB
WHERE epc=newepc
AND time_stamp>NOW()-INTERVAL 1 MINUTE )"""
cursor.execute(mySql_insert_query)
connection.commit()
print("Record inserted successfully into myTB table")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
# print("MySQL connection is closed")
error:
Failed to insert into MySQL table 1054 (42S22): Unknown column 'newepc' in 'field list'

As far as I can tell, you're trying to access a column named "newepc" which doesn't exist.
This happens, because you're not escaping the variable "newepc" in your select query, mySql doesn't know it should be a variable.. you can try f-Strings or just normal concatination.

Related

pymysql python TypeError string formatting

i changed the sqlite3 connection code to mysql and got a connection error
discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'add' raised an exception: TypeError: not all arguments converted during string formattingā†[0m
def add_user_to_blacklist(user_id: int) -> int:
db = pymysql.connect(host=host, port=port, user=user, password=password, db=database, charset=charset) # open
cursor = db.cursor() # create
cursor.execute("INSERT INTO blacklist(user_id) VALUES (?)", (user_id,))
db.commit()
rows = cursor.execute("SELECT COUNT(*) FROM blacklist").fetchone()[0]
cursor.close()
db.close()
return rows

Updating data to sql via python - ProgrammingError: ('HY000', 'Attempt to use a closed connection.')

Can anyone help me fix this code? I am new to Python.
What I'm trying to do is extract Python web scraped data into SQL, but I got this error:
DatabaseError: ('21S01', '[21S01] [Microsoft][ODBC SQL Server Driver][SQL Server]Column name or number of supplied values does not match table definition.')
and
TypeError: 'DatabaseError' object is not subscriptable.
After I have included conn.commit() at the end of the code. Now I get this error.
ProgrammingError: ('HY000', 'Attempt to use a closed connection.')
This is the code - can you please help me to identify the error?
import pypyodbc as odbc # pip install pypyodbc
import pandas as pd # pip install pandas
df = pd.read_excel(r'C:\Users\sahan\Desktop\Empdata.xlsx')
columns = ['nameX', 'id', 'mark', 'department']
df_data = df[columns]
records = df_data.values.tolist()
DRIVER = 'SQL Server'
SERVER_NAME = 'LAPTOP-DIVPVC2Q\SQLEXPRESS'
DATABASE_NAME = 'CSE'
def connection_string(driver, server_name, database_name):
conn_string = f"""
DRIVER={{{driver}}};
SERVER={server_name};
DATABASE={database_name};
Trust_Connection=yes;
"""
return conn_string
try:
conn = odbc.connect(connection_string(DRIVER, SERVER_NAME, DATABASE_NAME))
except odbc.DatabaseError as e:
print('Database Error:')
print(str(e.value[1]))
except odbc.Error as e:
print('Connection Error:')
print(str(e.value[1]))
sql_insert = '''
INSERT INTO emp_data
VALUES (?, ?, ?, ?, GETDATE())
'''
try:
cursor = conn.cursor()
cursor.executemany(sql_insert, records)
cursor.commit();
except Exception as e:
cursor.rollback()
print(str(e[1]))
finally:
print('Task is complete.')
cursor.close()
conn.commit ()
conn.close()
Please help
When you use "insert into", you must provide a value for every column in the table. It looks like you are dropping all but four columns in the input file. If these are not the only fields in the table you are inserting into, you will get the table definition error.

how to insert filename as a string variable into mysql database in python

I have extracted filename from a certain directory. Filename is a string variable. Such as: 'LineNo-YYMMDD_hhmm'. Now I want to insert the filename into the existing MySQL DB. But couldn't find how to add as a str variable. This is what I had tried. Have some other way also checking net.
....
file_prefix = os.path.basename(name)[: - (len(filetail))]
(file_prefix is: LineName-200215_1619)
try:
connection = mysql.connector.connect(
host='localhost', db = 'db_name',
user='usr', password='myPass')
mysql_insert_query = " INSERT INTO fileHeader (headInfo) VALUES %s" % str(file_prefix)
cursor = connection.cursor()
cursor.execute(mysql_insert_query)
connection.commit()
cursor.close()
except mysql.connector.Error as error:
print ("Failed to insert record into fileHeader table {}".format(error))
Getting the following error:
Failed to insert record into fileHeader table 1064 (42000): You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'LineName-200215_1619' at line 1
add '' in your mysql_insert_query:
mysql_insert_query = " INSERT INTO fileHeader (headInfo) VALUES ( '{0}')".format(file_prefix)

SQL truncate table where table name is defined in function argument or variable

I'm trying to pass variable or function argument to the execute method
import pymysql
tablename = 'test_table'
con = pymysql.connect(**...)
with con.cursor() as cur:
cur.execute("TRUNCATE TABLE %s", tablename)
con.commit()
con.close()
Following error:
ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test_table'' at line 1")
Expecting to see no errors and the test_table empty of rows.
SO is slacking lately...
I did this instead and it worked:
import pymysql
tablename = 'test_table'
con = pymysql.connect(**...)
with con.cursor() as cur:
cur.execute("TRUNCATE TABLE %s" % tablename)
con.commit()
con.close()
print('Done')

How to insert variable to mysql database with python? "You have an error in your SQL syntax"

I am trying to insert one variable to mysql database with python. But I have syntax error.. Can You help me please? :)
import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(host='localhost',
database='Xiaomi_Temp',
user='user',
password='pass')
cursor = connection.cursor()
mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%d) """
recordTuple = (batt)
print(batt)
cursor.execute(mySql_insert_query, recordTuple)
connection.commit()
print("Record inserted successfully into table")
cursor.close()
except mysql.connector.Error as error:
print("Failed to insert record into table {}".format(error))
finally:
if (connection.is_connected()):
connection.close()
print("MySQL connection is closed")
I have variable batt and it has integer value.
My output is:
Failed to insert record into table 1064 (42000): 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 '%d)' at line 1
MySQL connection is closed
As the whole query needs to be in a string format while execution of query so %s should be used instead of %d which can be done as follows,
mySql_insert_query = """ INSERT INTO Temp_test (batt) VALUES (%s) """
recordTuple = (batt)
print(batt)
cursor.execute(mySql_insert_query, recordTuple)

Categories

Resources