for a project at uni i need to insert different kinds of variables into a MySql Database. Connecting and Inserting the data so far works fine. I don't know how to handle potential errors though. Which potential mistakes and exceptions do i need to catch and take care of ?
In my code i used a main method to just test the program. In the final version just the connection and the SQL queries are copied into the main script. I am open to use either the MySQL or the mysql.connector. Also: Do i need to put the query into a try block aswell ? Here is my code so far:
import mysql.connector
import time
from mysql.connector import errorcode
try:
con = mysql.connector.connect(
user= 'root',
password= '',
host='localhost',
database= 'testdb')
print("Connected.")
cursor = con.cursor()
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Passwort // Username")
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print("DataBase does not exist")
else:
print(e)
def insert_temp(Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID):
query = "INSERT INTO Temperatur (Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID)" \
"VALUES(%s, %s, %s, %s)"
args= (Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID)
cursor.execute(query, args)
con.commit()
def main():
# just test values so far
value = 18.5;
insert_temp(' ', time.strftime('%Y-%m-%d %H:%M:%S'), value, '1');
cursor.close()
con.close()
if __name__ == '__main__':
main()
please note that i have very little experience in python programming
Related
Inserting records into a MySQL database using Python MySQL Connector. Process works around 98% of the time. I am getting intermittent timeout responses from the server. Other times the script just hangs and nothing happens, which is the worse possible situation.
Can I timeout/kill the process using threading?
Can I set a timeout on the execute or commit statement?
import mysql.connector
try:
mydb = mysql.connector.connect(host="...", user="...", password="...", database="...")
mycursor = mydb.cursor()
except Exception as e:
print(e)
#Seems to always work up to this point
sql = "INSERT INTO test (name,tagline,location,experience) VALUES (%s, %s, %s, %s)"
val = ('test', 'test', 'test', 'test')
try:
mycursor.execute(sql, val)
mydb.commit()
except Exception as e:
print(e)
mycursor.close()
mydb.close()
Im currently attempting to follow a youtube tutorial on how to connect a database through Pycharm however it's not connecting and I'm not sure where the problem is or how I am able to solve it. the code is:
import mysql.connector
from mysql.connector import errorcode
try:
cnn = mysql.connector.connect(
user='root',
password='root',
host='localhost',
database='name')
print("it works")
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("something is wrong with username and password")
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print("database does not exist")
else:
print("E")
cursor = cnn.cursor()
addName = "INSERT INTO name (fName, lName) values (%s, %s)"
fName = "Rae"
lName = "Smith"
empName = (fName, lName)
cursor.execute(addName, empName)
cnn.commit()
cursor.close()
cnn.close()
Once I run it I get the error:
Traceback (most recent call last):
something is wrong with username and password
line 19, in <module>
cursor = cnn.cursor()
NameError: name 'cnn' is not defined
I've seen the user on the tutorial receiving the same warning however when he runs his code there is no error like the one I receive. How I may be able to solve this?
I need to call a MySQL stored procedure from Python, and I don't need to wait for the procedure to finish.
How can this be done?
code below work for me
import mysql.connector
def insertComment(ecID, eID, eComment):
try:
contraseƱa = input("Please, enter your database password: ")
connection = mysql.connector.connect(host='localhost',
database='mantenimiento',
user='hernan',
password=contraseƱa,
port=3309)
if connection.is_connected():
cursor = connection.cursor(prepared=True)
procedure = "call mantenimiento.spSaveComment(%s, %s, %s)"
datos = (ecID, eID, eComment)
cursor.execute(procedure, datos)
# datos = [(ecID, eID, eComment)] # Tuple for executemany
# cursor.executemany(procedure, datos)
connection.commit()
print(cursor.rowcount, "Comment inserted sucessfully")
except mysql.connector.Error as error:
connection.rollback()
print("Failed to insert value into database {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("Server connection was closed")
insertComment(15, 25, 'Test MariaDB or MySQL SP from python')
One possible solution is by using celery: "Celery is an asynchronous task queue/job queue based on distributed message passing.". You can create a task where you call your MySQL store procedure.
I found such a code online but I am trying to edit it to link Python data to postgresql. I am really new to coding so I would really appreciate your help.
import psycopg2
import sys
connection = None
connection = psycopg2.connect("host='localhost' db='football'
user ='postgres' password='password'")
cur = con.cursor()
con.commit()
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `Games` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster#python.org', 'very-secret'))
except SyntaxError as e:
print("There was an error: {}".format(e))
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT row[5]"
cursor.execute(sql, ('row [5]',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
Your try statement needs to be paired with an except. The purpose of try/except is to catch any errors thrown in your try block gracefully. But without an except, try isn't very useful.
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `Games` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster#python.org', 'very-secret'))
except SyntaxError as e:
print("There was an error: {}".format(str(e)))
Your actual psycopg2 code looks about right.
I am trying to make a login system with python and mysql. I connected to the database, but when I try to insert values into a table, it fails. I'm not sure what's wrong. I am using python 3.5 and the PyMySQL module.
#!python3
import pymysql, sys, time
try:
print('Connecting.....')
time.sleep(1.66)
conn = pymysql.connect(user='root', passwd='root', host='127.0.0.1', port=3306, database='MySQL')
print('Connection suceeded!')
except:
print('Connection failed.')
sys.exit('Error.')
cursor = conn.cursor()
sql = "INSERT INTO login(USER, PASS) VALUES('test', 'val')"
try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()
print('Operation failed.')
conn.close()
I think it may have to do with the order of the statements in the connection. According to the PyMySQL github (found here) the correct order is host, port, user, passwd, db.
Like this :
user = input("User: ")
pass = input("Pass: ")
sql = "INSERT INTO login(USER, PASS) VALUES('%s', '%s')"%(user, pass)
btw you should connect like this :
conn = pymysql.connect(
host='127.0.0.1',
user='root',
passwd='root',
db='MySQL
)