python如何快速连接MySQL数据库
目录
python连接MySQL数据库
二.使用python对数据库进行操作
三.关闭数据库
python连接MySQL数据库
1.导入模块
利用jupyter notebook先来安装第三方库pymysql。
!pip install pymysql
安装成功截图如下:
然后将其模块导入:
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)
运行结果:
2.创建数据库
cursor.execute("drop database if exists test")
sql = "create database test"
cursor.execute(sql)
运行结果:
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)
运行结果:
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)
运行结果:
5.查询操作
sql = "select * from employee"
cursor.execute(sql)
data = cursor.fetchone()
print(data)
运行结果:
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)
运行结果:
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)
运行结果:
三.关闭数据库
db.close()
原文链接:https://blog.csdn.net/qq_44176343/article/details/109392566