python编程字典数据库_python如何快速连接MySQL数据库

python如何快速连接MySQL数据库

目录

python连接MySQL数据库

二.使用python对数据库进行操作

三.关闭数据库

python连接MySQL数据库

1.导入模块

利用jupyter notebook先来安装第三方库pymysql。

!pip install pymysql

安装成功截图如下:

a6de54cd74e2986ba63a159ac25e694a.png

然后将其模块导入:

import pymysql

2.打开数据库

#打开数据库连接

#数据库名为mysql,也可以没有这个参数

db = pymysql.connect(host = "127.0.0.1",port = 3306,user = 'root',passwd = '19980202PENG',db = 'mysql',charset = 'utf8')

3.创建游标对象cursor

cursor = db.cursor()

二.使用python对数据库进行操作

使用execute()方法来实现对数据库的基本操作。

1.查询数据库版本

cursor.execute('select version( )')

data= cursor.fetchone()

print("Database Version:%s" % data)

运行结果:

7aaf27372deb1e5bb479a45650eb5916.png

2.创建数据库

cursor.execute("drop database if exists test")

sql = "create database test"

cursor.execute(sql)

运行结果:

00f49ca193cbb38efe6c275522f0c9a1.png

3.创建数据表

cursor.execute("drop table if exists employee")

sql = """

CREATE TABLE EMPLOYEE(

FIRST_NAME CHAR(20) NOT NULL,

LAST_NAME CHAR(20),

AGE INT,

SEX CHAR(1),

INCOME FLOAT)

"""

cursor.execute(sql)

运行结果:

23632047353b245dd77e7fe8797fed20.png

4.插入操作

#插入数据

sql = "insert into employee values('彭','文奎',20,'w',5000)"

cursor.execute(sql)

db.commit()

#查看插入后的结果

sql = "select * from employee"

cursor.execute(sql)

data = cursor.fetchone()

print(data)

运行结果:

1b52e3a265af61fbabad94e9925e10b0.png

5.查询操作

sql = "select * from employee"

cursor.execute(sql)

data = cursor.fetchone()

print(data)

运行结果:

8c3ca9e3cdabf80d6caf76f8fd5bb2e4.png

6.指定条件查询

#更新数据库

sql = "update employee set age = age+1 where sex = '%c' " %('w')

cursor.execute(sql)

db.commit() #提交到数据库执行:插入,更新,删除

#查看更新后的结果

sql = "select * from employee"

cursor.execute(sql)

data = cursor.fetchone()

print(data)

运行结果:

bb998c19383c9f48b81d1fbe5dbe3991.png

7.删除操作

#删除数据

sql = "delete from employee where age > '%d'" % (30)

cursor.execute(sql)

db.commit()

#查看更新后的结果

sql = "select * from employee"

cursor.execute(sql)

data = cursor.fetchone()

print(data)

运行结果:

01901bd117b06324176cf71f04060016.png

三.关闭数据库

db.close()

原文链接:https://blog.csdn.net/qq_44176343/article/details/109392566

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值