如何用Python对数据库中的数据进行增删改查

您所在的位置:网站首页 python数据库查询后合并 如何用Python对数据库中的数据进行增删改查

如何用Python对数据库中的数据进行增删改查

#如何用Python对数据库中的数据进行增删改查| 来源: 网络整理| 查看: 265

pyhton如何连接mysql数据库

1、导入模块

2、打开数据库连接

3、创建游标对象cursor

如何用Python对数据库中的数据进行增删改查

import pymysql

#连接数据库

conn=pymysql.connect(host = ‘127.0.0.1’ # 连接名称,默认127.0.0.1

,user = ‘root’ # 用户名

,passwd=‘password’ # 密码

,port= 3306 # 端口,默认为3306

,db=‘test’ # 数据库名称

,charset=‘utf8’ # 字符编码

cur = conn.cursor() # 生成游标对象

#=插入语句===================

sql= “INSERT INTO student VALUES (‘p’,‘魏六’,‘17’)”

#===================================================

try:

cur.execute(sql1) # 执行插入的sql语句

conn.commit() # 提交到数据库执行

except:

coon.rollback()# 如果发生错误则回滚

conn.close() # 关闭数据库连接

然后我们再运行查询语句

import mysql.connector

conn=mysql.connector.connect(host = ‘127.0.0.1’ # 连接名称,默认127.0.0.1

,user = ‘root’ # 用户名

,passwd=‘password’ # 密码

,port= 3306 # 端口,默认为3306

,db=‘test’ # 数据库名称

,charset=‘utf8’ # 字符编码

cur = conn.cursor() # 生成游标对象

sql=“select * from student ” # SQL语句

cur.execute(sql) # 执行SQL语句

data = cur.fetchall() # 通过fetchall方法获得数据

for i in data[:]: # 打印输出所有数据

print (i)

cur.close() # 关闭游标

conn.close() # 关闭连接

执行结果就是

(‘b’, ‘钱二’, ‘16’)

(‘c’, ‘张三’, ‘17’)

(‘d’, ‘李四’, ‘17’)

(‘e’, ‘王五’, ‘16’)

(‘a’, ‘赵大’, ‘16’)

(‘p’, ‘魏六’, ‘17’)

import pymysql

#连接数据库

conn=pymysql.connect(host = ‘127.0.0.1’ # 连接名称,默认127.0.0.1

,user = ‘root’ # 用户名

,passwd=‘password’ # 密码

,port= 3306 # 端口,默认为3306

,db=‘test’ # 数据库名称

,charset=‘utf8’ # 字符编码

cur = conn.cursor() # 生成游标对象

#=删除语句===================

sql = “DELETE FROM student WHERE 学号 = “a”

#===================================================

try:

cur.execute(sql) # 执行插入的sql语句

conn.commit() # 提交到数据库执行

except:

coon.rollback()# 如果发生错误则回滚

conn.close() # 关闭数据库连接

import pymysql

#连接数据库

conn=pymysql.connect(host = ‘127.0.0.1’ # 连接名称,默认127.0.0.1

,user = ‘root’ # 用户名

,passwd=‘password’ # 密码

,port= 3306 # 端口,默认为3306

,db=‘test’ # 数据库名称

,charset=‘utf8’ # 字符编码

cur = conn.cursor() # 生成游标对象

#=删除语句===================

sql =”UPDATE student SET 学员姓名 = ‘欧阳’ WHERE 学号 = ‘b’ “

#===================================================

try:

cur.execute(sql) # 执行插入的sql语句

conn.commit() # 提交到数据库执行

except:

coon.rollback()# 如果发生错误则回滚

conn.close() # 关闭数据库连接

import pymysql

#连接数据库

conn=pymysql.connect(host = ‘127.0.0.1’ # 连接名称,默认127.0.0.1

,user = ‘root’ # 用户名

,passwd=‘password’ # 密码

,port= 3306 # 端口,默认为3306

,db=‘test’ # 数据库名称

,charset=‘utf8’ # 字符编码

cur = conn.cursor() # 生成游标对象

#=删除语句===================

sql=”select * from student “ # SQL语句

#====================================================

try:

cur.execute(sql) # 执行插入的sql语句

data = cur.fetchall()

for i in data[:]:

print (i)

conn.commit() # 提交到数据库执行

except:

coon.rollback()# 如果发生错误则回滚

conn.close() # 关闭数据库连接

整合自:Python学习网、CDA数据分析研究院

编辑:jq



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3