美文网首页
使用Python简单进行mysql库insert select操

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

作者: 三省吾身a | 来源:发表于2016-11-07 18:34 被阅读0次

    用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操

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