使用python连接数据库

阅读更多
#! /usr/bin/python

import sys,MySQLdb

max_pk=-1;
max_gmt_create='2017-11-07 9:33:15';
record_count=0;
last_gmt_create=max_gmt_create;

while 1:
  db = MySQLdb.connect('127.0.0.1','sysbench_test','abc','abc')
  cursor = db.cursor()
  try:
    sql="sql"
    cursor.execute(sql)
    ## 获取所有结果
    results=cursor.fetchall()

    index = 0

    for row in results:
      record=str(row[0])+","+str(row[1])
      print record
      record_count += 1
      index += 1
      max_pk = row[0]
      max_gmt_create = row[1]

    print("next====:"+str(max_pk)+","+str(max_gmt_create))
    if index == 0:
      print "break"
      break
  ### 获取并打印异常信息
  except MySQLdb.Error,e:
    print "MySQL Error:%s" % str(e)
    print "Error:unable to fetch data"

  db.close()

print "all record count:"+str(record_count)




#! /usr/bin/python

import sys,MySQLdb

db = MySQLdb.connect('abc','abc','abc','abc')

##字典形式结果
cursor = db.cursor(MySQLdb.cursors.DictCursor)

insert_sql="insert into `show_full_stats` (`my_time_sec`,`my_value`,`my_metric`) values "

try:
  cursor.execute("show full stats")
  ##获取一条数据
  row=cursor.fetchone()
  insert_sql=insert_sql+"(now(),"+str(row['FULLGCTIME'])+""","full_gc_time"),"""
  insert_sql=insert_sql+"(now(),"+str(row['THREAD_RUNNING'])+""","thread_running"),"""
  insert_sql=insert_sql+"(now(),"+str(row['FULLGCCOUNT'])+""","full_gc_count"),"""
  insert_sql=insert_sql+"(now(),"+str(row['QPS'])+""","qps")"""
except:
  print "Error:unable to fetch data"

db.close()

db2= MySQLdb.connect('127.0.0.1','abc','abc','abc')

cursor2=db2.cursor()

try:
  cursor2.execute(insert_sql)
  db2.commit()
  ### 获取并打印异常信息
except MySQLdb.Error,e:
  print "MySQL Error:%s" % str(e)
  db2.rollback()

db2.close()

你可能感兴趣的:(使用python连接数据库)