In response to the multi-thread concurrent operation of the system, a simple Python script is written today to insert and retrieve data to and from MySQL, And the mysqldb and threading modules are used.
Among them, the threading module is an object-oriented encapsulation of the thread module, which is easy to use.
Import mysqldb <br/> Import threading <br/> Import sys <br/> def db_op_thread_func (I, num_of_op): <br/> conn = mysqldb. connect (host = "x. x. x. X ", Port = x, user =" XXXX ", passwd =" ", DB =" XXXX ") <br/> cursor = Conn. cursor () <br/> SQL = "select * from XXXX" <br/> for J in range (0, INT (num_of_op )): <br/> cursor.exe cute (SQL) <br/> Print "Thread", I, ":", "Num:", j </P> <p> Conn. close () <br/> If _ name _ = "_ main _": <br/> ARGs = sys. argv <br/> num_of_thd = ARGs [1] <br/> num_of_op = ARGs [2] <br/> threads = [] <br/> for I in range (0, INT (num_of_thd): <br/> threads. append (threading. thread (target = db_op_thread_func, argS = (I, num_of_op) </P> <p> for T in threads: <br/> T. start () </P> <p> for T in threads: <br/> T. join ()
Note:
1. To prevent program exceptions caused by exit of the main thread before other threads, you need to call the join () function and wait until the process ends;
2. The print statement is used to understand the program running status and check whether the program is stuck in any place in real time;
3. the python program obtains the command line parameters;
Improvement:
1. If you want to simulate different operations, you can write several SQL statements to a string array and obtain them randomly and put them in the thread for execution;