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
安装,很简单,一步一步NEXT就好了,默认装到C:\python下,我觉得这个路径就很好。
2、安装Python-mysql库
我试了下,我机器上使用easy_install安装MySQLdb出错。
windows解决方案:easy_install MySQL-python 或者 pip install MySQL-python不过,我用的最笨的方法,到http://www.cr173.com/soft/22957.html这里下载了MySQL-python.rar安装包进行安装。
Linux解决方案:apt-get install python-dev 或者 yum install python-devel
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()
相关资料:
[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8 (本节引自http://drizzlewalk.blog.51cto.com/2203401/448874)