PyMySQL Error inserting values into table. - Python - python

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
)

Related

Parse and Insert XML file to SQL Database

So i want to store my XML data to database using python connector to mysql.
import mysql.connector
from getpass import getpass
from mysql.connector import connect, Error
import xml.etree.ElementTree as ET
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="results"
)
if mydb:
print ("Connected Successfully")
else:
print ("Connection Not Established")
tree = ET.parse('report.xml')
res = tree.findall('entry')
for test in res:
name = test.find('name').text
verdict = test.find.int('verdict').text
description = test.find('description').text
report = """INSERT INTO test_executions (name,verdict,description)
VALUES(%s,%s,%s)"""
cursor = mydb.cursor()
cursor.execute(report,(name,verdict,description))
mydb.commit()
print("Data inserted successfully.")
print(mycursor.rowcount, "record inserted.")
I already have this code but everytime i run it, it never go through the for loop and commit the insertion to my DB. Is there something wrong with the code?

How to trigger 'return' when specific output given

I'm developing a authentication script in Python. I need PyMySQL to check if user exists, how can I do that?
I read the documention but didn't find answer to my question.
def check():
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
userexist = # PyMySQL check code here
if userexist=='True':
return 'good'
It's not clear whether you want to check for the pymysql user or a user from the database. This code will address both instances.
pymysql will raise an exception: pymysql.err.OperationalError if the user does not exist. You therefore need a try, except clause like this:
def check():
try:
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
except pymysql.err.OperationalError:
print('User with entered connection credentials does not exists')
return False
try:
with connection.cursor() as cursor:
cursor.execute("select...") # Fill with your select statement
result = cursor.fetchone()
if result is None:
connection.close()
return False
finally:
connection.close()
return 'good'

How to connect MySQL workbench with from shell using Python?

I have database in MySQL workbench and I'm running Python code from shell to connect to my database.
But I am unable to import mysql.connector or mysqlDb (got this suggestion from w3school). So I am unable to connect to my database.
I think the question does not concern connecting with Putty, but more about importing mysql.connector in your python script.
"But I am unable to import mysql.connector or mysqlDb ( got this suggestion form w3school)"
--It will be easier to help you if your code is attached to your post.
import mysql.connector
cnx = mysql.connector.connect(########)
think this scrap of code will be helpful."Loading file from Oracle"
def load_file(DT):
ip = ######
port = #####
service_name = '#####'
dsn = cx_Oracle.makedsn(ip, port, service_name=service_name)
t = datetime.now().strftime("%Y%m%d%H%M%S")
SQL = "select name...."
fn = "/root/..." + t + ".csv"
fn_tmp = "/root/.." + t + ".csv"
FILE = open(fn_tmp, "w")
FILE.write(
'name...;' + '\n')
out = csv.writer(FILE, delimiter=';')
logging.info("Database connect " + t)
try:
conn = cx_Oracle.connect('####', '###', dsn)
cur = conn.cursor()
cur.execute(SQL)
except cx_Oracle.DatabaseError, exc:
conn = None
error, = exc.args
logging.error(
"Oracle connection problem Error Code:{0}".format(str(error).decode("####",
"ignore").encode("utf-8",
"ignore"))
)
for row in cur:
out.writerow(localize_floats(row))
logging.info("Database disconnect " + t)
try:
cur.close()
conn.close()
except cx_Oracle.DatabaseError, exc:
error, = exc.argsgv[0]
logging.error("Oracle-Error-Code:{0}".format(str(error).decode("####",
"ignore").encode("utf-8",
"ignore"))
)
FILE.close()
os.rename(fn_tmp, fn)
An option that you can try is to use pymysql. More info here. A code snippet is the following:
import pymysql.cursors
connection = pymysql.connect(host='IP',
port=3306,
user='user',
password='pass',
db='database',
charset='utf8mb4',
autocommit=True,
cursorclass=pymysql.cursors.DictCursor)
with connection.cursor() as cursor:
query = 'Your query'
cursor.execute(query)
connection.close()

PYTHON MYSQL doesn't work second time

Am receiving json data (from an other python script) to put inside MYSQL database, the code work fine the first time but the second time I got this error:
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
For troubleshooting am sending always the same data, but it still write an error the second time.
I tried also from information found on furums to place : cur = mydb.cursor() at diferents places but I have never been able to get this code work the second time.
There is my code :
import mysql.connector
import json
mydb = mysql.connector.connect(
host="localhost",
user="***",
passwd="***",
database="***"
)
def DATA_REPARTITION(Topic, jsonData):
if Topic == "test":
#print ("Start")
INSERT_DEBIT(jsonData)
def INSERT_DEBIT(jsonData):
cur = mydb.cursor()
#Read json from MQTT
print("Start read data to insert")
json_Dict = json.loads(jsonData)
debit = json_Dict['debit']
print("I send")
print(debit)
#Insert into DB Table
sql = ("INSERT INTO debit (data_debit) VALUES (%s)")
val=debit,
cur.execute(sql,val)
mydb.commit()
print(cur.rowcount, "record inserted.")
cur.close()
mydb.close()
Thanks for your help!
You only open your database connection once, at the start of the script, and you close that connection after making the first insert. Hence, second and subsequent inserts are failing. You should create a helper function which returns a database connection, and then call it each time you want to do DML:
def getConnection():
mydb = mysql.connector.connect(
host="localhost",
user="***",
passwd="***",
database="***")
return mydb
def INSERT_DEBIT(jsonData):
mydb = getConnection()
cur = mydb.cursor()
# Read json from MQTT
# rest of your code here...
cur.close()
mydb.close()

MYSQL closing and reestablishing connection to execute many queries

when i tried executing 30+ queries using a single connection in python script the queries were executed but the changes were not reflected in the database but when i closed and reestablished the connection for every 10 queries and executed the queries seemed to work why did this happen but this problem hasn't occured when i tried executing same 30+ queries using my command line why is it so
why should we reestablish the connection
This didn't work
import MySQLdb
con = MySQLdb.connect(hostname,user, password, dbname, port)
cur = con.cursor()
cur.execute(query1)
.
.
.
cur.execute(query50)
cur.execute('commit')
cur.close()
con.close()
This Worked
import MySQLdb
con = MySQLdb.connect(hostname,user, password, dbname, port)
cur = con.cursor()
cur.execute(query1)
.
.
cur.execute(query10)
cur.execute('commit')
cur.close()
con.close()
#reestablished connection
con = MySQLdb.connect(hostname,user, password, dbname, port)
cur = con.cursor()
cur.execute(query11)
.
.
cur.execute(query20)
cur.execute('commit')
cur.close()
con.close()
#reestablished connection
con = MySQLdb.connect(hostname,user, password, dbname, port)
cur = con.cursor()
cur.execute(query21)
.
.
cur.execute(query30)
cur.execute('commit')
cur.close()
con.close()

Categories