Reputation: 1033
I impored MySQLdb to use in python but i am getting the following error:
File "test.py", line 76, in <module>
db = Database()
File "test.py", line 18, in __init__
self.connection = MySQLdb.connect(host = self.host, user = self.user, passwd = self.passwd, db = self.db)
File "/home/ue/.pythonbrew/pythons/Python-2.7.5/lib/python2.7/site-packages/MySQLdb/__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "/home/ue/.pythonbrew/pythons/Python-2.7.5/lib/python2.7/site-packages/MySQLdb/connections.py", line 193, in __init__
super(Connection, self).__init__(*args, **kwargs2)
_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")
Exception AttributeError: "Database instance has no attribute 'connection'" in <bound method Database.__del__ of <__main__.Database instance at 0xb74cf80c>> ignored
I have seen other posts but none of them is helping me. I can even restart mysql as I cannot find /var/run/mysqld/
I do not think there is an error in the code as it is from Mike Hibberts Python video lectures: http://www.youtube.com/watch?v=FFdNteScYe4&list=PLxxA5z-8B2xm1yUDAh2_pXGWBTePjCa3n
Would really really appreciate help in this.
Upvotes: 0
Views: 1226
Reputation: 313
I think, you should use some msyql client to check your mysql database first. #2002 error means it can not connect to mysql, I have confront this cause I have not start mysql server.
Upvotes: 1
Reputation: 1033
@Lego Stormtroopr
I have added my code here. Sorry abt that, I should not assume that.
import MySQLdb
class Database:
host = "localhost"
user = "testuser"
passwd = "testpass"
db = "test"
def __init__(self):
self.connection = MySQLdb.connect(host = self.host, user = self.user, passwd = self.passwd, db = self.db)
def query(self, q):
cursor = self.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute(q)
self.connection.commit()
return cursor.fetchall()
def __del__(self):
self.connection.close()
if __name__ == "__main__":
db = Database()
q = "DELETE FROM testTable"
db.query(q)
q = """
INSERT INTO testTable
('name', 'age')
VALUES
('Mike', 39),
('Michael', 32),
('Angela', 21)
"""
db.query(q)
q = """
SELECT * FROM testTable
WHERE age = 21
"""
people = db.query(q)
for person in people:
print "Found: %s" % person['name']
Upvotes: 0