python 3 簡單線程、資料庫操、Mssql訪問樣本

來源:互聯網
上載者:User
'''
Tested:
    Python 3.3.0
    Microsoft SQL Server 2008
'''

import time
import random
import adodbapi
import threading

'''
    簡單定時器類
'''
class Timer(threading.Thread):
    def __init__(self,fn,args=(),sleep = 0):
        threading.Thread.__init__(self)
        self.fn = fn
        self.args = args
        self.interval = sleep
        self.setDaemon(True)
        self.enable = True
        self.running = False

    def __do(self):
        self.running = True
        self.fn(*self.args)
        self.running = False

    def run(self):
        while self.enable :
            time.sleep(self.interval)
            self.__do()

    def stop(self):
        #stop the loop
        self.enable = False
        while True:
            if not self.running : break
            time.sleep(0.01)

'''
    簡單資料庫訪問類
'''
class DbHelper:
    def __init__(self,conn):
        self.conn = conn;
        try:
            self.connect = adodbapi.connect(conn,120)
            self.cursor = self.connect.cursor();
        except EnvironmentError as err:
            print('connection failure:' + err);

    def getConn(self):
        return self.conn;

    def getDbTime(self):
        self.cursor.execute("select getdate()");
        daterow = self.cursor.fetchone();
        return str(daterow[0]);

    def execNoResult(self,sql):
        self.cursor.execute(sql);
        self.connect.commit();

    def getExecResult(self,sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall();

    def closeConn(self):
        try:
            self.cursor.close();
            self.connect.commit();
            self.connect.close();
        except EnvironmentError as err:
            print('close connection failure:' + err);

def getConnection():
    dbprov = 'SQLOLEDB' # ADO can use OLE
    dbserv = '192.168.1.118,1433'
    dbuser = 'sa'
    dbpwd = 'pwd'
    dbname = 'water'
    return  'Provider=%s;Data Source=%s;Initial Catalog=%s;User ID=%s;Password=%s;' % (dbprov, dbserv, dbname, dbuser, dbpwd )

def updateRawData():
    dbClass = DbHelper(getConnection());

    try:
        for row in dbClass.getExecResult("select * from rawdata"):
            dbClass.execNoResult("update rawdata set value='{0}',proc_date=getdate() where pos='{1}'".format( "%.2f" % random.uniform(0,20),row[0]));
        print("update success->" + dbClass.getDbTime());
        dbClass.closeConn();
    except EnvironmentError as err:
        print('connection failure:' + err);

Timer(updateRawData,sleep=5).run()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.