So currently I'm able to perform mysql queries by simply doing
import mysql.connector
from mysql.connector import connect, Error
with connect(
host="localhost",
user="user",
password="password",
) as connection:
select_query = """
SELECT * FROM MY_TABLE
"""
with connection.cursor() as cursor:
cursor.execute(select_query)
Is there a way to do this but without the "SQL"
Something like this pseudo code
table = Table("MY_TABLE")
return table.select_all()
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()
I'm new to Python and I wanted to ask you for help.
I want to put the data of a view in SQL Server into a table of my database in MySQL, when I try to give the following error:
Execution failed on sql: SELECT name FROM sqlite_master WHERE
type='table' AND name=?; not all arguments converted during string
formatting unable to rollback
Using Python version 3.7
Below is the code I use:
import pymysql.cursors
import pyodbc
import pandas as pd
# SQL Server Connection
connection = pyodbc.connect("DSN=SQLServer") #autocommit=True
try:
with connection.cursor() as cursor:
result = "SELECT * FROM dw.dbo.vW_sale"
df = pd.read_sql_query("SELECT * FROM dw.dbo.vW_sale", connection)
cursor.execute(result)
table = cursor.fetchall()
print(table)
finally:
connection.close()
# MySQL connection
cnx = pymysql.connect(host='test',
user='test',
password='test',
db='dw')
try:
with cnx.cursor() as cursor:
mysql = "select *from ft_sale_test"
cursor.execute(mysql)
result = cursor.fetchall()
#print(result)
finally:
cnx.close()
# using if_exists to handle the table that already exists
The error happens right here
df.to_sql(con=cnx, name= 'ft_sale_test', if_exists= 'replace')
I am trying to connect to Oracle through Python and trying to execute a few DDL & DML statements. Please help how it can be done
a simple query
import cx_Oracle
con = cx_Oracle.connect('pythonhol/welcome#127.0.0.1/orcl')
cur = con.cursor()
cur.execute('select * from departments order by department_id')
for result in cur:
print result
cur.close()
con.close()
You can do something like this:
import cx_Oracle
connection = cx_Oracle.connect("username", "password", "ip of your server"/"database name")
cursor = connection.cursor()
cursor.execute("select * from table_name")
for row in cursor:
print(row)
connection.close()