Python simulates concurrent MySQL operations on multiple clients

Source: Internet
Author: User

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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.