Home > Backend Development > Python Tutorial > Introduction to the method of connecting to the database in python

Introduction to the method of connecting to the database in python

黄舟
Release: 2018-05-11 17:37:00
Original
3771 people have browsed it

This article mainly introduces the method of connecting to the database in python in detail, which has certain reference value. Interested friends can refer to it

The MYSQL module does not currently support python3.0 or above. version, since the python I downloaded is version 3.0, I can only use other methods to connect to the database.

The solutions for Python3.x to connect to MySQL include: oursql, PyMySQL, myconnpy, etc. Here we mainly install pymysql

1. Installation

pymysql installation : Find the location of the python folder pip program and open the command window:

pip install pymysql3

2. Use

After the installation is complete, the specific steps for database connection are as follows

Introduce the API module.
Get the connection to the database.
Execute SQL statements and stored procedures.
Close the database connection.

import pymysql

#查询
#连接数据库
conn = pymysql.connect(host='数据库服务器名',user='用户名',passwd='密码',db='数据库名',pot='数据路端口号',charset='utf8')
#获取游标
cur = conn.cursor()
cur.execute('数据库查询语句')
#获取数据,fetchone获取一条数据,fetchall获取全部数据
data = cur.fetchall()
for d in data:
 print(d)
#关闭游标
cur.close()
#关闭数据库
conn.close()

#插入、删除,修改操作
#连接数据库
conn = pymysql.connect(host='数据库服务器名',user='用户名',passwd='密码',db='数据库名',pot='数据路端口号',charset='utf8')
#获取游标
cur = conn.cursor()
cur.execute('数据库插入语句')
#提交当前事务到数据库
conn.commit()
#rowcount:返回数据条数或影响行数
print('插入:',cur.rowcount,'条数据')
#关闭游标
cur.close()
#关闭数据库
conn.close()
Copy after login

You can add a try...except statement to the database operation to catch errors. When an error occurs, you can roll back the database operation and go back to before modification:

try:
 # 执行sql语句
 cur.execute(sql)
 # 提交到数据库执行
 cur.commit()
except:
 # 发生错误时回滚
 cur.rollback()

# 关闭游标
cur.close()
#关闭数据库
conn.close()
Copy after login

The above is the detailed content of Introduction to the method of connecting to the database in python. 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