when i run this code in my raspberry-pi nothing happend and the code runs smouthly but there no results
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="raspberry", # your password
db="raspberry") # name of the data base
cur = db.cursor()
cur.execute("UPDATE visitors SET nb_visits = nb_visits+1 WHERE id = 1")
You should commit your transaction before changes take effect :
cur.execute("UPDATE visitors SET nb_visits = nb_visits+1 WHERE id = 1")
db.commit()
Related
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)
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 use the mysql.connector module to fetch rows in a python script but when I update a table using the terminal, my script doesen't see any changes.
My code is this:
import mysql.connector
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db')
cursor = database.cursor()
cursor.execute('SELECT * FROM my_table')
print(cursor.fetchall())
cursor.execute('SELECT * FROM my_table')
print(cursor.fetchall())
The first time it always reads the correct values but at the second time it does not see changes even when I have update my database.
I tried this solutions but it still did not work:
I tried updating the database using the mysql.connector module
I tried installing some older versions
I tried using the root user
When use performs DML like update, delete, etc You have to commit cursor after performing the operation otherwise your operation not save. There are use case of commit cursor some time
due to the electricity issue
atomicity transaction will rollback or commit latter
like
import mysql.connector
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db')
cursor = database.cursor()
try:
cursor.execute("update Employee set name = 'alex' where id = 110")
cursor.commit()
except:
cursor.rollback()
cursor.close()
commit if the update will succeed otherwise rollback if got any error at the database level
or you can pass autocommit=True when you connect with database it will work too it's global configuration it will commit of some interval of time
like
database = mysql.connector.connect(host='localhost', user='root', passwd='password', database='my_db', autocommit=True)
cursor = database.cursor()
there are two mysql connection in my python script. example:
conn1 = mdb.connect(server, user, pw, db)
conn2 = mdb.connect(server, user, pw, db)
#1. then, I execute "select" sql command to select table A by conn1,
#2. after that, I execute "update" sql command to update table A by conn2,
#3. finally, I execute "select" sql command again to select table A by conn1,
but finally, the result of #3 is same as #1; however, after #2, i saw the data is updated in mysql workbench.
Is anybody know why #3 cannot get the latest data?
following is my python codes:
import MySQLdb as mdb
import time
conn1 = mdb.connect(SERVER, USER, PASSWORD, DB)
cur1 = conn.cursor()
count1 = cur.execute("SELECT trigger_time FROM trigger_set WHERE id=1")
data1 = cur.fetchall()
cur1.close()
print data1
conn2 = mdb.connect(SERVER, USER, PASSWORD, DB)
cur2 = conn2.cursor()
cur2.execute("update trigger_set set trigger_time = '2013/8/30 17:15' where id=1")
conn2.commit()
cur2.close()
cur1 = conn.cursor()
count1 = cur.execute("SELECT trigger_time FROM trigger_set WHERE id=1")
data1 = cur.fetchall()
print data1
Things would work if you commit your conn1 before selecting again.. or just enable auto_commit to True.
conn1.commit()
This has been talked about here: http://sourceforge.net/p/mysql-python/discussion/70461/thread/efea588e
BTW your code contains conn and cur variables which have not been defined..
I think the problem lies with reusing the same cursor `cur1' for step 1 and 3.Try using a different cursor or connection for your last select too.
Below Code is my CGI Script, where am trying to do a insert Command.
#! C:\Python27\python.exe -u
import cgi
import MySQLdb
import xml.sax.saxutils
query = cgi.parse()
db = MySQLdb.connect(
host = "127.0.0.1",
user = "root",
passwd = "mysql123",
db = "welcome")
print 'Content-type: text/plain\n\n<?xml version="1.0" encoding="utf-8"?>\n<result>'
try:
c = db.cursor()
c.execute("insert into welcome.registrations values ('test','test',now())")
print '\t<update>true</update>'
except:
print '\t<update>false</update>'
print "</result>"
when i run the go to the url - .com/cgi-bin/reg.cgi, am not finding any insert operation done in mysql DB
You need to do db.commit() after c.execute().
Or you could do:
with db:
c = db.cursor()
c.execute("insert into welcome.registrations values ('test','test',now())")
make sure you do a db.commit() after every insert (or in the end, any will work ):
try:
c = db.cursor()
c.execute("insert into welcome.registrations values ('test','test',now())")
db.commit()
db.close() # Make sure you close the connection else multiple connections will result in hanging of mysql server.