我用的是python3,2应该也一样。
第一步安装pymysql 命令如图:
编写程序如下:
<code>import datetime import pymysql.cursors # 连接配置信息 config = { 'host': '127.0.0.1', #本地服务器 'port': 3306, 'user': 'root', 'password': 'password', 'db': 'bds_dev', 'charset': 'utf8mb4', 'cursorclass': pymysql.cursors.DictCursor, } # 创建连接 connection = pymysql.connect(**config) # 执行sql语句 try: with connection.cursor() as cursor: # 执行sql语句,进行查询 sql = 'SELECT * FROM bds_dev.b_short_msg' cursor.execute(sql) # 获取查询结果 result = cursor.fetchall() #获取全部结果,取一条为 fetchone() print(result) # 没有设置默认自动提交,需要主动提交,以保存所执行的语句 connection.commit() finally: connection.close(); /<code>
控制台运行还是报错如下图:原因是缺加解密模块
安装加解密模块
成功执行sql!