码迷,mamicode.com
首页 > 数据库 > 详细

python3 链接Mysql数据库

时间:2020-04-30 17:37:36      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:ase   -bash   返回   ror   error:   hal   执行sql   sql   imp   

使用的是PyMySql组件

pip3 install PyMySQL

代码

#!/usr/bin/python3
import pymysql
 
# 打开数据库连接
conn = pymysql.connect (
    host=‘127.0.0.1‘,
    port=3306,
    user=‘root‘,
    password=‘12345‘,
    database=‘mysql‘,
    charset=‘utf8‘
)

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)  # 返回字典数据类型
 
# 定义将要执行的sql语句
# sql = ‘select user from user;‘
sql = "SELECT user FROM user"
# 拼接并执行sql语句
cursor.execute(sql)
 
try:
    cursor.execute(sql)
   # 获取所有记录列表
    results = cursor.fetchall()
    
    for x in results:
        print(x)
except:
    print ("Error: unable to fetch data")

cursor.close()
conn.close()

python3 链接Mysql数据库

标签:ase   -bash   返回   ror   error:   hal   执行sql   sql   imp   

原文地址:https://www.cnblogs.com/feipeng8848/p/12809721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!