Python操作MySQL

 

1.安装PyMySQL

使用pip命令安装PyMySQL库。

pip install PyMySQL

2.创建数据库

使用脚本create_employee.sql创建数据库mytestdb,以及创建数据表employee。

create_employee.sql代码如下:

create database if not exists mytestdb character set utf8;

use mytestdb;

drop table if exists `employee`;

create table `employee`(
  `id` int(11) not null auto_increment,
  `name` varchar(40) default null,
  `age` int default null,
  `sex` char(1) default null,
  `income` float default null,
  primary key (`id`)
)engine=innodb default charset=utf8;
mysql> source C:/Users/INT 3/Desktop/create_employee.sql;

3.数据库插入操作

import pymysql
#打开数据库连接
db = pymysql.connect(host='127.0.0.1', user='root',password='123456',
                     database='mytestdb',port=3306, charset='utf8')
#使用cursor()方法获取操作游标
cursor = db.cursor()
#SQL插入语句
sql = "insert into employee(name, age, sex, income) values('王五', 26, 'F', 9000)"
try:
    cursor.execute(sql)
    db.commit()
except Exception as e:
    print(e)
    db.rollback()
finally:
    db.close()

也可以使用变量向SQL语句中传递参数: 

import pymysql
#打开数据库连接
db = pymysql.connect(host='127.0.0.1', user='root',password='123456',
                     database='mytestdb',port=3306, charset='utf8')
cursor = db.cursor()
sql = "insert into employee(name, age, sex, income) values('%s', '%d', '%s', '%d')"%('张三',30, 'M', 6000)
try:
    cursor.execute(sql)
    db.commit()
except Exception as e:
    print(e)
    db.rollback()
finally:
    db.close()

4.批量插入操作

cursor.executemany批量执行sql语句。

import pymysql

db = pymysql.connect(host='127.0.0.1', user='root', password='123456', port=3306,
                     database='mytestdb', charset='utf8')
cursor = db.cursor()
sql = "insert into employee(name, age, sex, income)values (%s, %s, %s, %s)"
ls = []
employ1 = ('张三', 22, 'M', 7000)
employ2 = ('李四', 25, 'F', 8000)
ls.append(employ1)
ls.append(employ2)
try:
    #cursor.executemany批量执行sql语句
    cursor.executemany(sql, ls)
    #提交到数据库执行
    db.commit()
except Exception as e:
    print(e)
    db.rollback()
finally:
    db.close()

5.查询操作

python查询Mysql,使用fetchone()方法获取单条数据,使用fetchall()方法获取多条数据。
rowcount是一个只读属性,并返回execute()方法后影响的行数。

import pymysql
db = pymysql.connect(host='127.0.0.1', user='root', password='123456', database='mytestdb', port=3306, charset='utf8')
#使用cursor方法操作游标
cursor = db.cursor()
sql = "select * from employee where income > '%d'" %(2000)
try:
    #执行sql语句
    cursor.execute(sql)
    #获取所有记录列表
    results = cursor.fetchall()
    for row in results:
        id = row[0]
        name = row[1]
        age = row[2]
        sex = row[3]
        income = row[4]
        #打印结果
        print("id=%s, name=%s, age=%d, sex=%s, income=%d" %(id, name, age, sex, income))
except Exception as e:
    print(e)
finally:
    db.close()

6.更新操作

#数据库更新操作
import pymysql
db = pymysql.connect(host='127.0.0.1', user='root', password='123456',
                     database='mytestdb', port=3306, charset='utf8')
cursor = db.cursor()
sql = "update employee set age = '%d' where id = '%s'"%(28, 1)
try:
    #执行sql语句
    cursor.execute(sql)
    #提交到数据库执行
    db.commit()
except Exception as e:
    print(e)
    db.rollback()
finally:
    db.close()

7.删除操作

import pymysql
db = pymysql.connect(host='127.0.0.1', user='root', password='123456',
                     database='mytestdb', port=3306, charset='utf8')
cursor = db.cursor()
sql = "delete from employee where id='%s'"%(1)
try:
    cursor.execute(sql)
    db.commit()
except Exception as e:
    print(e)
    #发生错误时回滚
    db.rollback()
finally:
    db.close()

8.执行事务

#执行事务
import pymysql

db = pymysql.connect(host='127.0.0.1', user='root', password='123456',
                     database='mytestdb', port=3306, charset='utf8')
cursor = db.cursor()
#SQL删除记录语句
sql = "delete from employee where age > '%d'"%(20)
try:
    #执行SQL语句
    cursor.execute(sql)
    #向数据库提交
    db.commit()
except:
    #发生错误时回滚
    db.rollback()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python可以使用多种库来操作MySQL数据库,其中包括PyMySQLmysqlclient。PyMySQL是一个纯Python编写的库,安装非常简单,而mysqlclient是底层使用C编写的库,安装可能会有一些问题。\[3\]你可以根据自己的需求选择其中之一进行安装和使用。 在使用PyMySQL库时,你可以使用%s作为参数占位符来执行SQL操作,这与Python自带的sqlite3模块的占位符问号(?)有所不同。如果需要更详细的文档,你可以参考PyMySQL的官方文档。\[2\] 如果你想了解更多关于Python操作MySQL的知识,可以参考一些专门的章节或教程,这些资源会更详细地介绍如何使用Python来进行MySQL数据库操作。\[1\]希望这些信息对你有所帮助! #### 引用[.reference_title] - *1* [Python操作MySQL](https://blog.csdn.net/sanylove/article/details/124166373)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [太全了——用Python操作MySQL的使用教程集锦](https://blog.csdn.net/m0_59485658/article/details/126364328)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Python操作MySql](https://blog.csdn.net/PAN_BING/article/details/120812542)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值