1、PyMySQL 驱动
- PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库
- Python2中则使用mysqldb。
2、PyMySQL 安装
pip3 install PyMySQL
3、数据库连接
- data = cursor.fetchone()获取单条数据,如有多条只获取第一条
- 结果集中的内容只能被获取一次
import pymysql
db = pymysql.connect(host='localhost',
port=3306,
user='root',
password='********',
charset='utf8',
db='test')
cursor = db.cursor()
cursor.execute("select * from trade")
for data in cursor.fetchall():
print(data)
db.close()
4、创建数据库表
import pymysql
db=pymysql.connect(
host="localhost",
user="root",
password="********",
db="test"
)
print(db)
cursor=db.cursor()
cursor.execute("DROP TABLE IF EXISTS TEST")
sql="""CREATE TABLE TEST(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT)"""
cursor.execute(sql)
db.close()
5、插入数据
import pymysql
db = pymysql.connect(host="localhost",
user="root",
password="********",
db="test",
port = 3306)
cursor=db.cursor()
sql="""INSERT INTO TEST(FIRST_NAME,
LAST_NAME,
AGE,
SEX,
INCOME)
VALUES("锄禾","锄禾","20","M",2000)"""
try:
cursor.execute(sql)
db.commit()
except Exception as e:
db.rollback()
print(e.message)
db.close()
7、数据库查询操作
- fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
- fetchall(): 接收全部的返回结果行.
- rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
import pymysql
db = pymysql.connect(host="localhost",
user="root",
password="********",
db="test",
port = 3306)
cursor = db.cursor()
sql = "SELECT * FROM test WHERE INCOME > %s" % (1000)
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
print("fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
(fname, lname, age, sex, income))
except:
print("Error: unable to fetch data")
db.close()