python连接数据库详细操作 ———2021-07-14

python连接数据库详细操作

#导入
import pymysql

查询语句执行函数

def connect_db():
#连接数据库
db = pymysql.connect(host=“10.11.1.100”,user=“root”,passwd=“MyNewPass4!”,database=“yz_match_dev”,charset=“utf8”)
#生成游标对象
cursor = db.cursor()
#执行指定的sql语句
cursor.execute(“select * from yx_visit_ip where id = 50”)
#fetchall是拿到sql执行的所有结果,fetchone是拿一条数据,fetchmany(5)表示拿查询结果的前五条
result= cursor.fetchall()
#占位符应用 f “{变量名}”
print(f"数据库的版本号是:{result}")
#因为表中的每一条信息row都是列表的形式存储 所以可以做一下展示 找出单独的字段对应数据
for row in result:
id = row[0]
ip = row[1]
state = row[2]
print(id,ip,state)
#关闭数据库
db.close()

创建库的函数

def create_db():
# 连接数据库
db = pymysql.connect(host=“10.11.1.100”, user=“root”, passwd=“MyNewPass4!”, charset=“utf8”)
#生成游标对象
cursor = db.cursor()
# 执行指定的sql语句
cursor.execute(“create database if not exists woniuddb”)
#关闭数据库
db.close()

创建对应库里的表的函数

def create_table_db():
# 连接数据库
db = pymysql.connect(host=“10.11.1.100”, user=“root”, passwd=“MyNewPass4!”, database=“yz_match_dev”, charset=“utf8”)
# 生成游标对象
cursor = db.cursor()
#执行指定的sql语句
#如果要执行的sql语句比较长,那么则想以下这种方式执行sql语句 用三引号的方式括起来
sql = ‘’’ create table student (
id int primary key,
first_name char(20) not null,
last_name char(20),
age int ,
sex char(1),
class int
)
‘’’
cursor.execute(sql)
db.close()

插入表数据的函数

def insert_table_db():
db = pymysql.connect(host=“10.11.1.100”,user=“root”,database=“yz_match_dev”,passwd=“MyNewPass4!”,charset=“utf8”)
cursor = db.cursor()
sql = ‘’’
insert into yx_visit_ip(id,ip,state,is_default,start_time,end_time,is_valid,created_at) values
(‘83’,‘99.99.99.99’,‘0’,‘0’,‘2019-02-14 00:00:00’,‘2012-02-14 00:00:00’,1,‘2019-02-14 00:00:00’)
‘’’
#执行这个sql语句后的返回值 回告诉我们受影响多少行 也就是插入成功了多少
effect_rows=cursor.execute(sql)
#因为插入语句是dml 所以要想插入语句生效 必须要提交一下
db.commit()
db.close()

更改语句函数

def update_table_db():
db = pymysql.connect(host=“10.11.1.100”,user=“root”,passwd=“MyNewPass4!”,database=“yz_match_dev”,charset=“utf8”)
cursor = db.cursor()
sql = ‘’’
update yx_visit_ip set ip = “255.255.255.255” where id = 50
‘’’
cursor.execute(sql)
#注意 update语句也是dml 语句 所以要进行提交
db.commit()
db.close()

删除语句函数

def del_table_db():
db = pymysql.connect(host=“10.11.1.100”, user=“root”, passwd=“MyNewPass4!”, database=“yz_match_dev”, charset=“utf8”)
cursor = db.cursor()
sql = ‘’’
delete from yx_visit_ip where id = 83
‘’’
cursor.execute(sql)
#注意 delete语句也是dml 语句 所以要进行提交
db.commit()
db.close()

调用各个函数

if name==“main”:
# connect_db()
# create_db()
# create_table_db()
#insert_table_db()
#update_table_db()
#del_table_db()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值