python程序实现对数据库的select操作
import MySQLdb# 创建连接对象conn=MySQLdb.connect(host='47.115.130.16',port=3306,database='hrs',charset='utf8',user='huchaolin',password='123Hcl456&',autocommit=False)try:with conn.cursor() as curs
·
使用python实现对数据库的select操作方法:
- 创建连接对象
- 获取游标
- 使用游标执行select语句
- 通过游标抓取数据
- 关闭数据库连接(释放资源)
使用抓取游标抓取数据的格式有两种:
第一种如下所示:抓取到的结果时元组类型(默认类型)
import MySQLdb
# 1. 创建连接对象
conn=MySQLdb.connect(host='47.115.130.16',port=3306,
database='hrs',charset='utf8',
user='huchaolin',password='12cl45&',
)
try:
# 2. 获取游标
with conn.cursor() as cursor:
# 3. 使用游标执行select语句
cursor.execute(
'select dno, dname, dloc from tb_dept'
)
# 4. 通过游标抓取数据
# 通过cursor对象抓取查询结果,共有三个抓取数据的方法
# cursor是游标对象
# fetch_one() 抓取一个
# fetchmany(n) 抓取多个
# fetchall() 抓取所有
print(cursor.fetchall())
# print(cursor.fetchmany(2))
except MySQLdb.MySQLError as err:
print(err)
finally:
# 5. 关闭数据库连接(释放资源)
conn.close()
结果为:
第二种如下所示,抓取到的结果类型可以为字典类型:
此种方式内容显示更加清楚明了一些,但是需要新增一个设置(在创建连接对象里面添加cursorclass=DictCursor)
import MySQLdb
# 1. 创建连接对象
from MySQLdb.cursors import DictCursor
conn = MySQLdb.connect(host='47.104.31.138', port=3306,
user='root', password='Luh18',
database='hrs', charset='utf8',
cursorclass=DictCursor)
try:
# 2. 获取游标对象
with conn.cursor() as cursor:
# 3. 通过游标对象向数据库发出SQL语句获取执行结果
cursor.execute('select dno as no, dname as name, dloc as location from tb_dept')
# 4. 通过游标抓取数据
for dept in cursor.fetchall():
print(dept)
# print(f'{dept["name"]}\t{dept["location"]}')
except MySQLdb.MySQLError as err:
print(err)
finally:
# 5. 关闭数据库连接(释放资源)
conn.close()
结果为:
更多推荐
所有评论(0)