PyMySQL 连接数据库

本文介绍如何使用Python通过pymysql库连接MySQL数据库并进行增删改查操作。具体包括数据库连接配置、表的创建、数据的插入、删除、更新及查询等基本功能实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据库连接:
连接数据库前,请先确认以下事项:
1.您已经创建了数据库school。
2.在school数据库中您已经创建了表test1。
3.test1表字段为 id,name,sex。
4.连接数据库school使用的用户名为 "root" ,密码为 "123456",你可以可以自己设定或者直接使用root用户名及其密码,Mysql数据库用户授权请使用Grant命令。
5.在你的机子上已经安装了pymysql。

创建数据库表:
[python]   view plain  copy
  1. import pymysql  
  2. def createtable():  
  3.     #1.建立连接  
  4.     conn=pymysql.connect('localhost','root','123456','school')  
  5.     #2.得到cursor对象  
  6.     mycursor=conn.cursor()  
  7.     #3.执行sql语句  
  8.     sqlstr=''''' 
  9.        create table test1( 
  10.            id int PRIMARY KEY auto_increment, 
  11.            name varchar(20) not null, 
  12.            sex char(2) 
  13.        )DEFAULT CHARSET UTF8 
  14.     '''  
  15.     mycursor.execute(sqlstr)  
  16.     #4.获取执行结果,如果是创建表的语句则返回none  
  17.     mycursor.fetchone()  
  18.     #5.关闭连接对象  
  19.     conn.close()  
  20. createtable()  
在数据库表中添加内容:
[python]   view plain  copy
  1. import pymysql  
  2. def inserttable():  
  3.     conn = pymysql.connect('localhost''root''123456''school')  
  4.     mycursor = conn.cursor()  
  5.     sqlstr=''''' 
  6.        insert into test1(name,sex) values('李四','男') 
  7.     '''.encode('utf8')  
  8.     try:  
  9.         # 执行sql语句  
  10.         mycursor.execute(sqlstr)  
  11.         # 提交到数据库执行  
  12.         conn.commit()  
  13.     except:  
  14.         # 如果发生错误则回滚  
  15.         conn.rollback()  
  16.     conn.close()  
  17. inserttable()  
在数据库表中删除内容:
[python]   view plain  copy
  1. import pymysql  
  2. #提取公共连接方法  
  3. def getconn():  
  4.     conn = pymysql.connect('localhost''root''123456''school')  
  5.     mycursor=conn.cursor()  
  6.     return [conn,mycursor]  
  7. def deltable():  
  8.     conn=getconn()  
  9.     sqlstr='''''delete from test1 WHERE id=1'''  
  10.     try:  
  11.         print(conn[1].execute(sqlstr))  
  12.         conn[0].commit()  
  13.     except:  
  14.         conn[0].rollback()  
  15.     conn[0].close()  
  16. deltable()  
在数据库表中修改内容:
[python]   view plain  copy
  1. import pymysql  
  2. #提取公共连接方法  
  3. def getconn():  
  4.     conn = pymysql.connect('localhost''root''123456''school')  
  5.     mycursor=conn.cursor()  
  6.     return [conn,mycursor]  
  7. def updatetable():  
  8.     conn=getconn()  
  9.     sqlstr='''''update test1 set NAME='瑞克' WHERE id=3'''  
  10.     try:  
  11.         print(conn[1].execute(sqlstr))  
  12.         conn[0].commit()  
  13.     except:  
  14.         conn[0].rollback()  
  15.     conn[0].close()  
  16. updatetable()  

[python]   view plain  copy
  1. import pymysql  
  2. #提取公共连接方法  
  3. def getconn():  
  4.     conn = pymysql.connect('localhost''root''123456''school')  
  5.     mycursor=conn.cursor()  
  6.     return [conn,mycursor]  
  7. def operationtable(sqlstr):  
  8.     conn=getconn()  
  9.     try:  
  10.         print(conn[1].execute(sqlstr))  
  11.         conn[0].commit()  
  12.     except:  
  13.         conn[0].rollback()  
  14.     conn[0].close()  
  15. #删除  
  16. #sqlstr='''delete from test1 WHERE id=1'''  
  17. #修改  
  18. #sqlstr='''update test1 set NAME='瑞克' WHERE id=3'''  
  19. #增加  
  20. sqlstr='''''insert into test1(name,sex) values('王五','男')'''  
  21. operationtable(sqlstr)  

数据库查询:
Python查询Mysql使用 fetchone()方法获取单条数据, 使用fetchall()方法获取多条数据。
fetchone(): 该方法获取下一个查询结果集。结果集是一个对象。
fetchall(): 接收全部的返回结果行。
rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

[python]   view plain  copy
  1. import pymysql  
  2. #提取公共连接方法  
  3. def getconn():  
  4.     conn = pymysql.connect('localhost''root''123456''school')  
  5.     mycursor=conn.cursor()  
  6.     return [conn,mycursor]  
  7. class Test():  
  8.     def __init__(self,id=None,name=None,sex=None):  
  9.         self.id=id  
  10.         self.name=name  
  11.         self.sex=sex  
  12.     def __str__(self):  
  13.         return 'id:'+str(self.id)+',name:'+self.name+',sex:'+self.sex  
  14. #查询  
  15. def querytable():  
  16.     list=[]  
  17.     conn=getconn()  
  18.     sqlstr='''''select id,name,sex from test1'''  
  19.     conn[1].execute(sqlstr)  
  20.     rs=conn[1].fetchall()  
  21.     for row in rs:  
  22.         test=Test(row[0],row[1],row[2])  
  23.         list.append(test)  
  24.     conn[0].close()  
  25.     return list  
  26. testlist=querytable()  
  27. for row in testlist:  
  28.     print(row)  
结果:
id:2,name:张三,sex:男
id:3,name:瑞克,sex:男
id:4,name:王五,sex:男
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值