Python3.4 how to connect to mysql pymysql to connect to mysql database, python3.4pymysql
This article describes how to connect Python 3 4 to the mysql database. In Python 3 4, mysqldb of Python 2 7 cannot connect to the mysql database. You can use pymysql.
In python3.4, mysqldb of python2.7 cannot connect to the mysql database. You can use pymysql to connect to mysql.
Procedure:
Serial Number Description
1 go to github to download the pymysql installation package pymysql https://github.com/PyMySQL/PyMySQL
2. decompress the package to a drive letter.
3. Open the cmd window (in Windows) and run the command in the root directory of pymysql. python setup. py install
4. Import pymysql in the program
5. Connect to the database
Database operation API documentation connection: http://legacy.python.org/dev/peps/pep-0249/
Example:
Sample Code:
_ Author _ = 'qindongliang'
# Import a pymysql package
Import pymysql
Try:
# Get A database connection, note that if it is a UTF-8 type, you need to develop a database
Conn = pymysql. connect (host = 'localhost', user = 'root', passwd = 'qin', db = 'people', port = 3306, charset = 'utf8 ')
Cur = conn. cursor () # Get a cursor
Cur.exe cute ('select * from person ')
Data = cur. fetchall ()
For d in data:
# Note that the int type must be escaped using the str Function
Print ("ID:" + str (d [0]) + 'name: '+ d [1] + "Gender:" + d [2])
Cur. close () # close the cursor
Conn. close () # release database resources
Failed t Exception: print ("Exception occurred ")
Output result:
D: \ python \ python.exe D:/pythonide/pythonprojectworkspace/python/mysql. py
ID: 1 Name: Qin Tian Gender: male
ID: 2 Name: Wang Jing Gender: Female
Process finished with exit code 0
- This article is from: Linux technical network
- Link: http://www.ahlinux.com/python/13641.html