python对数据库的操作

首先引入模块

py文件中引入pymysql

from pymysql import *

Connection 对象

用于建立与数据库的连接

创建对象:调用connect()方法

conn=connect(参数列表)

· 参数host接的mysql主机IP,如果本机是'localhost'

· 参数port接的mysql主机的端口,默3306

· 参数database:数据的名称

· 参数user接的用

· 参数password接的密

· 参数charset:通信采用的编码方式,推荐使用utf8

cursor游标对象

cursor1 = con.cursor()

count = cursor1.execute(sql语句)  # 返回查到的数据个数

cursor1.fetchone() # 获取一个数据

cursor1.fetchmany(5) # 获取多个数据

cursor1.fetchall()  # 获取所有数据

任务结束后关闭cursor,connect

con.close( )

cursor1.close( )


例如:

# 1、导入pymysql
from pymysql import *

# 2、创建连接对象
con = connect(host= '192.168.205.132',port = 3306,user = 'root', password ='mysql',
        database = 'School',charset = 'utf8')

# 3、创建游标对象 cursor
cursors = con.cursor()

# 4、执行sql
sql = "select * from goods"

# 5、执行sql语句  execute:执行
# 返回受影响的行数
count = cursors.execute(sql)

# fetch:获取、获得---->get
# fetchone一次只拿一条数据
# for i in range(count):
#     print(cursors.fetchone())

#fetchmany 获取指定条数的数据
# for i in cursors.fetchmany(5):
#     print(i)
# print(cursors.fetchmany(5))

#fetchall 获取全部数据
for i in cursors.fetchall():
    print(i)

print(count)

# 6、关闭游标对象
cursors.close()

# 7、关闭连接对象
con.close()

数据的增加删除修改!!!!!!!!!!!

其实很简单,我们只需修改mysql语句

例如插入数据:

sql = "insert into goods_brands values(0,'微软')"

例如修改数据:

sql = "update goods_brands set name='内涵段子' where id = 18"

例如删除数据:

sql = "delete from goods_brands where id = 18"

但是注意最后要加上con.commit()把数据提交,这是pymsql的一个功能,防止误操作,只有确认提交才会真正修改数据库


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值