简体   繁体   中英

how to connect a python code to database using mysql

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.

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

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM