Example Analysis of MySQLdb usage in python, pythonmysqldb
This example describes the usage of MySQLdb in python. Share it with you for your reference. The specific analysis is as follows:
Download and install MySQLdb
① Linux version
Http://sourceforge.net/projects/mysql-python/ download, installation is to install setuptools first, and then under the download file directory, modify mysite. cfg, specify the local mysql-config file path
② Windows
Find a http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe online
After installation, import MySQLdb will receive a warning like DeprecationWarning: the sets module is deprecated.
The reason is that 2.6 does not know the sets module, but the set built-in function has been added. Find _ init _ in the MySQLdb folder __. py, comment out from sets import ImmutableSet class DBAPISet (ImmutableSet): Add class DBAPISet (frozenset):; find converters. py comment out from sets import BaseSet, Set. Then, Set the values of rows 45th and 129 to set.
Done.
The following demo is started:
Python code
#-*-Coding: UTF-8-*-# mysqldb import time, MySQLdb # connection conn = MySQLdb. connect (host = "localhost", user = "root", passwd = "", db = "test", charset = "utf8") cursor = conn. cursor () # Write SQL = "insert into user (name, created) values (% s, % s)" param = ("aaa", int (time. time () n = cursor.exe cute (SQL, param) print n # update SQL = "update user set name = % s where id = 3" param = ("bbb ") n = cursor.exe cute (SQL, param) print n # query n = cursor.exe cute ("select * from user") for row in cursor. fetchall (): for r in row: print r # delete SQL = "delete from user where name = % s" param = ("aaa") n = cursor.exe cute (SQL, param) print n cursor. close () # close conn. close ()
The basic usage is as simple as above. For further use, you have not performed any operations. First, you can find some information on the Internet for future reference.
1. Introduce the MySQLdb Library
Copy codeThe Code is as follows: import MySQLdb
2. Establish a connection with the database
Copy codeThe Code is as follows: conn = MySQLdb. connect (host = "localhost", user = "root", passwd = "sa", db = "mytable", charset = "utf8 ")
The connect method is used to establish a connection with the database, receive several parameters, and return the connection object.
Common parameters include
Host: specifies the Database host name. The local host is used by default.
User: Database login name. The default value is the current user.
Passwd: Password for database login. Empty by default.
Db: name of the database to be used. No default value exists.
Port: the TCP port used by the MySQL service. The default value is 3306.
Charset: Database encoding.