SQL do not commit when hosted by server? - python

I made a website with flask which connect to a db file with sqlite3. When i run it locally it functions, but when I host it on vercel, the log shows no error but the db never commit and save any changes.
#example of a update
with sqlite3.connect(db) as connection:
try:
connection.execute("UPDATE Survey SET Responders = Survey.Responders+1 WHERE SurveyID = ?",(data["id"],))
connection.commit()
print("response added")
except Error as e:
print(e)
The database never save any changes, although i can select from the connection normally

Related

Python mysql connector rollback not working

I am writing a python script that does the following as a part a transaction.
Creates a new database.
Creates new tables using a schema.sql file.
Copies the data from the master DB to this new DB using insert into select * from master.table_name... like SQL statements.
Commits the txn, in the else block, if everything goes right. Rollback the txn, in the except block, if something goes wrong.
Close the connection in the finally block.
However, while testing, I found out that rollback isn't working. If an exception is raised after DB is created, even after rollback, DB is created. If an exception is raised after inserting data into a few tables with some tables remaining, calling rollback in the except block does not revert the inserted data. The script looks like this:
import mysql.connector
try:
conn = mysql.connector.connect(host='localhost', port=3306,
user=USERNAME, password=PASSWORD,
autocommit=False)
cursor.execute("START TRANSACTION;")
cursor.execute(f"DROP DATABASE IF EXISTS {target_db_name};")
cursor.execute(f"CREATE DATABASE {target_db_name};")
cursor.execute(f"USE {target_db_name};")
with open(SCHEMA_LOCATION) as f:
schema_query = f.read()
commands = schema_query.split(";")
for command in commands:
cursor.execute(command)
for query in QUERIES:
cursor.execute(f"{query}{org_Id};")
except Exception as error:
conn.rollback()
else:
conn.commit() # cursor.execute("COMMIT")
finally:
if conn.is_connected():
cursor.close()
conn.close()
Below are the details of the setup
Python3
mysql-connector-python==8.0.32
MySQL 5.7
Storage Engine: InnoDB

Connect to a database located on phpmyadmin from python

I'm looking to connect to a database via python.
The database is on phpmyadmin.
I read the section "variable" on phpmyadmin and I saw that the hostname is "atexo-sourcing-prod-01.local-trust.com".
Unfortunately, when I try to connect with this python code and with the same login and password that I use to connect to phpmyadmnin:
try:
conn = mariadb.connect(
user="mylogin",
password="my_password",
host="atexo-sourcing-prod-01.local-trust.com",
port=3306,
database="atexo_prod_sourcing_db")
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
I have an error, saying
Can't connect to server on 'atexo-sourcing-prod-01.local-trust.com'
(10061)
(I think it's not a problem of hostname, because when I put a random name, I have an other error).
Any idea to fix this?

Unable to create mysql database using flask sqlalchemy, Operational Error in SQL

Using Flask, I'm attempting to build a web application for user authentication, however the database is not being created and I keep receiving sql.errors.opertionalerror.
When I use sqlite, it functions perfectly, but when I use mysql, I receive the above mentioned error.
I am providing the SQLALCHEMY_DATABASE_URI='mysql+pymysql://username:password#localhost:3306/db_name' in the enivronment file.
Is it acceptable to use the Python MySQL (pymysql) connector to establish a database?
import pymysql as pm
def creating_user_db():
try:
mydb = pm.connect(host='localhost',
user='username',
passwd='password'
)
mydb.autocommit = False
cursor = mydb.cursor()
mydb.cursor().execute('CREATE DATABASE IF NOT EXISTS db_name;')
except Exception as e:
print(e)
finally:
cursor.close()
mydb.close()
Please correct me where I made a mistake and assist me with this.
Thanks In advance!

Asnycpg PostgreSQL connection issues

I'm using Python with asnycpg to interact with my PostgreSQL database.
After some time, if I don't interact with it and then try to do so, I get an connection is closed error. Is this a server side config or client side config issue?
How to solve it?
The database automatically closes the connection due to security reasons.
So I suggest you to open the connection to db just before running queries with asyncpg, and then to reclose the connection right afterwards.
Furthermore, you can manage the possible errors that you get when the connection is closed by properly rising exceptions.
Take a look at this example:
Import asyncpg
print("I'm going to run a query with asyncpg")
# if the connection to db is not opened, then open it
if not connection:
# try to open the connection to db
try:
connection = await asyncpg.connect(
host=YOUR_DATABASE_HOST,
user=YOUR_DATABASE_USER,
password=YOUR_DATABASE_PASS,
database=YOUR_DATABASE_DB_NAME
)
except (Exception, asyncpg.ConnectionFailureError) as error:
Print("Error while connecting to db: {}".format(error))
else:
#connection already up and running
pass
QUERY_STRING = """
INSERT INTO my_table(field_1, field_2)
VALUES ($1, $2);
"""
try:
await connection.execute(QUERY_STRING, value_to_assign_to_field_1, value_to_assign_to_field_2)
return None
# except (Exception, asyncpg.UniqueViolationError) as integrError:
# print("You are violating unique constraint.")
except (Exception, asyncpg.ConnectionFailureError) as error:
print("Connection to db has failed. Cannot add data.")
return "{}".format(error)
finally:
if (connection):
await Utils.close_connection(connection)
print("data has been added. closing the connection.")

I'm trying to display MySQL queries in a web browser using Python

I am trying to run MySQL commands through Python source code and have it display in my web browser.
When I compile the code in an editor (Komodo Edit) it complies and returns the expected set of rows, but when I try to view in a browser the source code is displayed, not the query result I seek...
Here's what I have...
import mysql.connector
conn = None
try:
conn = mysql.connector.Connect(host="localhost", user="jump", password="secret")
print('Connected to MySQL!')
except Exception as ex:
print('cannot connect to MySQL : exception : ' + str(ex))
cursor = conn.cursor()
cursor.close()
print('terminating connection with MySQL')
conn.close()
...I'm pretty sure the source is good, and that somewhere I missed a configuration step or some such.
I can get my command prompt to open the source file and display the query results, so I've got a connection between Python and MySQL server, which I verified through the MySQL workbench also.
Thanks for any help y'all can give!
-M

Categories

Resources