python mysql

坚持每天学一点,每天积累一点点,作为自己每天的业余收获,这个文章是我在吃饭的期间写的,利用自己零散的时间学了一下python操作MYSQL,所以整理一下。

我采用的是MySQLdb操作的MYSQL数据库。先来一个简单的例子吧:

import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
    cur=conn.cursor()
    cur.execute('select * from user')
    cur.close()
    conn.close()
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

  请注意修改你的数据库,主机名,用户名,密码。

下面来大致演示一下插入数据,批量插入数据,更新数据的例子吧:

import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    cur=conn.cursor()
     
    cur.execute('create database if not exists python')
    conn.select_db('python')
    cur.execute('create table test(id int,info varchar(20))')
     
    value=[1,'hi rollen']
    cur.execute('insert into test values(%s,%s)',value)
     
    values=[]
    for iin range(20):
        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()
    cur.close()
    conn.close()
 
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

  请注意一定要有conn.commit()这句来提交事务要不然不能真正的插入数据。

运行之后我的MySQL数据库的结果就不上图了。

import MySQLdb
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
    cur=conn.cursor()
     
    conn.select_db('python')
 
    count=cur.execute('select * from test')
    print 'there has %s rows record' % count
 
    result=cur.fetchone()
    print result
    print 'ID: %s info %s' % result
 
    results=cur.fetchmany(5)
    for r in results:
        print r
 
    print '=='*10
    cur.scroll(0,mode='absolute')
 
    results=cur.fetchall()
    for r in results:
        print r[1]
     
 
    conn.commit()
    cur.close()
    conn.close()
 
except MySQLdb.Error,e:
     print "Mysql Error %d: %s" % (e.args[0], e.args[1])

  运行结果就不贴了,太长了。

查询后中文会正确显示,但在数据库中却是乱码的。经过我从网上查找,发现用一个属性有可搞定:

在Python代码 

conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python') 中加一个属性:
 改为:
conn = MySQLdb.Connect(host='localhost', user='root', passwd='root', db='python',charset='utf8') 
charset是要跟你数据库的编码一样,如果是数据库是gb2312 ,则写charset='gb2312'。

 ################################################

下面贴一下常用的函数:

然后,这个连接对象也提供了对事务操作的支持,标准的方法
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条.

参考资料:

MySQLdb‘s user guide

package MySQLdb

#############################################

开始操作的demo:

Python代码
# -*- coding: utf-8 -*-     
#mysqldb    
import time, MySQLdb    
   
#连接    
conn=MySQLdb.connect(host="localhost",user="root",passwd="",db="test",charset="utf8")  
cursor = conn.cursor()    
   
#写入    
sql = "insert into user(name,created) values(%s,%s)"   
param = ("aaa",int(time.time()))    
n = cursor.execute(sql,param)    
print n    
   
#更新    
sql = "update user set name=%s where id=3"   
param = ("bbb")    
n = cursor.execute(sql,param)    
print n    
   
#查询    
n = cursor.execute("select * from user")    
for row in cursor.fetchall():    
    for r in row:    
        print r    
   
#删除    
sql = "delete from user where name=%s"   
param =("aaa")    
n = cursor.execute(sql,param)    
print n    
cursor.close()    
   
#关闭    
conn.close()  

############################################################################

基本的使用如上,还是很简单的,进一步使用还没操作,先从网上找点资料放上来,以备后续查看

1.引入MySQLdb库 

import MySQLdb 

2.和数据库建立连接 
conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8") 
提供的connect方法用来和数据库建立连接,接收数个参数,返回连接对象. 

比较常用的参数包括 
host:数据库主机名.默认是用本地主机. 
user:数据库登陆名.默认是当前用户. 
passwd:数据库登陆的秘密.默认为空. 
db:要使用的数据库名.没有默认值. 
port:MySQL服务使用的TCP端口.默认是3306.
charset:数据库编码.

更多关于参数的信息可以查这里 
http://mysql-python.sourceforge.net/MySQLdb.html 

然后,这个连接对象也提供了对事务操作的支持,标准的方法 
commit() 提交 
rollback() 回滚 

3.执行sql语句和接收返回值 
cursor=conn.cursor() 
n=cursor.execute(sql,param) 
首先,我们用使用连接对象获得一个cursor对象,接下来,我们会使用cursor提供的方法来进行工作.这些方法包括两大类:1.执行命令,2.接收返回值 

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条. 

下面的代码是一个完整的例子. 
#使用sql语句,这里要接收的参数都用%s占位符.要注意的是,无论你要插入的数据是什么类型,占位符永远都要用%s 
sql="insert into cdinfo values(%s,%s,%s,%s,%s)" 
#param应该为tuple或者list 
param=(title,singer,imgurl,url,alpha) 
#执行,如果成功,n的值为1 
n=cursor.execute(sql,param) 

#再来执行一个查询的操作 
cursor.execute("select * from cdinfo") 
#我们使用了fetchall这个方法.这样,cds里保存的将会是查询返回的全部结果.每条结果都是一个tuple类型的数据,这些tuple组成了一个tuple 
cds=cursor.fetchall() 
#因为是tuple,所以可以这样使用结果集 
print cds[0][3] 
#或者直接显示出来,看看结果集的真实样子 
print cds 

#如果需要批量的插入数据,就这样做 
sql="insert into cdinfo values(0,%s,%s,%s,%s,%s)" 
#每个值的集合为一个tuple,整个参数集组成一个tuple,或者list 
param=((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2)) 
#使用executemany方法来批量的插入数据.这真是一个很酷的方法! 
n=cursor.executemany(sql,param) 

4.关闭数据库连接 
需要分别的关闭指针对象和连接对象.他们有名字相同的方法 
cursor.close() 
conn.close() 

