有一同事要离职了,我负责交接一个用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
hello world,少不了的hello world
#!/usr/bin/python # output HELLO WORLD
print 'HELLO WORLD.';
这次的需求是连接Mysql。
首先,下载并安装MySQL的Connector/Python
目前,可从此页面下载:http://dev.mysql.com/downloads/connector/python/1.0.html
与普通软件安装无异。
编写脚本
连接数据库,并查询数据
#coding=utf-8
#!/usr/bin/python
import mysql.connector; try:
conn = mysql.connector.connect(host='172.0.0.1', port='', user='username', password="", database="testdev", use_unicode=True);
cursor = conn.cursor();
cursor.execute('select * from t_user t where t.id = %s', '');
# 取回的是列表,列表中包含元组
list = cursor.fetchall();
print list; for record in list:
print "Record %d is %s!" % (record[0], record[1]); except mysql.connector.Error as e:
print ('Error : {}'.format(e));
finally:
cursor.close;
conn.close;
print 'Connection closed in finally';
运行脚本
直接运行此py脚本就可以了
018.连接MYSQL.py
fetchall函数返回的是[(xxx, xxx)]的记录,数据结构为“列表(中括号[])包含元组(小括号())”。此二属于常用的集合。
列表
就像JAVA的List,即,有序的;可包含不同类型元素的
#coding=utf-8
#!/usr/bin/python list = ['today', 'is', 'sunday'];
index = 0;
for record in list:
print str(index) + " : " + record;
index = index + 1;
结果:
d:\python27_workspace>"04.list type.py"
0 : today
1 : is
2 : sunday
元组
与列表类型,只是元组的元素不能修改
#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 < len(tuple)):
print str(index) + " : " + tuple[index];
index = index + 1;
围绕着连接、查询MySQL这个需求,算是对Python作了一个初步的认识与实践。