I'd like to access mydb variable on line 15, but it can¨t be seen. Even though I would go for Global variable, it still stays the same.
Code:
import mysql.connector
def connect():
try:
mydb = mysql.connector.connect(
host='localhost',
user='root',
password='12345',
database="Food"
)
except:
print("Possibly wrong PWD")
mycursor = mydb.cursor()
Error:
NameError: name 'mydb' is not defined
Thanks a lot.
did you call a function? I see you defined it, but don't see where you call it. Try
import mysql.connector
def connect():
try:
return mysql.connector.connect(
host='localhost',
user='root',
password='12345',
database="Food"
)
except:
print("Possibly wrong PWD")
mydb = connect()
mycursor = mydb.cursor()
Related
When I try to use mysql.connector in python, nothing happens, the terminal freezes and nothing happens infinitely
import mysql.connector
hostname = '********.mysql.database.azure.com'
username = '***************.mysql.database.azure.com'
password = '*******'
database = '*********'
port = 3306
print("Hello World");
try:
# conn = mariadb.connect(
conn = mysql.connector.connect(
user=username,
password=password,
host=hostname,
port=port,
ssl_ca="BaltimoreCyberTrustRoot.crt.pem"
)
print("Connection established")
except:
print("Error")
C:\Users\Nathan Almeida\Documents\workspace\research-api>python connection.py
Hello World
Imagem com o codigo
Problem solved
I took a look at the mysql documentation and found mysql.connector.MySQLConnection.
I changed mysql.connector.connect to mysql.connector.MySQLConnection and it worked.
But I still don't understand why mysql.connector.connect doesn't work and freezes the terminal.
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?
Hi i have problem regarding db connection. i want to put db connection in seprate file and can use in multiple files.
i have tried this
connection.py
import pymysql
import mysql.connector
class Connection:
def __init__(self):
conn = mysql.connector.connect(host="localhost", user="root", password="", db="")
cur = conn.cursor()
return cur, conn
main.py
import connection
cur, conn = connection.Connection()
Error
cur, conn = connection.Connection()
TypeError: __init__() should return None, not 'tuple'
connection.py
import pymysql
import mysql.connector
def get_connection():
conn = mysql.connector.connect(host="localhost", user="root", password="", db="")
cur = conn.cursor()
return cur, conn
main.py
import connection
cur, conn = connection.get_connection()
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()
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
)