四步完成,基本的数据库操作就是这样了.下面是两个有用的连接 
MySQLdb用户指南: 
http://mysql-python.sourceforge.net/MySQLdb.html 
MySQLdb文档: 
http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html

5 编码(防止乱码)

需要注意的点:

    1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
    2 MySQL
数据库charset=utf-8 
    3 Python
连接MySQL是加上参数 charset=utf8 
    4 
设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)

#encoding=utf-8 
 import sys 
 import MySQLdb 
  
 reload(sys) 
 sys.setdefaultencoding('utf-8') 
  
 db=MySQLdb.connect(user='root',charset='utf8') 


注:MySQL的配置文件设置也必须配置成utf8

设置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都设置默认的字符集(通常在/etc/mysql/my.cnf): 

[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8

########################################################

python mysql乱码问题

安装好之后,模块名字叫做MySQLdb ,在Window和Linux环境下都可以使用,试验了一下挺好用,
不过又发现了烦人的乱麻问题,最后用了几个办法,解决了!
我用了下面几个措施,保证MySQL的输出没有乱麻:
    1 Python文件设置编码 utf-8 (文件前面加上 #encoding=utf-8)
    2 MySQL数据库charset=utf-8 
    3 Python连接MySQL是加上参数 charset=utf8 
    4 设置Python的默认编码为 utf-8 (sys.setdefaultencoding(utf-8)

mysql_test.py

#encoding=utf-8
import sys
import MySQLdb
reload(sys)
sys.setdefaultencoding('utf-8')

db=MySQLdb.connect(user='root',charset='utf8')
cur=db.cursor()
cur.execute('use mydb')
cur.execute('select * from mytb limit 100')
f=file("/home/user/work/tem.txt",'w')
for i in cur.fetchall():
    f.write(str(i))
    f.write(" ")
f.close()
cur.close()   

上面是linux上的脚本,windows下运行正常!
注:MySQL的配置文件设置也必须配置成utf8
设置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都设置默认的字符集(通常在/etc/mysql/my.cnf): 
[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8

###########################################################

使用ultramysql + gevent

①ultramysql下载:https://github.com/esnme/ultramysql

#python setup.py build install

②配置gevent环境

安装 libevent

apt-get install libevent-dev

安装python-dev

apt-get install python-dev

安装greenlet

easy_install greenlet

安装gevent

easy_install gevent

一个小测试

测试gevent 的任务池

?
from  gevent import  pool
g =  pool.Pool()
def  a():
     for  i in  xrange ( 100 ):
         g.spawn(b)
def  b():
     print  'b'
g.spawn(a)
g.join()

注意:gevent运行为非阻塞模式,主要用于并发执行模式。

以上内容部分来自互联网!


python调用MySql存储过程

环境:

1.mysql5.0 或者以上支持存储过程的版本

2.安装MySQL-python,目前支持到2.x

步骤:

一.数据库准备

1.建立表

CREATE TABLE `Account` (
`id`BIGINT(20)NOT NULL AUTO_INCREMENT,
`sm_accountName`VARCHAR(100)COLLATE gbk_chinese_ciNOT NULL DEFAULT '',
`sm_password` TEXT COLLATE gbk_chinese_ciNOT NULL,
`sm_onlineTime`BIGINT(20) UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `accountNameIndex` (`sm_accountName`)
)ENGINE=InnoDB

?

2.建立存储过程

CREATE  PROCEDURE `proctest`(IN i_idBIGINT,IN i_onlinetimeBIGINT,OUT o_accnameVARCHAR(30),OUT o_accpwdVARCHAR(50))
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT''
BEGIN
select sm_accountName,sm_password
into o_accname,o_accpwd
from `tbl_Account`where id=i_idand sm_onlineTime=i_onlinetime limit 1;
END;

?

3.插入部分数据

INSERT INTO `Account` (`id`, `sm_accountName`, `sm_password`, `sm_onlineTime`) VALUES
(1,'luoshulin','asdfsdf', 0),
(2,'test','1', 0),
(3,'adsfasd','asdf', 1);
?

到这里数据库相关内容就准备好了接下去开始写python脚本

二.python脚本

#!/usr/bin/env python
# -*- coding: utf8 -*-
import MySQLdb
import time
import os, sys, string
def CallProc(id,onlinetime):
'''调用存储过程,
输入参数:编号,在线时间,输出:帐号,密码;
使用输出参数方式'''
accname=''
accpwd=''
conn= MySQLdb.connect(host='localhost',user='root',passwd='111111',db='ceshi')
cur=conn.cursor()
cur.callproc('proctest',(id,onlinetime,accname,accpwd))
cur.execute('select @_proctest_2,@_proctest_3')
data=cur.fetchall()
if data:
for recin data:
accname=rec[0]
accpwd=rec[1]
cur.close()
conn.close();
return accname,accpwd
def CallProct(id,onlinetime):
'''调用存储过程,
输入参数:编号,在线时间,输出:帐号,密码;
使用select返回记录方式'''
accname=''
accpwd=''
conn= MySQLdb.connect(host='localhost',user='root',passwd='111111',db='ceshi')
cur=conn.cursor()
cur.nextset()
cur.execute('call ptest(%s,%s)',(id,onlinetime))
data=cur.fetchall()
if data:
for recin data:
accname=rec[0]
accpwd=rec[1]
cur.close()
conn.close();
return accname,accpwd
name,pwd=CallProct(1,0)
print name,pwd

三.测试

将python脚本保存为 并执行可以看到结果

?
1
2
[root@redhat-dev python] # python pycallproc.py
luoshulin asdfsdf

测试使用的是select返回记录的方式,对于使用输出参数返回结果情况也是一样的。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值