Python array to mysql DB - python

Why i can't save a array list to mysql DB ^^.
This Script work
Code work:
########################################
# Importing modules
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="*******",
password="*********",
database="meineTestDB",
)
cursor = conn.cursor()
insert_stmt = (
"INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME)"
"VALUES (%s, %s)"
)
data = ('Test1', 'Test2')
try:
# Executing the SQL command
cursor.execute(insert_stmt, data)
# Commit your changes in the database
conn.commit()
except:
# Rolling back in case of error
conn.rollback()
print("Data inserted")
#Closing the connection
conn.close()
########################################
but i want save array to MySQL DB
I try | data = (cars1, cars2) | or | data = ((cars1), (cars2)) | but it doesn't work.
########################################
# Importing modules
import mysql.connector
conn = mysql.connector.connect(
host="localhost",
user="*******",
password="*********",
database="meineTestDB",
)
cars1 = ["Ford", "Volvo", "BMW"]
cars2 = ["Ford", "Volvo", "BMW"]
cursor = conn.cursor()
insert_stmt = (
"INSERT INTO EMPLOYEE (FIRST_NAME, LAST_NAME)"
"VALUES (%s, %s)"
)
data = (cars1, cars2)
try:
# Executing the SQL command
cursor.execute(insert_stmt, data)
# Commit your changes in the database
conn.commit()
except:
# Rolling back in case of error
conn.rollback()
print("Data inserted")
#Closing the connection
conn.close()
########################################
sry for this Symple question i'm new to that Space.
I hope you can help my.
THX for all answer.
It looks like your post is mostly code; please add some more details. 0.o

Related

Python: No of rows are always 9 and does not return affected rows count after UPDATE query

This is not something complicated but not sure why is it not working
import mysql.connector
def get_connection(host, user, password, db_name):
connection = None
try:
connection = mysql.connector.connect(
host=host,
user=user,
use_unicode=True,
password=password,
database=db_name
)
connection.set_charset_collation('utf8')
print('Connected')
except Exception as ex:
print(str(ex))
finally:
return connection
with connection.cursor() as cursor:
sql = 'UPDATE {} set underlying_price=9'.format(table_name)
cursor.execute(sql)
connection.commit()
print('No of Rows Updated ...', cursor.rowcount)
It always returns 0 no matter what. The same query shows correct count on TablePlus
MysQL API provides this method but I do not know how to call it as calling against connection variable gives error
I am not sure why your code does not work. But i am using pymysql, and it works
import os
import pandas as pd
from types import SimpleNamespace
from sqlalchemy import create_engine
import pymysql
PARAM = SimpleNamespace()
PARAM.DB_user='yourname'
PARAM.DB_password='yourpassword'
PARAM.DB_name ='world'
PARAM.DB_ip = 'localhost'
def get_DB_engine_con(PARAM):
DB_name = PARAM.DB_name
DB_ip = PARAM.DB_ip
DB_user = PARAM.DB_user
DB_password = PARAM.DB_password
## engine = create_engine("mysql+pymysql://{user}:{pw}#{ip}/{db}".format(user=DB_user,pw=DB_password,db=DB_name,ip=DB_ip))
conn = pymysql.connect(host=DB_ip, user=DB_user,passwd=DB_password,db=DB_name)
cur = conn.cursor()
return cur, conn ## , engine
cur, conn = get_DB_engine_con(PARAM)
and my data
if i run the code
table_name='ct2'
sql = "UPDATE {} set CountryCode='NL' ".format(table_name)
cur.execute(sql)
conn.commit()
print('No of Rows Updated ...', cur.rowcount)
the result No of Rows Updated ... 10 is printed. and the NLD is changed to NL
If using mysql.connector
import mysql.connector
connection = mysql.connector.connect(
host=PARAM.DB_ip,
user=PARAM.DB_user,
use_unicode=True,
password=PARAM.DB_password,
database=PARAM.DB_name
)
cur = connection.cursor()
table_name='ct2'
sql = "UPDATE {} set CountryCode='NL2' ".format(table_name)
cur.execute(sql)
print('No of Rows Updated ...', cur.rowcount)
connection.commit()
it still works
and the country code is updated to NL2 and No of Rows Updated ... 10 is printed. The second time i run then No of Rows Updated ... 0 is printed.
Not sure why it does not work on your machine.

