python读取mysql

1.python读取mysql

#!/usr/bin/python3
import pymysql

# 打开数据库连接
db = pymysql.connect(host="192.138.7.104",user="root",password="root",db="dbname",port=port,charset='utf8')

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 查询语句
sql = "SELECT ZTB_XMMC,ZTB_CGNR FROM DA_ZTBXX WHERE ZTB_ZBJG LIKE '%山东有限公司%'"

try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   len = results.__len__()
   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")

# 关闭数据库连接
db.close()

你可能感兴趣的:(大数据技术)