mysql connector python windows_随笔记:Python于Windows下初实践,及使用Connector/Python连接MySQL...

有一同事要离职了,我负责交接一个用Python同步数据的项目。

之前木有做过Python,周休,做个简单的查询数据库,小练一下手。

包含:

安装

连接、查询MySQL

列表

元组

for循环

while循环

下载

上Python官方网站,下载Python安装包,目前流行的版本为2.7和3.x版本,这两个大版本之间语法有些差异,并不兼容。

这次项目用到的是2.7版本,所以,先学习此。

目前,下载页面为:https://www.python.org/downloads/release/python-279/

安装

windows的安装步骤与普通软件一致,安装完成后,需将python目录设置(用“追加”来形容可能更合适)到PATH中。

再用命令查看其版本,以确认是否成功安装

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

python -v

View Code

hello world,少不了的hello world

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

#!/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

与普通软件安装无异。

编写脚本

连接数据库,并查询数据

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

#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脚本就可以了

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

018.连接MYSQL.py

View Code

fetchall函数返回的是[(xxx, xxx)]的记录,数据结构为“列表(中括号[])包含元组(小括号())”。此二属于常用的集合。

列表

就像JAVA的List,即,有序的;可包含不同类型元素的

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

#coding=utf-8#!/usr/bin/python

list= ['today', 'is', 'sunday'];

index=0;for record inlist:print str(index) + ":" +record;

index= index + 1;

View Code

结果:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

d:\python27_workspace>"04.list type.py"0 : today1 : is

2 : sunday

View Code

元组

与列表类型,只是元组的元素不能修改

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

#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作了一个初步的认识与实践。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值