MYSQL not accepting values from insert statement - python

So im trying to insert values into a MYSQL database table but the following error keeps on popping up.
would really appreciate some help.
This is my code which i wrote to input a value from a file and store it in a database table.
import mysql.connector
import pickle
try:
connection = mysql.connector.connect(host='localhost',
database='PETROL',
user='Sarthak',
password='q1w2e3r4t5')
cursor = connection.cursor ( )
print(connection)
fp1 = open ("D:/Python/petrol/pdate/pdate.txt" , "rb+")
while True :
try :
pdate = pickle.load (fp1)
cursor.execute("DROP TABLE IF EXISTS DATES")
cursor.execute("CREATE TABLE DATES (ID INT AUTO_INCREMENT PRIMARY KEY,Date DATE)")
cursor.execute ("INSERT INTO DATES(Date) VALUES(pdate)")
cursor.execute("SHOW TABLES")
cursor.commit()
except EOFError :
fp6.close ()
except mysql.connector.Error as error:
print("Failed to create table in MySQL: {}".format(error))
cursor.close()
connection.close()
The following error keeps on popping up -:
Failed to create table in MySQL: 1054 (42S22): Unknown column 'pdate' in 'field list'
I am not able to encounter what problem is caused by the insert statement which i wrote.

Its better you write your insert statement like this
query = "INSERT INTO DATES(`Date`) VALUES(%s)" cursor.execute (query, pdate)

