Python3使用pymysql连接 Mysql

转载自:https://blog.youkuaiyun.com/lionel_fengj/article/details/53132313


PyMySql 安装

  1. $ git clone https://github.com/PyMySQL/PyMySQL
  2. $ cd PyMySQL/
  3. $ python3 setup.py install 
    安装过程如下图所示: 

  4. git 命令安装 PyMySql

也可以pip install  pymysql命令安装

数据库连接

  • import pymysql
    #打开数据库连接
    db = pymysql.connect('localhost', 'username', 'password', 'testDB')
    #使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    #使用 execute()  方法执行 SQL 查询 
    cursor.execute("SELECT VERSION()")
    #使用 fetchone() 方法获取单条数据.
    data = cursor.fetchone()
    print("Database version : %s " % data) #输出结果:{Database version : 5.7.13} 说明数据库连接成功
    db.close() # 关闭数据库连接

数据插入

已经在我的数据库下建立了 User 这张表,字段分别有id,name,age,以下实例使用 Sql 的 insert 语句向 User 表中插入一条数据。

#插入数据('jf',26)到表中
import pymysql
db = pymysql.connect('localhost', 'username', 'password', 'testDB')
cursor = db.cursor()
# SQL 插入语句
sql = """insert into User(name,age) VALUES ('jf',26)"""
try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()
db.close()

数据查询

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。 
- fetchone(): 该方法获取下一个查询结果集。结果集是一个对象。 
- fetchall(): 接收全部的返回结果行。 
- rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

#查询 id=1的数据记录
import pymysql
db = pymysql.connect('localhost', ' username', 'password', 'testDB')
cursor = db.cursor()
sql = "select * from EMPLOYEE where id=1"
try:
    cursor.execute(sql)
    results = cursor.fetchall()
    for row in results:
        id = row[0]
        name=row[1]
        age = row[2]
        print("id=%d,name=%s,age=%d" % (id,name, age))
        #id=1,name=jf,age=26
except:
    print('Error,unable to fetch data')

数据更新

#id=1的年龄增加一岁
import pymysql
db = pymysql.connect('localhost', 'username', 'password', 'testDB')
cursor = db.cursor()
sql = "update USER set age=age+1 where id=1"
try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()
db.close()

数据删除

#年龄大于20岁的删除
import pymysql
db = pymysql.connect('localhost', 'username', 'password', 'testDB')
cursor = db.cursor()
sql = "delete from EMPLOYEE where age>20"
try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()
db.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值