python 修改库源码_Python实现mysql数据库增删改查

利用python操作mysql数据库用法简单,环境配置容易,本文将实现对库增、删、改、查的简易封装!

1. 环境配置

安装第三方包 ,导入模块 mysql.connector

pip install mysql-connector

2.使用说明

本文将提供add,delete,update,query以及connect五种方法,下边将详述使用参数:

方法名

描述

传入参数

return

connect

创建链接数据库*

opt:用户可传入自定义数据库链接信息

{'host':'','user':'','password':'','port':'','database':'','charset':''}

返回链接connect

add

插入

mydb:创建的链接connent;

sql:sql插入、更新语句

# sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"

# sql = "UPDATE sites SET name = %s WHERE name = %s"

val:插入、更新的值

# val = ("RUNOOB", "https://www.runoob.com")

# val = ("Zhihu", "ZH")

update

更新

delete

删除

mydb,sql

query

查询

list

说明:首先建立链接,其次再将获取到的链接进行数据库增删改查

3.源代码

# coding=utf-8

import mysql.connector #先安装mysql-connector-python-1.0.12-py3.3,再引入包 pip install mysql-connector

#创建链接数据库

def connect(opt):

config={'host':opt['host'] or '127.0.0.1',#默认127.0.0.1

'user':opt['user'] or 'root',

'password':opt['password'] or 'root',

'port':opt['port'] or 3306,#默认即为3306

'database':opt['database'] or 'hibernate',

'charset':opt['charset'] or 'utf8'#默认即为utf8

}

try:

mydb=mysql.connector.connect(**config)#connect方法加载config的配置进行数据库的连接,完成后用一个变量进行接收

except mysql.connector.Error as e:

print('数据库链接失败!',str(e))

else:#try没有异常的时候才会执行

print("数据库连接sucessfully!")

return mydb

# 插入

# sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"

# val = ("RUNOOB", "https://www.runoob.com")

def add(mydb,sql,val):

mycursor = mydb.cursor()

mycursor.execute(sql, val)

mydb.commit() # 数据表内容有更新,必须使用到该语句

print(mycursor.rowcount, "记录插入成功。")

# 更新

# sql = "UPDATE sites SET name = %s WHERE name = %s"

# val = ("Zhihu", "ZH")

def update(mydb,sql,val):

mycursor = mydb.cursor()

mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, " 条记录被修改")

# 查询

# sql="SELECT * FROM sites"

def query(mydb,sql):

mycursor = mydb.cursor()

mycursor.execute(sql)

myresult = mycursor.fetchall() # fetchall() 获取所有记录

for x in myresult:

print(x)

return myresult

# 删除

# sql = "DELETE FROM sites WHERE name = 'stackoverflow'"

def delete(mydb,sql):

mycursor = mydb.cursor()

mycursor.execute(sql)

mydb.commit()

print(mycursor.rowcount, " 条记录删除")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值