What to use to connect to database in python3

(*-*)浩
Release: 2019-08-01 15:30:51
Original
2537 people have browsed it

What is PyMySQL?

What to use to connect to database in python3

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
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!