I am using below code for connectivity:
import MySQLdb
db = MySQLdb.connect("localhost","root","root","test" )
cursor = db.cursor()
cursor.execute("SELECT * from student")
data = cursor.fetchone()
print "Database result : %s " % data
db.close()
i am getting below error during running the file:
Traceback (most recent call last):
File "C:/Python27/xsxs.py", line 5, in <module>
db = MySQLdb.connect("localhost","root","root","test" )
File "C:\Python27\lib\site-packages\MySQLdb\__init__.py", line 81, in Connect
return Connection(*args, **kwargs)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 187, in __init__
super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")
How can i solve it.
-
Are your database/server credentials correctly written? Try running "mysql -u root -p root" in the shell and tell us what you see. Then try "use test" in the mysql shell and check if you can select your database.Aneesh Dogra– Aneesh Dogra2013年03月22日 09:19:16 +00:00Commented Mar 22, 2013 at 9:19
-
Your code is attempting to connect to a mySQL server running on the same computer as the python code. If that's what you wanted then most likely, your database on the local machine is not running and you need to start it before running the python code.Paul– Paul2013年03月22日 09:19:32 +00:00Commented Mar 22, 2013 at 9:19
3 Answers 3
the problem seems to be that no mysql server is running on your windwos host. You either have to install it (http://www.mysql.de/why-mysql/windows/) or have to choose another server like
db = MySQLdb.connect("my_mysql_host.mydomain.tld","root","root","test" )
Thats it.
Greetings
Sign up to request clarification or add additional context in comments.
Comments
Check you connectionstring:
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="username", # your username
passwd="Pswrd", # your password
db="MyDB") # name of the data base
This SO will help you:
How do I connect to a MySQL Database in Python?
Best Regards
answered Mar 22, 2013 at 9:21
BizApps
6,1409 gold badges43 silver badges65 bronze badges
Comments
Install mysql connector using pip,
sudo pip install mysql-connector-python
Sample code to connect a local database named TCS and select data from table named student,
import mysql.connector
cnx = mysql.connector.connect(user='root', password='1234',
host='localhost',
database='TCS')
try:
cursor = cnx.cursor()
cursor.execute("select * from student")
result = cursor.fetchall()
print result
finally:
cnx.close()
answered Jul 3, 2018 at 13:30
Codemaker2015
16.1k9 gold badges118 silver badges93 bronze badges
Comments
lang-py