python连接mysql数据库
说明:
1.如果你使用的是其他数据库,例如PostgreSQL,你可以使用psycopg2库来连接和获取数据库数据。使用方法类似,只需要根据你的实际情况修改连接参数和SQL语句即可。
2.首先确保本地数据库可以查询到数据,比如:若没有登陆SVN,本地数据库无法查询数据,那么python代码也会执行失败
一、基础了解
1.安装pymysql库: pip install pymysql
pymysql非python自带,导入前需要在Python中安装pymysql库
2.创建连接时,数据库端口是默认的3306,conn里port可以不写
如果不是,则要声明一下端口 port = '3307'
3.获取数据库数据的步骤如下:
- 导入pymysql
- 创建连接conn = pymysql.connect()
- 创建游标(数据库交互对象)cursor = conn.cursor()
- 写sql语句
- 用游标执行sql语句cursor.execute(sql)
- 提交事务/回滚事务conn.commit()/conn.rollback()
- 获取打印执行结果
- 关闭游标
- 关闭连接
实例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # 1.导入pymysql import pymysql # 2.创建连接 conn = pymysql.connect(host = 'localhost' , user = 'root' , password = 'password' , db = 'database_name' ) # 3.创建游标对象 cursor = conn.cursor() # 4.执行SQL查询语句 sql = "SELECT * FROM table_name" cursor.execute(sql) # 5.获取查询结果# 使用fetchone()方法获取单条数据 datal = cursor.fetchone()<br># 使用fetchall() 获取全部数据 data2 = cursor.fetchall( )<br># 使用fetchmany(n) 获取n条数据 data2 = cursor.fetchmany(2) 获取2条数据result = cursor.fetchall() # 6.一行一行打印查询结果,也可以直接打印,显示效果不太好# print(result) for row in result: print(row) <br># 7.关闭游标和数据库连接 <br>cursor.close() <br>conn.close() |
4.conn自带事务,可以直接conn.commit()提交事务
5.增删改数据,均要提交commit(),没有确认提交,则数据库数据是未发生变化的。查询不用commit数据
6.插入内容不写死:
1 2 3 4 5 | name = input ( "请输入名字:" ) id = input ( "请输入ID:" ) sql = 'insert into t_user values(%d, "%s")' % ( int ( id ),name) # 编写sql语句 corcur.execute(sql) conn.commit() |
7.封装增删改查数据库数据的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import pymysql cur = None conn = None def getall(sql): #用来执行查询 # 连接数据库,charset:通信采用的编码方式,默认是gb2312',要求与数据库创建时指定的编码格式一致 conn = pymysql.connect(host = 'localhost' , user = 'root' , password = '123123' , db = 'test1' , charset = 'utf8) cur = conn.cursor # 获取cursor对象 cur.execute(sql) # 通过cursor的对象去执行SQL语句 return cur.fetchall() def exceDML(sql): #用来执行插入 conn = pymysql.connect(host = 'localhost, user=' root, password = '123123' , db = 'test1' charset = 'utf8' ) cur = conn.cursor # 通过cursor的对象去执行SQL语句 cur.execute(sql) # 提交事物 conn.commit() def close0: #用来关闭连接 if cur: cur.close() if conn: conn.close() |
1 2 3 4 5 6 7 8 | from day3 import mysqlHelper name = input (“请输入名字 :") id = input (“请输入 ID :") sql1 = "insert into t user values(%d," % s") % ( int ( id ),name) sql2 = 'select * from t_user' mysqlHelper.exceDML(sql1) print (mysqlHelper.getall(sql2)) mysqlHelper.close() |
8.插入数据用占位符%s可以防止sql注入:
1 2 3 4 5 | # 插入时使用“%s”作为占位符可以防SQL注入 sql = r """insert into new table (id,name,age) values (%s,%s,%s)""" cursor.execute(sql,( 1 , "小明" , "10" ))cursor.execute(sql,( 2 , "小张" , "11" )) cursor.executemany(sql, (( 3 , "Tom" , "12" ),( 4 , "Jim" , "13" ))) # 多参数传入时需要使用元组,不得列多参数 cursor.executemany(sql,(( 5 , "Tom" , "14" ),( 6 , "Jim" , "15" ))) |
二、按条件查询数据库数据
查询某数据,查询条件不固定写死:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # -*- coding: utf-8 -*- import pymysql, datetime def connect_mysql(dates): conn = pymysql.connect(host = '10.185.66.85' , port = 3306 , user = 'test1' , password = 'test1234' , db = 'test' , charset = "utf8" ) cursor = conn.cursor() sql = f "select * from est_flow_charge where trading_day ='{dates}'" cursor.execute(sql) result = cursor.fetchall() for row in result: print (row) cursor.close() conn.close() if __name__ = = '__main__' : dates = '2023-12-01' # dates = datetime.date.today() 获取当日日期 connect_mysql(dates) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具