import pickle
try:
connection = mysql.connector.connect(host='localhost',
database='PETROL',
user='Sarthak',
password='q1w2e3r4t5')
cursor = connection.cursor ( )
print(connection)
fp1 = open ("D:/Python/petrol/pdate/pdate.txt" , "rb+")
while True :
try :
pdate = pickle.load (fp1)
cursor.execute("DROP TABLE IF EXISTS DATES")
cursor.execute("CREATE TABLE DATES (ID INT AUTO_INCREMENT PRIMARY KEY,Date DATE)")
query = "INSERT INTO DATES(`Date`) VALUES(%s)"
cursor.execute (query, pdate)
cursor.execute("SHOW TABLES")
connection.commit() #use connection.commit instead of cursor.commit
except EOFError :
fp6.close ()
except mysql.connector.Error as error:
print("Failed to create table in MySQL: {}".format(error))
cursor.close()
connection.close()```

Related

How to insert a list in postgres through python

I have a list
A=[1,2,3,3,4,5,6,8,90,8,6,5]
I want to put this list into a postgres table
After making a cursor and connection
I tried this
for i in A:
cusror.execute("Insert into schema1.table1 Values (%s)" ,i)
connection.commit()
But getting an error
TypeError: Not all arguments converted during string formatting.
Can someone help me out please
Use this function I will provide, just make sure to change TABLE_NAME and the columns for the ones you will be inserting:
import psycopg2
def bulkInsert(records):
try:
connection = psycopg2.connect(user="sysadmin",
password="pynative##29",
host="127.0.0.1",
port="5432",
database="postgres_db")
cursor = connection.cursor()
# Here replace the table and the columns
sql_insert_query = """ INSERT INTO TABLE_NAME (id, model, price)
VALUES (%s,%s,%s) """
# executemany() to insert multiple rows
result = cursor.executemany(sql_insert_query, records)
connection.commit()
print(cursor.rowcount, "Record inserted successfully into mobile table")
except (Exception, psycopg2.Error) as error:
print("Failed inserting record into mobile table {}".format(error))
finally:
# closing database connection.
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
# Example of how to use the function
records_to_insert = [(4, 'LG', 800), (5, 'One Plus 6', 950)]
bulkInsert(records_to_insert)
The 2nd argument to cursor.execute() should be a tuple. Try:
for i in A:
cursor.execute("Insert into schema1.table1 Values (%s)", (i,))
connection.commit()
Noting down a point from documentation -
For positional variables binding, the second argument must always be a sequence, even if it contains a single variable (remember that Python requires a comma to create a single element tuple):
>>> cur.execute("INSERT INTO foo VALUES (%s)", "bar") # WRONG
>>> cur.execute("INSERT INTO foo VALUES (%s)", ("bar")) # WRONG
>>> cur.execute("INSERT INTO foo VALUES (%s)", ("bar",)) # correct
>>> cur.execute("INSERT INTO foo VALUES (%s)", ["bar"]) # correct
Correct answer for your issue would be
for i in A:
cusror.execute("Insert into schema1.table1 Values (%s)" ,(i,))
connection.commit()
Using psycopg2 Fast execution helpers:
import psycopg2
from psycopg2.extras import execute_batch,execute_values
con = psycopg2.connect("dbname=test user=postgres host=localhost port=5432")
cur = con.cursor
A=[1,2,3,3,4,5,6,8,90,8,6,5]
param_list = [[id] for id in A]
#Using execute_batch
sql = "Insert into public.table1 values (%s)"
execute_batch(cur, sql, param_list)
con.commit()
#Using execute_values
sql = "Insert into public.table1 values %s"
execute_values(cur, sql, param_list)
con.commit()

Failed to update table record: 1064 (42000): You have an error in your SQL syntax; Python

I want to send my variable to MySQL database. But I have a warning. This code was successful to upload.
import mysql.connector
try:
connection = mysql.connector.connect(host='localhost',
database='mydb',
user='root',
password='')
cursor = connection.cursor()
username = 1111111 #example
isian = "tryfile.pkl" #example, i want send string data
print("Before updating a record ")
sql_select_query = """select * from signature where id = %s"""
cursor.execute(sql_select_query %(username))
record = cursor.fetchone()
print(record)
# Update single record now
sql_update_query = """Update signature set signature = "%s" where id = %s"""
cursor.execute(sql_update_query %(isian,username))
connection.commit()
print("Record Updated successfully ")
print("After updating record ")
cursor.execute(sql_select_query)
record = cursor.fetchone()
print(record)
except mysql.connector.Error as error:
print("Failed to update table record: {}".format(error))
finally:
if connection.is_connected():
connection.close()
print("MySQL connection is closed")
Warning
Failed to update table record: 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 '%s' at line 1
I don't understand with error, because I am using MySQL not MariaDB
What's happen to my code?
MariaDB is the engine used in modern MySQL databases.
The problem is your second call to sql_select_query, because you forgot to add the % (username), so nothing was substituted. HOWEVER, you should not be doing the substitutions yourself. You need to let the database connector do it. It's an easy change:
print("Before updating a record ")
sql_select_query = """select * from signature where id = ?"""
cursor.execute(sql_select_query, (username,))
record = cursor.fetchone()
print(record)
# Update single record now
sql_update_query = """Update signature set signature = ? where id = ?"""
cursor.execute(sql_update_query, (isian,username))
connection.commit()
print("Record Updated successfully ")
print("After updating record ")
cursor.execute(sql_select_query, (username,))
record = cursor.fetchone()
print(record)

make temporary database with sqlite

I wanna make a temporary database but I don't know I going in the right way or not
I get the error no such table: list but I don't know why python raise that error
this is my code:
def connect():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS list (id INTEGER PRIMARY KEY , namee VARCHAR , number INTEGER ,"
" price INTEGER )"
)
conn.commit()
conn.close()
def insert(name, number, price):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"INSERT INTO list VALUES (NULL ,?,?,?,?,?)", (name, number, price)
)
conn.commit()
conn.close()
def view():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"SELECT * FROM list"
)
rows = cur.fetchall()
conn.close()
return rows
def delete(id):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("DELETE FROM list WHERE id=?", (id,))
conn.commit()
conn.close()
connect()
and this is my error:
Traceback (most recent call last):
File "D:\python\WindowsProject\app\user\memory.py", line 42, in <module>
print(insert('pizza',2,6))
File "D:\python\WindowsProject\app\user\memory.py", line 17, in insert
cur.execute(
sqlite3.OperationalError: no such table: list
sqlite3.connect(":memory:") creates an in-memory database that only exists as long as the connection is in use.
The problem is that you're closing the database connection in each function. As soon as you close it, the in-memory database vanishes. INSERT fails because the table no longer exists.
You'll need to preserve (or pass) the conn and cur objects so that you can use them between functions.

unique values for a duration in mysql

I am new in mysql, I have a table with two cols tag_id and time_stamp, I use a python connector. I need to insert new tag_id just only if did not insert the same tag_id in last 5 min (or some other duration). How can I do that using python mysql.connector?
create table:
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='test',
user='root',
password='root')
mySql_Create_Table_Query = """CREATE TABLE tags (
Id int(11) NOT NULL AUTO_INCREMENT,
tag_id varchar(250) NOT NULL,
time_stamp Datetime NOT NULL,
PRIMARY KEY (Id)) """
cursor = connection.cursor()
result = cursor.execute(mySql_Create_Table_Query)
print("Laptop Table created successfully ")
except mysql.connector.Error as error:
print("Failed to create table in MySQL: {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
Insertion function:
def insertVariblesIntoTable(tag, time_stamp):
try:
connection = mysql.connector.connect(host='localhost',
database='test',
user='root',
password='root')
cursor = connection.cursor()
mySql_insert_query = """INSERT INTO tags(tag_id, time_stamp )
VALUES (%s, %s) """
recordTuple = (tag, time_stamp)
cursor.execute(mySql_insert_query, recordTuple)
connection.commit()
print("Record inserted successfully into tags 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")
I'd just do a query of the table like this:
import arrow
check = '''select max(timestamp) from tags where tag_id = {}'''
try:
with conn.cursor() as curs:
curs.execute(check.format(tag_id))
max_time = curs.fetchone()
if max_time <= arrow.utcnow().shift(minutes=-5).format('YYYY-MM-DD HH:mm:ss'):
#run the inserts
else:
pass

Problem with inserting into MySQL database from Python

I am having trouble inserting a record into a MySQL database from python. This is what I am doing.
def testMain2():
conn = MySQLdb.connect(charset='utf8', host="localhost", user="root", passwd="root", db="epf")
cursor = conn.cursor()
tableName = "test_table"
columnsDef = "(export_date BIGINT, storefront_id INT, genre_id INT, album_id INT, album_rank INT)"
exStr = """CREATE TABLE %s %s""" % (tableName, columnsDef)
cursor.execute(exStr)
#Escape the record
values = ["1305104402172", "12", "34", "56", "78"]
values = [conn.literal(aField) for aField in values]
stringList = "(%s)" % (", ".join(values))
columns = "(export_date, storefront_id, genre_id, album_id, album_rank)"
insertStmt = """INSERT INTO %s %s VALUES %s""" % (tableName, columns, stringList)
cursor.execute(insertStmt)
cursor.close()
conn.close()
The table is created however nothing is in the table. I can run the INSERT statement successfully in Terminal with the same credentials.
Any suggestions on what I may be doing wrong?
You haven't committed the transaction.
conn.commit()
(The MySQLdb library sets autocommit to False when connecting to MySQL. This means that you need to manually call commit or your changes will never make it into the database.)

Categories