How to have python function input() within mysql command? - python

Here is what i am trying to do:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="J"
)
mycursor = mydb.cursor()
sql = "UPDATE account SET balance = '100' WHERE address = 'input()'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
I want to know how to put input within the SQL command? Any other ways than that? I know in php that you put it within , but in python?
And what this code is all about is to refill or decrease customer balance.
like in db i got accounts and ofcourse there are alot of customers. How to make it so that it changes according to my input? thanks for reading.

Use the placeholder (%s) mechanism:
sql = "UPDATE account SET balance = '100' WHERE address = '%s'"
value = input()
mycursor.execute(sql, (value,)) # note well, the second argument must be a tuple, even if one-element only

import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="J"
)
mycursor = mydb.cursor()
custumValue=input("Enter your Address")
sql = "UPDATE account SET balance = '100' WHERE address = %s"
mycursor.execute(sql,(custumValue,))
mydb.commit()
print(mycursor.rowcount, "record(s) affected")

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.

Insert Data in mysql using python

import mysql.connector
mydb = mysql.connector.connect(
host="10.0.72.17",
user="admin",
passwd="1qaz!QAZ",
database="test"
)
mycursor = mydb.cursor()
sql = "INSERT INTO biage(kompaniis_saxeli) VALUES (%s)"
val = ('bane')
mycursor.execute(sql, val)
mycursor = mydb.cursor()
mydb.commit()
This is my python code , and i create column
kompaniis_saxeli varchar(225)
but when i try to run this code there is error
raise ValueError("Could not process parameters")
ValueError: Could not process parameters
The python driver needs at least a 2 dimensional list for values
So use:
import mysql.connector
mydb = mysql.connector.connect(
host="10.0.72.17",
user="admin",
passwd="1qaz!QAZ",
database="test"
)
mycursor = mydb.cursor()
sql = "INSERT INTO biage(kompaniis_saxeli) VALUES (%s)"
val = ('bane',)
mycursor.execute(sql, val)
mycursor = mydb.cursor()
mydb.commit()

Python array to mysql DB

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

python Insert tupule value to mysql database

I need to install tupule value to database,but getting "Unknown column 'Mac' in 'field list'" error
Below is the code i used
import mysql.connector, csv, sys
conn = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="mydjangoapp",
port=3307,
)
cursor=conn.cursor()
t1=('Mac', 'Mohan')
sql="insert into books (title,isbn) values(%s,%s)" %t1
cursor.execute(sql)
Don't use % interpolation, use placeholders.
t1 = ('Mac', 'Mohan',)
cursor.execute("INSERT INTO books (title, isbn) VALUES (%s, %s)", t1)

Updating results from a mysql-connector fetchall

I'm trying to select certain records from the civicrm_address table and update the geocode columns. I use fetchall to retrieve the rows then, within the same loop, I try to update with the results of the geocoder API, passing the civicrm_address.id value in the update_sql statement.
The rowcount after the attempted update and commit is always -1 so I am assuming it failed for some reason but I have yet to figure out why.
import geocoder
import mysql.connector
mydb = mysql.connector.connect(
[redacted]
)
mycursor = mydb.cursor(dictionary=True)
update_cursor = mydb.cursor()
sql = """
select
a.id
, street_address
, city
, abbreviation
from
civicrm_address a
, civicrm_state_province b
where
location_type_id = 6
and
a.state_province_id = b.id
and
street_address is not null
and
city is not null
limit 5
"""
mycursor.execute(sql)
rows = mycursor.fetchall()
print(mycursor.rowcount, "records selected")
for row in rows:
address_id = int(row["id"])
street_address = str(row["street_address"])
city = str(row["city"])
state = str(row["abbreviation"])
myaddress = street_address + " " + city + ", " + state
g = geocoder.arcgis(myaddress)
d = g.json
latitude = d["lat"]
longitude = d["lng"]
update_sql = """
begin work;
update
civicrm_address
set
geo_code_1 = %s
, geo_code_2 = %s
where
id = %s
"""
var=(latitude, longitude, address_id)
print(var)
update_cursor.execute(update_sql, var, multi=True)
mydb.commit()
print(update_cursor.rowcount)
mycursor.close()
update_cursor.close()
mydb.close()
Here is a simpler script:
I have executed the update_sql statement directly in the MySQL workbench and it succeeds. It is not working from Python.
import geocoder
import mysql.connector
try:
mydb = mysql.connector.connect(
[redacted]
)
mycursor = mydb.cursor(dictionary=True)
update_cursor = mydb.cursor()
update_sql = """
begin work;
update
civicrm_address
set
geo_code_1 = 37.3445
, geo_code_2 = -118.5366074
where
id = 65450;
"""
update_cursor.execute(update_sql, multi=True)
mydb.commit()
print(update_cursor.rowcount, "row(s) were updated")
except mysql.connector.Error as error:
print("Failed to update record to database: {}".format(error))
mydb.rollback()
finally:
# closing database connection.
if (mydb.is_connected()):
mydb.close()
I have it working now. I did remove the "begin work" statement but not the multi=True and it wouldn't work. Later I removed the multi=True statement and it works.

Categories