Python连接MySQL数据库
一、 连接数据库
1、下载安装pymyql库
1 | pip3 install pymysql |
2、导入库
1 | import pymysql |
3、连接数据库,最好用try except捕获异常
1 2 3 4 5 6 7 8 9 10 11 | DBHOST = 'localhost' DBUSER = 'root' DBPASS = 'root' DBNAME = 'dbtest' DBPORT = '13306' #端口不是默认的话需要指定一下端口 try : # 每个参数都应该指定到对应的参数名上,否则会报init() takes 1 positional argument but 5 were given错误 db = pymysql.connect(host=DBHOST,user=DBUSER, password=DBPASS,database=DBNAME,port=DBPORT) print( '数据库连接成功!' ) except pymysql.Error as e: print( '数据库连接失败:' +str(e)) |
二、操作数据库之前需要先声明一个游标
1 | cur = db.cursor() |
三、创建一张新表
1、创建表之前先检查是否存在,如果存在则删除
1 | cur.execute( 'DROP TABLE IF EXISTS Student' ) |
2、编辑sql语句
1 2 3 | sqlQuery = "CREATE TABLE Student(Name CHAR(20) NOT NULL ,Email CHAR(20),Age int )" cur.execute(sqlQuery) |
四、向表中插入一条数据
1、编辑sql语句
1 | sqlQuery= " INSERT INTO Student (Name, Email, Age) VALUE (%s,%s,%s) " |
2、编辑准备插入的值
1 | value=( 'Mike' , '123456@163.com' ,20) |
3、执行sql语句
1 2 3 4 5 6 7 | try : cur.execute(sqlQuery,value) db.commit() print( '数据插入成功!' ) except pymysql.Error as e: print( "数据插入失败:" +e ) db.rollback() |
五、查询表中的数据,并输出表数据到excel中
1、编辑sql语句
1 | sqlQuery = "SELECT * FROM Student" |
2、使用fetchall()方法接收全部的返回结果行
1 2 3 4 5 6 7 8 9 10 | try : cur.execute(sqlQuery) results=cur.fetchall() for row in results: name=row[0] email=row[1] age=row[2] print( 'Name:%s,Email:%s,Age:%s' %(name,email,age)) except pymysql.Error as e: print( "数据查询失败:" +str(e)) |
六、更新表中的数据
1、编辑sql语句
1 | sqlQuery = "UPDATE Student SET Name= %s WHERE Name=%s" |
2、编辑更新的信息
1 | value = ( 'John' , 'updated name' ) |
3、提交修改
1 2 3 4 5 6 7 8 | try : cur.execute(sqlQuery, value) db.commit() print( '数据更新成功!' ) except pymysql.Error as e: print( "数据更新失败:" +str(e)) # 发生错误时回滚 db.rollback() |
七、删除表中的数据
1、编辑sql语句
1 | sqlQuery = "DELETE FROM Student where Name=%s" |
2、编辑更新的信息
1 | value = ( 'John' ) |
3、提交修改
1 2 3 4 5 6 7 8 | try : cur.execute(sqlQuery, value) db.commit() print( 'Date Deleted Successfully' ) except pymysql.Error as e: print( "数据删除失败:" +str(e)) # 发生错误时回滚 db.rollback() |
八、删除一张表
1、编辑sql语句
1 | sqlQuery= 'DROP TABLE IF EXISTS Student' |
2、提交修改
1 2 3 | cur.execute(sqlQuery) print( '表删除成功!' ) |
分类:
Python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
2019-11-17 Zookeeper搭建