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()