美文网首页那年夏天
Python3 数据库连接

Python3 数据库连接

作者: 坚持到底v2 | 来源:发表于2019-01-11 10:40 被阅读0次

1. 安装 PyMySQL

pip install PyMySQL

如果不支持 pip 命令 ( 最好还是使用 pip 安装)

git clone https://github.com/PyMySQL/PyMySQL
cd PyMySQL
python setup.py install

还有的教程使用的是 mysql-connector 语法大同小异

2 示例

import pymysql
# 打开数据库连接
db = pymysql.connect("10.0.209.149","sa","xxx","dbName") 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")

# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()

print("Database version : %s " % data)
# 关闭数据库连接
db.close()

大概过程就是

(1) 连接数据库

(2) 创建一个cursor

(3) 使用cursor执行sql语句

(4) db.commit() 和 db.rollback() 提交和回滚

(5) 最后关闭数据库

3 增,删,改 示例

# 打开数据库连接
db = pymysql.connect("10.0.209.149","sa","xxx","dbName") 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
sql="update employee set age=age+1 where sex='%c'" % ('M')
try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()
finally:
    db.close()

4 查询示例

fetchone(): 该方法获取下一个查询结果集。结果集是一个对象

fetchall(): 接收全部的返回结果行.

rowcount: 这是一个只读属性, 返回执行execute()方法后影响的行数。

# 打开数据库连接
db = pymysql.connect("10.0.209.149","sa","xxx","dbName") 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
sql="select * from employee where income > '%d'" % (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=%d,sex=%s,income=%d" % (fname, lname, age, sex, income ))
except:
    print("Error: unable to fetch data")
finally:
    db.close()

相关文章

网友评论

    本文标题:Python3 数据库连接

    本文链接:https://www.haomeiwen.com/subject/hrwtdqtx.html