当前位置:网站首页>PyMySQL连接数据库
PyMySQL连接数据库
2022-04-23 06:11:00 【sunshinecxm_BJTU】
1.什么是PyMySQL?
PyMySQL是从Python连接到MySQL数据库服务器的接口。 它实现了Python数据库API v2.0,并包含一个纯Python的MySQL客户端库。 PyMySQL的目标是成为MySQLdb的替代品。
PyMySQL参考文档:http://pymysql.readthedocs.io/
2.如何安装PyMySQL?
通过pip命令来安装-
3.数据库连接在连接到MySQL数据库之前,请确保以下几点:
- 已经创建了一个数据库:test。
- 已经在test中创建了一个表:employee。
- employee表格包含:fist_name,last_name,age,sex和income字段。
- MySQL用户“root”和密码“123456”可以访问:test。
- Python模块PyMySQL已正确安装在您的计算机上。
- 已经通过MySQL教程了解MySQL基础知识。
创建表employee的语句为:
CREATE TABLE `employee` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`first_name` char(20) NOT NULL,
`last_name` char(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`income` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
实例
以下是Python通过PyMySQL模块接口连接MySQL数据库“test”的示例 -
注意:在 Windows 系统上,import PyMySQL 和 import pymysql 有区别。
#!/usr/bin/python3
#coding=utf-8
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)
# disconnect from server
db.close()
运行此脚本时,会产生以下结果 -
Database version : 5.7.14-log
如果使用数据源建立连接,则会返回连接对象并将其保存到db中以供进一步使用,否则将db设置为None。 接下来,db对象用于创建一个游标对象,用于执行SQL查询。 最后,在结果打印出来之前,它确保数据库连接关闭并释放资源。
4.创建数据库表
建立数据库连接后,可以使用创建的游标的execute方法将数据库表或记录创建到数据库表中。
示例
下面演示如何在数据库:test中创建一张数据库表:employee -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS employee")
# Create table as per requirement
sql = """CREATE TABLE `employee` ( `id` int(10) NOT NULL AUTO_INCREMENT, `first_name` char(20) NOT NULL, `last_name` char(20) DEFAULT NULL, `age` int(11) DEFAULT NULL, `sex` char(1) DEFAULT NULL, `income` float DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
cursor.execute(sql)
print("Created table Successfull.")
# disconnect from server
db.close()
运行此脚本时,会产生以下结果 -
Created table Successfull.
5.插入操作
当要将记录创建到数据库表中时,需要执行INSERT操作。
示例
以下示例执行SQL的INSERT语句以在EMPLOYEE表中创建一条(多条)记录 -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Mac', 'Su', 20, 'M', 5000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
## 再次插入一条记录
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME, AGE, SEX, INCOME) VALUES ('Kobe', 'Bryant', 40, 'M', 8000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
print (sql)
print('Yes, Insert Successfull.')
# disconnect from server
db.close()
运行此脚本时,会产生以下结果 -
Yes, Insert Successfull.
上述插入示例可以写成如下动态创建SQL查询 -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \ LAST_NAME, AGE, SEX, INCOME) \ VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Max', 'Su', 25, 'F', 2800)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
示例
以下代码段是另一种执行方式,可以直接传递参数 -
..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s", "%s")' % \
(user_id, password))
..................................
6.读取操作
任何数据库上的读操作表示要从数据库中读取获取一些有用的信息。
在建立数据库连接后,就可以对此数据库进行查询了。 可以使用fetchone()方法获取单条记录或fetchall()方法从数据库表中获取多个值。
fetchone() - 它获取查询结果集的下一行。 结果集是当使用游标对象来查询表时返回的对象。
fetchall() - 它获取结果集中的所有行。 如果已经从结果集中提取了一些行,则从结果集中检索剩余的行。
rowcount - 这是一个只读属性,并返回受execute()方法影响的行数。
示例
以下过程查询EMPLOYEE表中所有记录的工资超过1000员工记录信息 -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# 按字典返回
# cursor = db.cursor(pymysql.cursors.DictCursor)
# Prepare SQL query to select a record from the table.
sql = "SELECT * FROM EMPLOYEE \ WHERE INCOME > %d" % (1000)
#print (sql)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
#print (row)
fname = row[1]
lname = row[2]
age = row[3]
sex = row[4]
income = row[5]
# Now print fetched result
print ("name = %s %s,age = %s,sex = %s,income = %s" % \
(fname, lname, age, sex, income ))
except:
import traceback
traceback.print_exc()
print ("Error: unable to fetch data")
# disconnect from server
db.close()
name = Mac Su,age = 20,sex = M,income = 5000.0
name = Kobe Bryant,age = 40,sex = M,income = 8000.0
7.更新操作
UPDATE语句可对任何数据库中的数据进行更新操作,它可用于更新数据库中已有的一个或多个记录。
以下程序将所有SEX字段的值为“M”的记录的年龄(age字段)更新为增加一年。
#!/usr/bin/python3
#coding=utf-8
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
#cursor = db.cursor()
cursor = db.cursor(pymysql.cursors.DictCursor)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 \ WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
8.删除操作
当要从数据库中删除一些记录时,那么可以执行DELETE操作。 以下是删除EMPLOYEE中AGE超过40的所有记录的程序 -
#!/usr/bin/python3
#coding=utf-8
import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (40)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
版权声明
本文为[sunshinecxm_BJTU]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_36744449/article/details/123562410
边栏推荐
猜你喜欢
JVM basics you should know
[2021 book recommendation] kubernetes in production best practices
第2章 Pytorch基础1
PaddleOCR 图片文字提取
Component based learning (1) idea and Implementation
一款png生成webp,gif, apng,同时支持webp,gif, apng转化的工具iSparta
Record WebView shows another empty pit
Component learning (2) arouter principle learning
[2021 book recommendation] Red Hat Certified Engineer (RHCE) Study Guide
Itop4412 HDMI display (4.4.4_r1)
随机推荐
c语言编写一个猜数字游戏编写
Exploration of SendMessage principle of advanced handler
读书小记——Activity
Component learning
Tiny4412 HDMI display
MySQL笔记5_操作数据
JVM basics you should know
iTOP4412 SurfaceFlinger(4.0.3_r1)
xcode 编译速度慢的解决办法
Recyclerview 批量更新View:notifyItemRangeInserted、notifyItemRangeRemoved、notifyItemRangeChanged
Apprentissage par composantes
第2章 Pytorch基础2
ProcessBuilder工具类
Kotlin征途之data class [数据类]
三子棋小游戏
组件化学习(1)思想及实现方式
[2021 book recommendation] kubernetes in production best practices
[exynos4412] [itop4412] [android-k] add product options
素数求解的n种境界
Android暴露组件——被忽略的组件安全