POSTGRES: CREATE TABLE doesn't save - python

I'm connecting to a postgres database in Heroku and trying to create a table. I run the code below but no new table shows up in the database.
import psycopg2
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
create_table = (""" CREATE TABLE test_table (account_address__c varchar); """)
cur = conn.cursor()
cur.execute(create_table)
conn.close()
Can you help?
Thank you!

I forgot to add
conn.commit()
.
cur = conn.cursor()
cur.execute(create_table)
conn.commit()
conn.close()

Related

Python update query in mariadb

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)

My SQL with Python: Select the row with the highest value and change the value there

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()

AWS Lambda: How can I execute RDS Aurora queries as atomic transaction?

I have the following Python code in an AWS Lambda function, and I want the queries on an RDS Aurora DB to run atomically, that is, run all or run none. Will the conn.commit() statement do that for me? If not how can I accomplish this? conn is my DB connection object.
# Connect to the DB
conn = pymysql.connect(rds_host, user=username,
passwd=password, db=db_name,
connect_timeout=10)
# Run queries
with conn.cursor() as cur:
cur.execute("create table some_table_2020 like some_table;")
cur.execute("insert into some_table_2020 select * from some_table;")
cur.execute("rename table some_table to some_table_20200629;")
cur.execute("rename table some_table_2020 to some_table;")
conn.commit()
Thanks to kielni's comment, here's the answer, per Use Commit and Rollback to Manage MySQL Transactions in Python
# Connect to the DB
conn = pymysql.connect(rds_host, user=username,
passwd=password, db=db_name,
connect_timeout=10)
try:
# Run queries
with conn.cursor() as cur:
cur.execute("create table some_table_2020 like some_table;")
cur.execute("insert into some_table_2020 select * from some_table;")
cur.execute("rename table some_table to some_table_20200629;")
cur.execute("rename table some_table_2020 to some_table;")
conn.commit()
exception:
# Failed to commit changes in the DB, do rollback
conn.rollback()
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()

How to connect to Oracle DB through python

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()

How to retrieve table names in a mysql database with Python and MySQLdb?

I have an SQL database and am wondering what command you use to just get a list of the table names within that database.
To be a bit more complete:
import MySQLdb
connection = MySQLdb.connect(
host = 'localhost',
user = 'myself',
passwd = 'mysecret') # create the connection
cursor = connection.cursor() # get the cursor
cursor.execute("USE mydatabase") # select the database
cursor.execute("SHOW TABLES") # execute 'SHOW TABLES' (but data is not returned)
now there are two options:
tables = cursor.fetchall() # return data from last query
or iterate over the cursor:
for (table_name,) in cursor:
print(table_name)
SHOW tables
15 chars
show tables will help. Here is the documentation.
It is also possible to obtain tables from a specific scheme with execute the single query with the driver below.
python3 -m pip install PyMySQL
import pymysql
# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='my_database')
# Create a Cursor object
cur = conn.cursor()
# Execute the query: To get the name of the tables from a specific database
# replace only the my_database with the name of your database
cur.execute("SELECT table_name FROM information_schema.tables WHERE table_schema = 'my_database'")
# Read and print tables
for table in [tables[0] for tables in cur.fetchall()]:
print(table)
output:
my_table_name_1
my_table_name_2
my_table_name_3
...
my_table_name_x

Categories

Resources