I am on a hobby project, working on a python mysql database, where I simple make the connection and perform some basic action, but when I run it give me reference error. My whole code looks like;
# My Mysql Library
import mysql.connector
#My Database class
class Database(object):
# Class Attributes
connection = None
cursor = None
TABLE_NAME = "customer"
# My constructor
def __init__(self):
""" This constructor is used to connect the database with my python application
and make the connection object and then create the cursor object with help
of it we create the table if not exists """
connection = mysql.connector.connect(
host="localhost",
user="root",
password="mypassword",
database="mydb"
)
# Initialize the cursor
self.cursor = connection.cursor()
# Create Individual Table
self.cursor.execute(f"""
CREATE TABLE IF NOT EXISTS {self.TABLE_NAME}(
cust_id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
cust_name VARCHAR(35),
cust_f_name VARCHAR(35),
cust_cno INTEGER(20) UNIQUE,
cust_address VARCHAR(50)
);
""")
def insert_data(self, name, f_name, cno, address):
""" This method is used to insert the value which is provided by user
With the help of GUI """
# self.cursor.execute(f"""
# INSERT INTO {Database.TABLE_NAME}(cust_name, cust_f_name, cust_cno, cust_address)
# VALUES (%, %, %, %, %)
# """, (name, f_name, cno, address))
# Insert Query
insert_query = f"""
INSERT INTO {Database.TABLE_NAME}(
cust_name, cust_f_name, cust_cno, cust_address
) VALUES (%, %, %, %);
"""
# Tuple of values which is to me inserted into the database
values = (name, f_name, cno, address)
# Execute the query and commit the data
self.cursor.execute(insert_query, values)
self.commit_data()
def commit_data(self):
""" This method is used to save all the data inside the db after data insertion"""
self.connection.commit()
def close_db(self):
""" This will close the database connection and cursor after performing everything"""
self.cursor.close()
self.connection.close()
# Main Body
db = Database()
db.insert_data("feezan", "noor", 552, "shaidu")
**But When I run it give the following error**
Traceback (most recent call last):
File "C:/Users/Feezan Khattak/OneDrive/Documents/My programming/Python Programming/PyQt5 Disgner/7- Data Entry With
Images/Database/MyDatabase.py", line 72, in
db.insert_data("feezan", "noor", 552, "shaidu")
File "C:/Users/Feezan Khattak/OneDrive/Documents/My programming/Python Programming/PyQt5 Disgner/7- Data Entry With
Images/Database/MyDatabase.py", line 58, in insert_data
self.cursor.execute(insert_query, values)
File "C:\Users\Feezan Khattak\AppData\Local\Programs\Python\Python37\lib\site-packages\mysql\connector\cursor_cext.py",
line 232, in execute
if not self._cnx:
ReferenceError: weakly-referenced object no longer exists
I will be highly appreciated your answers.
Related
So I'm trying to insert a class variable into a mysql database and I'm having problems.
mysql.connector.errors.ProgrammingError: 1050 (42S01): Table 'ordertable' already exists
This message pops up when i try to insert values into a table even when i know the table exists.
order.py
import tkinter
from tkinter import *
import connection
import mysql.connector
class MenuWindow():
def init(self):
db = mysql.connector.connect(host="localhost",user="root", passwd="", database = "pizza")
mycursor =db.cursor()
orderData = [(None, self.varTotal.get())]
for element in orderData:
mycursor.execute("INSERT INTO ordertable (orderid,total) VALUES (?,?)", element)
db.commit()
The table is created in this file
connection.py
def get_connection():
db = mysql.connector.connect(host="localhost",user="root", passwd="", database = "pizza")
mycursor = db.cursor()
mycursor.execute("CREATE TABLE orderTable (orderid INT AUTO_INCREMENT PRIMARY KEY, total INT)")
The error message does not complain about the insert. It complains about the create, because connection.py attempts to create the table when it already exists.
You only need to create the table exactly once, you do not need to create it whenever you reconnect.
Remove the line of
mycursor.execute("CREATE TABLE orderTable (orderid INT AUTO_INCREMENT PRIMARY KEY, total INT)")
Whenever I want to insert data in a pandas dataframe to the into a postgresql database I get this error
error: extra data after last expected column CONTEXT: COPY recommendations, line 1: "0,4070,"[5963, 8257, 9974, 7546, 11251, 5203, 102888, 8098, 101198, 10950]""
The dataframe consist of three column, the first and second column are of type integers and the third column is a list of integers.
I created a table in PostgreSQL using this function below
def create_table(query: str) -> None:
"""
:param query: A string of the query to create table in the database
:return: None
"""
try:
logger.info("Creating the table in the database")
conn = psycopg2.connect(host=HOST, dbname=DATABASE_NAME, user=USER, password=PASSWORD, port=PORT)
cur = conn.cursor()
cur.execute(query)
conn.commit()
logger.info("Successfully created a table in the database using this query {}".format(query))
return
except (Exception, psycopg2.Error) as e:
logger.error("An error occurred while creating a table using the query {} with exception {}".format(query, e))
finally:
if conn is not None:
conn.close()
logger.info("Connection closed!")
The query passed into this function is this:
create_table_query = '''CREATE TABLE Recommendations
(id INT NOT NULL,
applicantId INT NOT NULL,
recommendation INTEGER[],
PRIMARY KEY(id),
CONSTRAINT applicantId
FOREIGN KEY(applicantId)
REFERENCES public."Applicant"(id)
ON DELETE CASCADE
ON UPDATE CASCADE
); '''
I then use the function below to copy the data frame to the created table in postgres.
def copy_from_file(df: pd.DataFrame, table: str = "recommendations") -> None:
"""
Here we are going save the dataframe on disk as
a csv file, load the csv file
and use copy_from() to copy it to the table
"""
conn = psycopg2.connect(host=HOST, dbname=DATABASE_NAME, user=USER, password=PASSWORD, port=PORT)
# Save the dataframe to disk
tmp_df = "./tmp_dataframe.csv"
df.to_csv(tmp_df, index_label='id', header=False)
f = open(tmp_df, 'r')
cursor = conn.cursor()
try:
cursor.copy_from(f, table, sep=",")
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
os.remove(tmp_df)
logger.error("Error: %s" % error)
conn.rollback()
cursor.close()
logger.info("copy_from_file() done")
cursor.close()
os.remove(tmp_df)
And then I still get this error: extra data after last expected column CONTEXT: COPY recommendations, line 1: "0,4070,"[5963, 8257, 9974, 7546, 11251, 5203, 102888, 8098, 101198, 10950]"" please any recommendations on how to fix this issue? Thanks
copy_from uses the text format, not the csv format. You told it to use , as the separator, but that doesn't change the protecting method it is trying to use. So the commas inside the quotes are not treated as being protected, they are treated as field separators, and so of course there are too many of them.
I think you need to use copy_expert and tell it to use the csv format.
I'm newer to OOP in Python, and have been trying for awhile to use my database class database within another class.
How can I do so?
class database(object):
def connect_db(self):
try:
import sqlite3 as sqli
connection = sqli.connect('pw.db')
cur = connection.cursor()
except:
print("There was an error connecting to the database.")
I've been trying to like this, but it doesnt work:
import db_helper as dbh
class account_settings(object):
def create_account(self):
setting_username = input('\nUsername?\n')
setting_password = input('\nPassword?\n')
cur = db.connect_db()
with cur:
cur.execute('''
CREATE TABLE IF NOT EXISTS my_passwords(
id INTEGER PRIMARY KEY AUTOINCREMENT NULL,
password text UNIQUE
)
''')
try:
cur.execute('INSERT INTO my_passwords(password) VALUES(?)', (self.create_password(),) )
except:
print("Error occurred trying to insert password into db. Please retry")
c = account_settings()
c.create_account()
new error:
File "settings.py", line 30, in <module>
c.create_account()
File "settings.py", line 15, in create_account
with cur:
AttributeError: __exit__
You need to learn about variable scope. db.connect_db() creates a cursor connection with the name cur, but does not do anything with it; when that method finishes, the object is destroyed. In particular, it never makes it back to the create_account method.
There is a simple way to solve this: return the object back to the method, and use it there.
def connect_db(self):
...
cur = connection.cursor()
return cur
...
def create_account(self):
cur = db.connect_db()
with cur:
or even beter:
with db.connect_db()
Note that really, neither of these should be classes. Classes in Python are really only useful when you're keeping some kind of state, which isn't happening here. connect_db and create_account should just be standalone functions in their respective modules.
I have prepared a stored procedure that runs fine if I make the call from a MySQL console. But when running in python with mysql.connector controller, performs the insertion procedure correctly.
However, the result does not bring with fectchall() because the following error:
File "/home/sis1/prueba/prueba.py", line 16, in <module>
reg=conn.fetchall()
File "/usr/lib/pymodules/python2.7/mysql/connector/cursor.py", line 551, in fetchall
raise errors.InterfaceError("No result set to fetch from.")
InterfaceError: No result set to fetch from.`
Here's the stored procedure:
DROP PROCEDURE IF EXISTS pr_prueba;
CREATE DEFINER = rooter#localhost PROCEDURE pr_prueba(IN p_emp tinyint,OUT mensaje varchar(50),OUT registros integer)
BEGIN
DECLARE numreg INT (10);
DECLARE tabla VARCHAR (30);
DECLARE emp TINYINT(2);
SET #tabla = CONCAT("emp",p_emp,".usuario");
SET #emp = CAST(p_emp AS UNSIGNED);
SET #sql_text = CONCAT("INSERT INTO ",#tabla," ( name, lastname ) (SELECT UPPER(name), UPPER(lastname) FROM tablas GROUP BY tablas.operador);");
PREPARE stmt FROM #sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #mensaje="OK";
SET #sql_text = CONCAT("SELECT COUNT(*) INTO #numreg FROM ",#tabla,";");
PREPARE stmt FROM #sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #registros=#numreg;
SELECT #mensaje as mensaje, #registros as registros;
END ;
Here's python code:
import sys
import mysql.connector
if (__name__=='__main__'):
db = mysql.connector.connect(host="192.168.1.1",user="de",passwd="de2",database="dbim" )
conn = db.cursor()
args=(1,"",0)
conn.callproc("pr_prueba",args)
reg=conn.fetchall()
try:
db.commit()
except:
db.rollback()
print "error"
conn.close()
db.close()
I found the problem myself. I had to change the line:
reg=conn.fetchall()
for this:
for reg in conn.next_proc_resultset():
pass
I do not know if it is the best solution but it works
I am a programming beginner, and would like to get a little help with learning SQLite and Python.
Currently, I have a database called "Status.db" which contains two columns. These columns are "stamp", type INT, and "messages", type TEXT, consecutively.
The code I am using to try to read one instance of messages, with a particular stamp, ID, into a variable "output" is as follows:
#cherrypy.expose
def comment(self, ID = None):
con = lite.connect('static/database/Status.db')
with con:
cur = con.cursor()
cur.execute("SELECT messages FROM Status WHERE stamp is ?", (ID,))
temp = cur.fetchone()
output = temp[0]
However, when i execute this code, I get an error message that reads:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "proj1base.py", line 176, in comment
output = temp[0]
TypeError: 'NoneType' object is not subscriptable
I am wondering if anyone could clarify to me what this error means, and what i could do to make it work.
Thanks in advance!
EDIT:
Here is the code that created and writes into the database
#cherrypy.expose
def writeStatus(self, newStatus=None, post=None):
"""Update the status file with the most recent status update
by inserting a timestamp and new status into a database
"""
con = lite.connect('static/database/Status.db')
stamp = time()
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Status(stamp INT, messages TEXT)")
cur.execute("INSERT INTO Status VALUES(?, ?)", (stamp, newStatus))
That means that fetchone() is returning None, which means that your SQL query isn't returning any result rows.
This is probably because you should use = instead of is in your SQL:
SELECT messages FROM Status WHERE stamp = ?