I'm running python to connect to mariadb sql and do database create, table create and insert data. I'm getting error
local variable 'mariadb_connection' referenced before assignment
I follow the code below.
import mysql.connector as mariadb
def dbconnect():
try:
mariadb_connection = mariadb.connect(
host="192.168.100.115",
user="usr1",
password="usr1",
database="mydb",
)
except Exception as e:
sys.exit("Can't connect to Database")
return mariadb_connection
def create_db(db_name, table_name):
try:
mariadb_connection = dbconnect()
cursor = mariadb_connection.cursor()
# Create Database:
cursor.execute("CREATE DATABASE IF NOT EXISTS {}".format(db_name))
cursor.execute(
"""CREATE TABLE IF NOT EXISTS {}.{}(id INT primary key auto_increment, ser_num int(20), log_stat varchar(50), descrp varchar(50));""".format(db_name, table_name))
with open(latestFile, 'r') as f:
data = json.load(f)
sql = "INSERT INTO `table1` (`ser_num`, `log_stat`, `descrp`) VALUES ( %(ser_num)s, %(log_stat)s, %(descrp)s )"
cursor.executemany( sql, data['response']['data_log']['data'])
mariadb_connection.commit()
mariadb_connection.close()
except Exception as e:
print e
I really appreciate someone could advise me what is the problem to resolve... I have tried for few days without any luck. Please help me. Thank you for your support and help.
#After updated above as per comment by bruno.... i can run the script but it return error '1044 (42000): Access denied for user 'usr1'@'%' to database 'mydb'.. usr1 have read/write privilege