有一同事要离职了,我负责交接一个用Python同步数据的项目。
之前木有做过Python,周休,做个简单的查询数据库,小练一下手。
包含:
安装
连接、查询MySQL
列表
元组
for循环
while循环
下载
上Python官方网站,下载Python安装包,目前流行的版本为2.7和3.x版本,这两个大版本之间语法有些差异,并不兼容。
这次项目用到的是2.7版本,所以,先学习此。
目前,下载页面为:https://www.python.org/downloads/release/python-279/
安装
windows的安装步骤与普通软件一致,安装完成后,需将python目录设置(用“追加”来形容可能更合适)到PATH中。
再用命令查看其版本,以确认是否成功安装
python -v
View Code
hello world,少不了的hello world
#!/usr/bin/python
#output HELLO WORLD
print 'HELLO WORLD.';
View Code
这次的需求是连接Mysql。
首先,下载并安装MySQL的Connector/Python
目前,可从此页面下载:http://dev.mysql.com/downloads/connector/python/1.0.html
与普通软件安装无异。
编写脚本
连接数据库,并查询数据
#coding=utf-8#!/usr/bin/python
importmysql.connector;try:
conn= mysql.connector.connect(host='172.0.0.1', port='3306', user='username', password="123456", database="testdev", use_unicode=True);
cursor=conn.cursor();
cursor.execute('select * from t_user t where t.id = %s', '1');#取回的是列表,列表中包含元组
list =cursor.fetchall();printlist;for record inlist:print "Record %d is %s!" % (record[0], record[1]);exceptmysql.connector.Error as e:print ('Error : {}'.format(e));finally:
cursor.close;
conn.close;print 'Connection closed in finally';
View Code
运行脚本
直接运行此py脚本就可以了
018.连接MYSQL.py
View Code
fetchall函数返回的是[(xxx, xxx)]的记录,数据结构为“列表(中括号[])包含元组(小括号())”。此二属于常用的集合。
列表
就像JAVA的List,即,有序的;可包含不同类型元素的
#coding=utf-8#!/usr/bin/python
list= ['today', 'is', 'sunday'];
index=0;for record inlist:print str(index) + ":" +record;
index= index + 1;
View Code
结果:
d:\python27_workspace>"04.list type.py"0 : today1 : is
2 : sunday
View Code
元组
与列表类型,只是元组的元素不能修改
#coding=utf-8#!/usr/bin/python
tuple= ('today', 'is', 'sunday');#TypeError: 'tuple' object does not support item assignment#tuple[1] = 'are';
index=0;while (index
index= index + 1;
View Code
围绕着连接、查询MySQL这个需求,算是对Python作了一个初步的认识与实践。