Python mysqldb, sockets, and incoming threads

Source: Internet
Author: User
Tags thread stop c queue

1 Installing the MySQLdb module under CentOS

A first need to install Setuptool  b yum install-y mysql_devel header file C yum install-y python_devel header file cd mysqldb python setup.py buil D python setup.py Install

1.1. Database connection

MYSQLDB provides the Connect method to establish a connection to the database, receive several parameters, and return the connection object:

Conn=mysqldb.connect (host= "localhost", user= "root", passwd= "jb51", db= "test", charset= "UTF8") #建议使用键值字典形式, So don't be afraid of the order.

The more commonly used parameters include:
Host: the database hostname. By default, the local host
User: Database login name. The default is the current user
PASSWD: The Secret of database landing. Default is Empty
DB: The name of the database to use. No default value
The TCP port used by the Port:mysql service. Default is 3306
CharSet: Database encoding

Commit () Commit
Rollback () rollback

Close () Closes the connection

Cursor () returns a cursor that automatically opens a transaction which uses Autocommit (false) to turn off autocommit

1.2. Cursor method execution and return value

Executes a single SQL statement, receives the parameters for the SQL statement itself and the parameter list used, and returns the number of rows affected
Execute (Self, query, args)

Receives all the returned result rows.
Fetchall (self)


Receives a size bar to return the result row. If the value of size is greater than the number of result rows returned, the cursor.arraysize data is returned
Fetchmany (self, size=none)


Returns a result row
Fetchone (self)


This is a read-only property and returns the number of rows affected after executing the Execute () method
RowCount

2 socket

a Create SK = Socket.socket ();

#sk. setblocking (0) non-blocking, accept and recv once there is no data, then the error

B-Bound Sk.bind ((' localhost,8080 ')) represents an address in the form of a tuple (host,port) under Af_inet

C Listening Queue Sk.listen (back) starts listening for incoming connections. Backlog Specifies the maximum number of connections that can be suspended before a connection is rejected

D connect,address = sk.accept () Receive TCP Client connection (blocked) Wait for connection to arrive, return connection object and address

E connection Sk.connect (address)

F Receive Data SK.RECV (bufsize) Receive data size

G Send data Sk.send (string)

H Close Sk.close ()

Server

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port= ('127.0.0.1', 8080) SK=Socket.socket () sk.bind (Ip_port) Sk.listen (5) Flas=true whileflag:conn,addr=sk.accept () client_data= CONN.RECV (1024)    PrintClient_data Conn.sendall ('Test') Conn.close ()

Client

# !/usr/bin/env python # -*-coding:utf-8-*- Import  = ('127.0.0.1', 8080= socket.socket () sk.connect (Ip_port) Sk.sendall (' coming '= sk.recv (1024x768)print server_replysk.close ()

3 Threads (threading)

Start thread is ready to wait for CPU scheduling

SetName setting a name for a thread

GetName Get thread Name

Setdaemon set to background thread or foreground thread (default)
If it is a background thread, during the main thread execution, the background thread is also in progress, and after the main thread finishes executing, the background thread stops regardless of success or not.
If it is the foreground thread, during the main thread execution, the foreground thread is also in progress, and after the main thread finishes executing, wait for the foreground thread to finish, the program stops

The join executes each thread one by one and continues execution after execution, making multithreading meaningless

The Run method that executes the thread object automatically after the run thread is dispatched by the CPU

#!/usr/bin/env python#-*-coding:utf-8-*-ImportThreadingdefShow (ARG):Print 'Thread'+Str (ARG) forIinchRange (3): T= Threading. Thread (Target=show, args=(i,)) #也可以使用继承方式使用多线程, rewrite the Run Method T.start ()Print 'Main thread Stop'

3.1-Wire Lock

  a lock =threading.Lock()

lock =threading.RLock()可多次获取锁,释放的时候也需要几次

b lock.acquire () Get lock

C lock.release () release lock

3.2 Thread events (the mechanism of event handling: A "flag" is defined globally, and if the "flag" value is False, then it blocks when the program executes the Event.wait method, and if the "flag" value is true, then the Event.wait method is no longer blocked)

A E = threading. Event ()

b e.wait () block

C E.set () setting flag=true

D e.clear () clears the value of Set (), which is the reset flag

3.3 Queues

A = Queue (maxsize) maximum number of queues

b queue.empty () is empty

C queue.qsize () Queue Size

D Queue.full () whether the queue reaches the maximum value

e queue.put ()/get ()/clear () Add/Get/Empty

4 processes (processes each hold one piece of data, default cannot share data)

multiprocessing importProcess 

4.1 is used in a similar manner to threads, using multiprocessing as the process data is independent. Array/queue/value/manager Data co-management, of course, can also use Reids

4.2 Lock mechanism similar to thread

4.3 Process pool (multiprocessing. Pool)

p = number of Pool (n) processes

res = P.apply_async (func,args,callback)/apply () Asynchronous/synchronous execution

Res.get (time) Gets the process return data, timing: Blocked times

Python mysqldb, sockets, and incoming threads

Related Article

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.