Python多線程存取MySQL數據


這兩天正好接觸python對sql的多線程問題,於是寫了個demo以供參考。

首先安裝MySQLdb,指令是:pip install mysql-python

1.存入數據:

 1 import MySQLdb
 2 import datetime
 3 import time
 4 def insert(io):
 5     while True:
 6         time_now = datetime.datetime.now()
 7         print io,time_now
 8         conn = MySQLdb.connect(user = "root", passwd = "qwe123", host = "192.2.4.166", db = "python")
 9         cur = conn.cursor()
10         sql = "insert into table_%s values ('%s','%s');"
11         cur.execute(sql%(io,io,time_now))
12         cur.close()
13         conn.commit()
14         time.sleep(5)
15 
16 if __name__ == "__main__":
17     import threading
18     t = threading.Thread(target=insert,args=('in',))
19     t.start()
20     t = threading.Thread(target=insert,args=('out',))
21     t.start()
22     t.join()

2.讀取數據:

 1 #coding *.* coding: utf-8 *.*
 2 import MySQLdb
 3 import time
 4 conn = MySQLdb.connect(
 5     host = "192.2.4.166",
 6     port = 3306,
 7     user = "root",
 8     passwd = 'qwe123',
 9     db = 'python',
10     #如果遇到數據庫中有中文,加這條
11     charset = "utf8",
12 )
13 def read(io):
14     list = [0]
15     while True:
16         conn = MySQLdb.connect(user="root", passwd="qwe123", host="192.2.4.166", db="python")
17         # cursorclass 使輸出變為字典形式
18         cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
19         sql = "select * from table_%s order by date desc;"
20         cur.execute(sql % io)
21         info = cur.fetchone()
22         if info not in list:
23             print info
24             list.append(info)
25             list.pop(0)
26         cur.close()
27         conn.commit()
28         time.sleep(2)
29 
30 if __name__ == "__main__":
31     import threading
32     t = threading.Thread(target=read, args=('in',))
33     t.start()
34     t = threading.Thread(target=read, args=('out',))
35     t.start()
36     t.join()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM