使用Python简单进行mysql库insert select操作

用python简单的访问mysql数据库,执行insert ,select 操作。

# -*- coding: utf-8 -*-
import MySQLdb
import time

def insert():
    try:
        conn = MySQLdb.connect(host='127.0.0.1', user='testuser', passwd='aaaaaa', db='test',
                               charset="utf8", port=3306)
    except Exception as ee:
        print ee, "Can't connect configCenter database 127.0.0.1"
        return
    try:
        cursor = conn.cursor()
        cursor.execute("insert into test_table(id,updatetime,taskname)values(111,now(),'test---task2');")
        conn.commit()
    except Exception as e:
        print e
        return 0
    finally:
        conn.close()

def select():
    try:
        conn = MySQLdb.connect(host='127.0.0.1', user='testuser', passwd='aaaaaa', db='test',
                               charset="utf8", port=3306)
    except Exception as ee:
        print ee, "Can't connect configCenter database 127.0.0.1"
        return
    try:
        cursor = conn.cursor()
        cursor.execute("select * into outfile '/tmp/%s' from test_table where updatetime< '%s'" %
                       (time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time())),time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))
    except Exception as e:
        print e
        return 0
    finally:
        conn.close()

if __name__ == '__main__':
    # insert()
    select()


你可能感兴趣的:(使用Python简单进行mysql库insert select操作)