python间接操作sql数据库

一般银行的数据库是oracle,互联网企业用mysql

因此对于mysql,就可以通过python接口pymysql操作,本质上还是sql语言操作数据库,只是python再去拿结果分析

pymysql操作简介

  • 连接数据库得到表
  • cursor获得操作句柄
  • cursor.execute("sql语句")
  • fetch取结果,可进行进一步操作(fetchone,fetchall)
#!/usr/bin/python3
 
import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE 
       WHERE INCOME > %s" % (1000)
try:
   # 执行SQL语句
   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()

python间接操纵sql数据库的用处

  • 高效批量插入数据
  • 后续可方便数据分析,如pysql接口得到数据,生成dataframe二维字典,然后利用pandas做数据分析
  • 本质还是sql操作DB+python后处理
原文地址:https://www.cnblogs.com/Henry-ZHAO/p/14614751.html