Home >Backend Development >Python Tutorial >What to use to connect to database in python3
What is PyMySQL?
PyMySQL is a library used to connect to the MySQL database in the Python3.x version, In Python2, mysqldb is used.
PyMySQL follows the Python Database API v2.0 specification and includes the pure-Python MySQL client library. (Recommended learning: Python video tutorial)
PyMySQL installation
Before using PyMySQL, we need to ensure that PyMySQL is installed.
PyMySQL download address: https://github.com/PyMySQL/PyMySQL.
If it has not been installed yet, we can use the following command to install the latest version of PyMySQL:
$ pip3 install PyMySQL
Before connecting to the database, please confirm the following:
You have created the database TESTDB.
In the TESTDB database you have created the table EMPLOYEE
The fields of the EMPLOYEE table are FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
The user name used to connect to the database TESTDB is "testuser" and the password is "test123". You can set it yourself or directly use the root username and password. For Mysql database user authorization, please use the Grant command.
The Python MySQLdb module has been installed on your machine.
The following examples link to Mysql's TESTDB database:
#!/usr/bin/python3 import pymysql # 打开数据库连接 db = pymysql.connect("localhost","testuser","test123","TESTDB" ) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL 查询 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法获取单条数据. data = cursor.fetchone() print ("Database version : %s " % data) # 关闭数据库连接 db.close()
For more Python-related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of What to use to connect to database in python3. For more information, please follow other related articles on the PHP Chinese website!