您的位置:首页 > 编程语言 > Python开发

Win7下Python操作MySQL步骤

2016-01-27 10:21 267 查看
1、检视Python版本

如果尚未安装Python,那么你可以到Python官网进行下载:

For the MD5 checksums and OpenPGP signatures, look at the detailed
Python 3.3.3 page:

Python
3.3.3 Windows x86 MSI Installer (Windows binary -- does not include source)

Python
3.3.3 Windows X86-64 MSI Installer (Windows AMD64 / Intel 64 / X86-64 binary [1] --
does not include source)

Python
3.3.3 Mac OS X 64-bit/32-bit x86-64/i386 Installer (for Mac OS X 10.6 and later [2])

Python
3.3.3 Mac OS X 32-bit i386/PPC Installer (for Mac OS X 10.5 and later [2])

Python
3.3.3 compressed source tarball (for Linux, Unix or Mac OS X)

Python
3.3.3 xzipped source tarball (for Linux, Unix or Mac OS X, better compression)

For the MD5 checksums and OpenPGP signatures, look at the detailed
Python 2.7.6 page:

Python
2.7.6 Windows Installer (Windows binary -- does not include source)

Python
2.7.6 Windows X86-64 Installer (Windows AMD64 / Intel 64 / X86-64 binary [1] --
does not include source)

Python
2.7.6 Mac OS X 64-bit/32-bit x86-64/i386 Installer (for Mac OS X 10.6 and later [2])

Python
2.7.6 Mac OS X 32-bit i386/PPC Installer (for Mac OS X 10.3 and later [2])

Python
2.7.6 compressed source tarball (for Linux, Unix or Mac OS X)

Python
2.7.6 xzipped source tarball (for Linux, Unix or Mac OS X, better compression)

或者,你嫌慢,可以找几个离得近的:


Python for Windows

3.2.2

电信下载:
本地电信1本地电信2

网通下载:
本地网通

专用下载:
迅雷下载快车下载

安装,很简单,一步一步NEXT就好了,默认装到C:\python下,我觉得这个路径就很好。

2、安装Python-mysql库

我试了下,我机器上使用easy_install安装MySQLdb出错。



适才发现这是个名称错误的问题,国外友人已经回答了,有如下方案:

windows解决方案:easy_install
MySQL-python 或者 pip install MySQL-python

Linux解决方案:apt-get
install python-dev
或者 yum install python-devel

不过,我用的最笨的方法,到http://www.cr173.com/soft/22957.html这里下载了MySQL-python.rar安装包进行安装。

3、Python-mysql主要操作

主要操作,可以参考如下代码(转自Sephiroth):

#-*- encoding: gb2312 -*-

import os, sys, string

import MySQLdb

# 连接数据库 

try:

conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')

except Exception, e:

print e

sys.exit()

# 获取cursor对象来进行操作

cursor = conn.cursor()

# 创建表

sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"

cursor.execute(sql)

# 插入数据

sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)

try:

cursor.execute(sql)

except Exception, e:

print e

sql = "insert into test1(name, age) values ('%s', %d)" % ("张三", 21)

try:

cursor.execute(sql)

except Exception, e:

print e

# 插入多条

sql = "insert into test1(name, age) values (%s, %s)"

val = (("李四", 24), ("王五", 25), ("洪六", 26))

try:

cursor.executemany(sql, val)

except Exception, e:

print e

#查询出数据

sql = "select * from test1"

cursor.execute(sql)

alldata = cursor.fetchall()

# 如果有数据返回,就循环输出, alldata是有个二维的列表

if alldata:

for rec in alldata:

print rec[0], rec[1]

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)
注:MySQL的配置文件设置也必须配置成utf8

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

[client]

default-character-set = utf8

[mysqld]

default-character-set = utf8 (本节引自/article/4436254.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: