1、检视Python版本
如果尚未安装Python,那么你可以到Python官网进行下载:
For the MD5 checksums and OpenPGP signatures, look at the page:
- (Windows binary -- does not include source)
- (Windows AMD64 / Intel 64 / X86-64 binary -- does not include source)
- (for Mac OS X 10.6 and later )
- (for Mac OS X 10.5 and later )
- (for Linux, Unix or Mac OS X)
- (for Linux, Unix or Mac OS X, better compression)
For the MD5 checksums and OpenPGP signatures, look at the page:
- (Windows binary -- does not include source)
- (Windows AMD64 / Intel 64 / X86-64 binary -- does not include source)
- (for Mac OS X 10.6 and later )
- (for Mac OS X 10.3 and later )
- (for Linux, Unix or Mac OS X)
- (for Linux, Unix or Mac OS X, better compression)
或者,你嫌慢,可以找几个离得近的:
Python for Windows
3.2.2
安装,很简单,一步一步NEXT就好了,默认装到C:\python下,我觉得这个路径就很好。
2、安装Python-mysql库
我试了下,我机器上使用easy_install安装MySQLdb出错。
windows解决方案:easy_install MySQL-python 或者 pip install MySQL-python不过,我用的最笨的方法,到这里下载了MySQL-python.rar安装包进行安装。
Linux解决方案:apt-get install python-dev 或者 yum install python-devel
3、Python-mysql主要操作
主要操作,可以参考如下代码(转自):
-
#-*- 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()
相关资料:
[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8 (本节引自http://drizzlewalk.blog.51cto.com/2203401/448874)