Python: MySQL is not updating record despite of using Commit

I am facing a weird issue. I have the following code. The INSERTS go well but the update query does not work at all. The rowcount is also shown 1 still when I check in Table Plus it does not reflect.
When I directly run the query UPDATE shop_links set product_status = 3 where shop_url = 'https://example.com' in TablePlus it does show record.
The irony is, the update query which set to 1 works just fine and updates instantly
import mysql.connector
def get_connection(host, user, password, db_name):
connection = None
try:
# connection = pymysql.connect(host=host,
# user=user,
# password=password,
# db=db_name,
# charset='utf8',
# max_allowed_packet=1073741824,
# cursorclass=pymysql.cursors.DictCursor)
connection = mysql.connector.connect(
host=host,
user=user,
use_unicode=True,
password=password,
database=db_name
)
connection.set_charset_collation('utf8')
print('Connected')
except Exception as ex:
print(str(ex))
finally:
return connection
with connection.cursor() as cursor:
sql = 'INSERT INTO {} (shop_url,product_url) VALUES (%s, %s)'.format(TABLE_FETCH_PRODUCTS)
cursor.executemany(sql, records)
connection.commit()
with connection.cursor() as cursor:
# Update the shop URL
# sql = "UPDATE {} set product_status = 3 where shop_url = '{}' ".format(TABLE_FETCH, shop_url)
sql = "UPDATE {} set product_status = 3 where shop_url = %s ".format(TABLE_FETCH, shop_url)
print(sql)
print('----------------------------------------------------------------')
cursor.execute(sql, (shop_url,))
connection.commit()

how to overwrite or skip data when the same data is already existed in database?

i'm taking data from textfile which contains some duplicate data.And i'm trying to insert them into database without duplicating.i'm in trouble where inserting duplicate data.it should not be inserted again.data are not static values.
text_file = open(min_file, "r")
#doc = text_file.readlines()
for line in text_file:
field = line.split(";")
print(field)
try:
connection = mysql.connector.connect(host='localhost',
database='testing',
user='root',
password='root')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
mycursor = connection.cursor()
#before inserting
mycursor.execute("Select * from ftp")
myresult = mycursor.fetchall()
for i in myresult:
print(i)
sql ="Insert into ftp(a,b,c,d) \
select * from( Select VALUES(%s,%s,%s,%s) as temp \
where not exists \
(Select a from ftp where a = %s) LIMIT 1"
mycursor.execute(sql,field)
print(mycursor.rowcount, "record inserted.")
connection.commit()
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
One option is to add Unique constraint and let the DB validate uniqueness, this will throw exception which you can catch and skip.

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

sqlite transaction doesn't commit

I run this code but it doesn't commit anything.
def them_mon(self):
ten_mon = ['Tin học', 'Toán', 'Nhạc', 'Mỹ thuật', 'Sinh', 'Lý', 'Văn', 'Thể dục', 'Sử', 'Địa', 'GDCD', 'TTH', 'AVTH', 'KHKT']
len_tm = len(ten_mon)
i = 0
while i < len_tm:
ten = ten_mon[i]
#print(ten)
sql = "INSERT INTO bang_diem(TEN_MON) VALUES(?)"
self.conn.execute(sql, (ten,))
i+=1
self.conn.commit()
No record is added or anything in bang_diem
You have to execute with cursor object and not the connection object
# Creates or opens a DB
db = sqlite3.connect('data.db')
# Get a cursor object
cursor = db.cursor()
cursor.execute("INSERT INTO tabe_name (column1, column2) VALUES(?,?,?,?)", (column1, column2))
db.commit()

Categories