I am trying to update my mariadb table via python code .While compile the query nothing happen in my database. please check below code and let me know where i made mistake in update function
import mariadb
connection= mariadb.connect(user="user1", database="db1", host="ippp" ,password="pass")
cursor= connection.cursor()
cursor.execute("UPDATE product_options_combinations SET quantity=5944 WHERE item_code ='31628'")
cursor.close()
connection.close()
Hello here I have a clean code example for you. How to update it.
import pymysql
# Create a connection object
# IP address of the MySQL database server
Host = "localhost"
# User name of the database server
User = "user"
# Password for the database user
Password = ""
database = "GFG"
conn = pymysql.connect(host=Host, user=User, password=Password, database)
# Create a cursor object
cur = conn.cursor()
query = f"UPDATE PRODUCT SET price = 1400 WHERE PRODUCT_TYPE = 'broadband'"
cur.execute(query)
#To commit the changes
conn.commit()
conn.close()
You just need to add connection.commit() to your code, but I recommend you use a parametrized SQL preferably with a list of tuples,more of which might be added if needed, along with cursor.executemany() as being more performant for DML statements such as
import mariadb
connection= mariadb.connect(user="user1",
password="pass",
host="ippp",
port=3306,
database="db1")
cursor= connection.cursor()
dml="""
UPDATE product_options_combinations
SET quantity=%s
WHERE item_code =%s
"""
val=[
(5944,'31628')
]
cursor.executemany(dml,val)
connection.commit()
cursor.close()
connection.close()
Are you sure that the connection is working properly?
Have you tried to implement a try and catch routine to print mariadb errors?
Something like this:
# Connect to MariaDB Platform
import mariadb
try:
conn = mariadb.connect(
user="user",
password="password",
host="xx.xx.xx.xx",
port=3306,
database="db_name"
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
Related
I am creating a program that uses VS Code and MySQL Workbench 8.0 together. I am stuck and do not know how to connect the two software together
I also have to be able to upload records into a table that is stored in MySQL Workbench from the Python program that uses variables.
Please tell me if their are any details missing.
Thank you.
For connection:
I have researched on Google and have been unable to find an answer. I have found that I have to install certain packages and use the connect method. However, I do not know the parameters of the connect function.
For uploading data into table:
I have found that I have to create a cursor to somehow upload the data to the table, but am unsusre of the full details.
There are many packages in python that can connect to the mysql database, here we take pymysql as an example.
Install pymysql
pip install PyMySQL
I have already installed, so the prompt package already exists.
Sample code, query and insert data
import pymysql
con = pymysql.Connect(
host='localhost',
port=3306,
user='root',
password='123456',
db='test',
charset='utf8'
)
cur = con.cursor()
sql1 = 'select * from student'
cur.execute(sql1)
data = cur.fetchall()
cur.close()
con.close()
for i in data:
print(str(i))
Add an insert data statement, and re-query after inserting data.
import pymysql
con = pymysql.Connect(
host='localhost',
port=3306,
user='root',
password='123456',
db='test',
charset='utf8'
)
cur = con.cursor()
sql2 = 'insert into student values("002","jerry","W");'
cur.execute(sql2)
sql1 = 'select * from student'
cur.execute(sql1)
data = cur.fetchall()
con.commit()
cur.close()
con.close()
for i in data:
print(str(i))
I am trying to detach the database, but for some reason it does not detach with no error, am I missing something?
import pyodbc
params = 'DRIVER={SQL Server};SERVER=.\RISKSPEC_PSA2012;DATABASE=master;UID=sa;Pwd=sa_pasw;Trusted_Connection=yes;'
try:
with pyodbc.connect(params) as cnxn:
with cnxn.cursor() as cursor:
cnxn.autocommit = True
cursor.execute(
'''
USE [master];
ALTER DATABASE [sss] SET SINGLE_USER WITH NO_WAIT;
EXEC sp_detach_db #dbname=sss;
''')
except pyodbc.Error as ex:
QMessageBox.warning(self, 'pyodbc', ex.args[0])
SQLServer 2012 version: 11.0.2100
pyodbc version: 4.0.31
Thx for Gord Thompson for the tip.
Fixes:
SET SINGLE_USER WITH NO_WAIT -> SET TRUSTWORTHY ON
Remove from connect params "Trusted_Connection=yes;", It associates the system user instead of "sa" user.
import pyodbc
params = 'DRIVER={SQL Server};SERVER=.\RISKSPEC_PSA2012;DATABASE=master;UID=sa;Pwd=sa_pasw;'
try:
with pyodbc.connect(params) as cnxn:
cnxn.autocommit = True
with cnxn.cursor() as cursor:
cursor.execute(
'''
USE [master];
ALTER DATABASE [sss] SET TRUSTWORTHY ON;
EXEC sp_detach_db #dbname=sss;
''')
except pyodbc.Error as ex:
QMessageBox.warning(self, 'pyodbc', ex.args[0])
I have already searched for several solutions here and tried to get a working code. Everything works except for the where query.
In the where query I search for the highest value (numeric). However, this does not really work...
Here is my code and the structure of the MySQL database.
Thanks!
import pymysql
conn = pymysql.connect(host='localhost', unix_socket='', user='root', passwd='pw', db='database')
cur = conn.cursor()
cur.execute("SELECT * FROM dose")
for r in cur:
curr = conn.cursor()
sql = """UPDATE dose
SET status = "printed"
WHERE id = SELECT GREATEST (status) FROM dose (status);"""
# print(sql)
try:
# Execute the SQL command
curr.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Rollback in case there is any error
conn.rollback()
curr.close()
cur.close()
conn.close()
My SQL Database
You have a lot of things wrong in your code.
You donĀ“t use the results of your first select query, and the only thing that you do is iterate over the results to execute an UPDATE
Your update query is wrong
You should change it to:
import pymysql
conn = pymysql.connect(host='localhost', unix_socket='', user='root', passwd='pw', db='database')
curr = conn.cursor()
sql = """UPDATE dose
SET status = 'printed'
WHERE id = (SELECT max(status) FROM dose) """
try:
# Execute the SQL command
curr.execute(sql)
# Commit your changes in the database
conn.commit()
except:
# Rollback in case there is any error
conn.rollback()
curr.close()
conn.close()
I have been trying to insert data into the database using the following code in python:
import sqlite3 as db
conn = db.connect('insertlinks.db')
cursor = conn.cursor()
db.autocommit(True)
a="asd"
b="adasd"
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.close()
The code runs without any errors. But no updation to the database takes place. I tried adding the conn.commit() but it gives an error saying module not found. Please help?
You do have to commit after inserting:
cursor.execute("Insert into links (link,id) values (?,?)",(a,b))
conn.commit()
or use the connection as a context manager:
with conn:
cursor.execute("Insert into links (link,id) values (?,?)", (a, b))
or set autocommit correctly by setting the isolation_level keyword parameter to the connect() method to None:
conn = db.connect('insertlinks.db', isolation_level=None)
See Controlling Transactions.
It can be a bit late but set the autocommit = true save my time! especially if you have a script to run some bulk action as update/insert/delete...
Reference: https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.isolation_level
it is the way I usually have in my scripts:
def get_connection():
conn = sqlite3.connect('../db.sqlite3', isolation_level=None)
cursor = conn.cursor()
return conn, cursor
def get_jobs():
conn, cursor = get_connection()
if conn is None:
raise DatabaseError("Could not get connection")
I hope it helps you!
I have installed python 2.7 64bit,MySQL-python-1.2.3.win-amd64-py2.7.exe.
I use the following code to insert data :
class postcon:
def POST(self):
conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
cursor = conn.cursor()
n = cursor.execute("insert into d_message (mid,title,content,image) values(2,'xx','ccc','fff')")
cursor.close()
conn.close()
if n:
raise web.seeother('/')
This results in printing n as 1, but in mysql client data aren't visible.
google says I must add conn.autocommit(True).
but I don't know why MySQLdb turns it off;
by default MySQLdb autocommit is false,
You can set autocommit to True in your MySQLdb connection like this,
conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
conn.get_autocommit() #will return **False**
conn.autocommit(True)
conn.get_autocommit() #Should return **True** now
cursor = conn.cursor()
I don't know if there's a specific reason to use autocommit with GAE (assuming you are using it). Otherwise, you can just manually commit.
class postcon:
def POST(self):
conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
cursor = conn.cursor()
n = cursor.execute("insert into d_message (mid,title,content,image) values(2,'xx','ccc','fff')")
conn.commit() # This right here
cursor.close()
conn.close()
if n:
raise web.seeother('/')
Note that you probably should check if the insert happened successfully, and if not, rollback the commit.
Connector/Python Connection Arguments
Turning on autocommit can be done directly when you connect to a database:
import mysql.connector as db
conn = db.connect(host="localhost", user="root", passwd="pass", db="dbname", autocommit=True)
or
import mysql.connector
db = mysql.connector.connect(option_files='my.conf', autocommit=True)
Or call conn.commit() before calling close.