Python数据库(一)-Mysql数据库的连接

首先需要安装pymysql模块

然后用pymysql连接mysql并执行命令来查看数据

连接mysql数据库后需要创建游标来执行SQL语句

# -*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

import pymysql

conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='niushop_b2c') #创建连接

cursor = conn.cursor() #创建游标(实例化)

sql_result = cursor.execute('select * from sys_user') #执行SQL语句
print(sql_result) #打印有多少行的数据
print(cursor.fetchone()) #打印第一条数据
print('---------+----------')
print(cursor.fetchall()) #打印除第一条以外的所有数据

cursor.close() #关闭游标
conn.close() #关闭连接

运行结果

一共有四条数据,先打印了一条,分割符后打印剩下的三条数据

原文地址:https://www.cnblogs.com/sch01ar/p/8377896.html