PyCharm安装pymysql,切到终端,直接输入:pip install pymysql,回车即可
连接数据库时需要设置的属性:
# 连接数据库
db = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='root',
db='xiuyixiacom',
charset='utf8'
)
cursor = db.cursor()
host-服务器ip,一般填localhost,127.0.0.1。port-3306。user-数据库的用户名,passwd-数据库密码,db-数据库名称,charset-编码
然后取值输出打印sql查询的值:
sql = "SELECT username FROM user"
cursor.execute(sql)
result = cursor.fetchall()
for i in result:
res = i[0]
print(res)
最后关闭:
cursor.close()
db.close()
完整代码:
# -*- coding:utf-8 -*-
import pymysql
# 连接数据库
db = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='root',
db='xiuyixiacom',
charset='utf8'
)
cursor = db.cursor()
sql = "SELECT username FROM user"
cursor.execute(sql)
result = cursor.fetchall()
for i in result:
res = i[0]
print(res)
cursor.close()
db.close()