MySQLdb is an interface to the popular MySQL database server for Python. The design goals are
1. Compliance with Python database API version 2.0(兼容python 数据库API2.0接口)
2. Thread-safety(线程安全)
3. Thread-friendliness (threads will not block each other) (线程友好,线程间不会相互阻塞)
下载地址:(可以根据需要下载window 或linux版本的MySQLdb)
https://pypi.python.org/pypi/MySQL-python/1.2.5
如果是windows的版本,直接运行,一路next安装即可。如果是linux版本,则安装步骤如下: 详细可参与安装包中的INSTALL文件
$ tar xfz MySQL-python-1.2.1.tar.gz
$ cd MySQL-python-1.2.1
$ # edit site.cfg if necessary
$ python setup.py build
$ sudo python setup.py install # or su first
二、代码示例:
#!/usr/bin/python
# encoding=utf-8
# Filename: mysqltest
import datetime
import MySQLdb as dbi
try:
conn=dbi.connect(host="172.168.29.250",user='root',passwd='root',db='test',port=3306,charset='utf8')
cur=conn.cursor()
cur.execute("insert into test(id,name)values(5,'你好呀')")
conn.commit()
print "获取数据"
count=cur.execute('select * from test')
print "总记录条数%d" % count
result=cur.fetchone()
print "id:%d,name:%s" % result
results=cur.fetchmany(2)
for r in results:
print "id:%d,name:%s" % r
print "------------"
results=cur.fetchall()
for r in results:
print "id:%d,name:%s" % r
print "------------"
cur.scroll(0,mode='absolute')
result=cur.fetchone()
print "id:%d,name:%s" % result
print "------------"
print "创建数据库表并插入数据:"
# cur.execute('create database if not exists python')
conn.select_db('python')
# cur.execute('create table if not exists test (id int,info varchar(20))')
value=[1,'hi rollen']
cur.execute('insert into test values(%s,%s)',value)
values=[]
print datetime.datetime.now()
for i in range(10000):
values.append((i,'hi rollen'+str(i)))
# cur.executemany('insert into test values(%s,%s)',values)
# cur.execute('update test set info="I am rollen" where id=3')
#
# conn.commit()
print datetime.datetime.now()
print '请注意一定要有conn.commit()这句来提交事务,要不然不能真正的插入数据'
cur.close()
conn.close()
except dbi.Error,e:
print 'Mysql error %d:%s' %(e.args[0],e.args[1])
三、解决入库或显示中文乱码的问题
1.设置python默认的编码
在D:\Program\Python27\Lib\site-packages目录下,创建sitecustomize.py文件,内容如下:
import sys
sys.setdefaultencoding('utf-8')
python启动时,会自动加载sys模块并设置默认编码为utf-8
2.设置MYSQL的数据库编码为utf8
将default_character-set、character-set-server的值设置为utf8
[client]
port = 3306
socket = /data/mysqldata/mysql/mysql.sock
default_character-set=utf8
[mysqld]
port = 3306
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
lower_case_table_names=1
socket = /data/mysqldata/mysql/mysql.sock
datadir = /data/mysqldata/mysql
character-set-server = utf8
3.将py文件的编码设置为utf-8,并用utf-8进行保存
# encoding=utf-8
4.创建MYSQL数据库连接时,增加charset参数 conn=dbi.connect(host="172.168.29.250",user='root',passwd='root',db='test',port=3306,charset='utf8')
四、常用函数
这个连接对象也提供了对事务操作的支持,标准的方法
commit() 提交
rollback() 回滚
cursor用来执行命令的方法:
callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args):执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self):移动到下一个结果集
cursor用来接收返回值的方法:
fetchall(self):接收全部的返回结果行.
fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):返回一条结果行.
scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条.
http://mysql-python.sourceforge.net/MySQLdb.html
http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html
来源:oschina
链接:https://my.oschina.net/u/1410765/blog/199824