??xml version="1.0" encoding="utf-8" standalone="yes"?>天天av综合,在线一级成人,一区二区三区日韩http://www.aygfsteel.com/nkjava/category/47980.html|n瀚的沙漠Q方向最为重要,希望此blog能向大漠驼铃一Pl我方向和指引? EJB/JPA/JSF/Struts/Spring/Hibernate/Perl/Shell/C/Java zh-cnSun, 14 Aug 2011 08:26:30 GMTSun, 14 Aug 2011 08:26:30 GMT60python 判断 nullhttp://www.aygfsteel.com/nkjava/archive/2011/08/14/356482.html草原上的骆驼草原上的骆驼Sun, 14 Aug 2011 00:47:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/08/14/356482.htmlhttp://www.aygfsteel.com/nkjava/comments/356482.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/08/14/356482.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/356482.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/356482.htmlif not result2 is  None :

if result is None

注意是大?img src ="http://www.aygfsteel.com/nkjava/aggbug/356482.html" width = "1" height = "1" />

草原上的骆驼 2011-08-14 08:47 发表评论
]]>
Python q接 Mysqlhttp://www.aygfsteel.com/nkjava/archive/2011/08/14/356481.html草原上的骆驼草原上的骆驼Sun, 14 Aug 2011 00:46:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/08/14/356481.htmlhttp://www.aygfsteel.com/nkjava/comments/356481.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/08/14/356481.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/356481.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/356481.html
#coding=utf-8

#MySQLdb CZ
#
##################################
import MySQLdb

#建立和数据库pȝ的连?br />conn 
= MySQLdb.connect(host='localhost', user='root',passwd='longforfreedom')

#获取操作游标
cursor 
= conn.cursor()
#执行SQL,创徏一个数据库.
cursor.execute(
"""create database python """)

#关闭q接Q释放资?br />cursor.close();
插入数据、批量插入数?br />
#coding=utf-8
###################################
# @author migle
# @date 
2010-01-17
##################################
#MySQLdb CZ
#
##################################
import MySQLdb

#建立和数据库pȝ的连?br />conn 
= MySQLdb.connect(host='localhost', user='root',passwd='21ccvn')

#获取操作游标
cursor 
= conn.cursor()
#执行SQL,创徏一个数据库.
cursor.execute(
"""create database if not exists 21ccvn""")

#选择数据?br />conn.select_db(
'21ccvn');
#执行SQL,创徏一个数据表.
cursor.execute(
"""create table 21ccvn(id int, info varchar(100)) """)

value 
= [1,"inserted ?"];

#插入一条记?br />cursor.execute(
"insert into test values(%s,%s)",value);

values
=[]


#生成插入参数?br />
for i in range(20):
    values.append((i,
'Hello mysqldb, I am recoder ' + str(i)))
#插入多条记录

cursor.executemany(
"""insert into test values(%s,%s) """,values);

#关闭q接Q释放资?br />cursor.close();
查询Q获取一个,获取多个Q获取所有记录数
#coding=utf-8

#
# MySQLdb 查询
#
#######################################

import MySQLdb

conn 
= MySQLdb.connect(host='localhost', user='root', passwd='longforfreedom',db='21ccvn')

cursor 
= conn.cursor()

count 
= cursor.execute('select * from test')

print 
'd?nbsp;%s 条记?/span>',count

#获取一条记?每条记录做ؓ一个元l返?br />print 
"只获取一条记?"
result 
= cursor.fetchone();
print result
#print 
'ID: %s   info: %s' % (result[0],result[1])
print 
'ID: %s   info: %s' % result 

#获取5条记录,注意׃之前执行有了fetchone()Q所以游标已l指到第二条记录了,也就是从W二条开始的所有记?br />print 
"只获?条记?"
results 
= cursor.fetchmany(5)
for r in results:
    print r

print 
"获取所有结?"
#重置游标位置Q?/span>0,为偏U量QmodeQabsolute | relative,默认为relative,
cursor.scroll(
0,mode='absolute')
#获取所有结?br />results 
= cursor.fetchall()
for r in results:
    print r
conn.close()


草原上的骆驼 2011-08-14 08:46 发表评论
]]>
python的time和date处理http://www.aygfsteel.com/nkjava/archive/2011/03/04/345725.html草原上的骆驼草原上的骆驼Fri, 04 Mar 2011 08:23:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345725.htmlhttp://www.aygfsteel.com/nkjava/comments/345725.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345725.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/345725.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/345725.html内置模块time包含很多与时间相兛_数。我们可通过它获得当前的旉和格式化旉输出?/p>

time()Q以点形式q回自LinuxCU以来经q的U数。在linux中,00:00:00 UTC, January 1, 1970是新**49**的开始?/p>
strftime可以用来获得当前旉Q可以将旉格式化ؓ字符串等{,q挺方便的。但是需要注意的是获得的旉是服务器的时_注意时区问题Q比如gae撒谎那个的时间就是格林尼L间的0时区Q需要自p{换?br />
strftimeQ)函数时间格式化
我们可以使用strftimeQ)函数时间格式化为我们想要的格式。它的原型如下:

size_t strftime(
char *strDest,
size_t maxsize,
const char *format,
const struct tm *timeptr
);

我们可以Ҏformat指向字符串中格式命o把timeptr中保存的旉信息攑֜strDest指向的字W串中,最多向strDest中存放maxsize个字W。该函数q回向strDest指向的字W串中放|的字符数?br />
strftime使时间格式化。python的strftime格式是C库支持的旉格式的真子集?br />
  %a 星期几的?Weekday name, abbr.
  %A 星期几的全称 Weekday name, full
  %b 月分的简?Month name, abbr.
  %B 月䆾的全U?Month name, full
  %c 标准的日期的旉?Complete date and time representation
  %d 十进制表C的每月的第几天 Day of the month
  %H 24时制的时 Hour (24-hour clock)
  %I 12时制的时 Hour (12-hour clock)
  %j 十进制表C的每年的第几天 Day of the year
  %m 十进制表C的月䆾 Month number
  %M 十时制表C的分钟?Minute number
  %S 十进制的U数 Second number
  %U W年的第几周Q把星期日做为第一天(g0?3QWeek number (Sunday first weekday)
  %w 十进制表C的星期几(g0?Q星期天?Qweekday number
  %W 每年的第几周Q把星期一做ؓW一天(g0?3Q?Week number (Monday first weekday)
  %x 标准的日期串 Complete date representation (e.g. 13/01/08)
  %X 标准的时间串 Complete time representation (e.g. 17:02:10)
  %y 不带世纪的十q制q䆾Qg0?9QYear number within century
  %Y 带世U部分的十制q䆾 Year number
  %zQ?Z 时区名称Q如果不能得到时区名U则q回I字W。Name of time zone
  %% 癑ֈ?

1. # handling date/time data
   2. # Python23 tested vegaseat 3/6/2005
   3.
   4. import time
   5.
   6. print "List the functions within module time:"
   7. for funk in dir(time):
   8. print funk
   9.
  10. print time.time(), "seconds since 1/1/1970 00:00:00"
  11. print time.time()/(60*60*24), "days since 1/1/1970"
  12.
  13. # time.clock() gives wallclock seconds, accuracy better than 1 ms
  14. # time.clock() is for windows, time.time() is more portable
  15. print "Using time.clock() = ", time.clock(), "seconds since first call to clock()"
  16. print "\nTiming a 1 million loop 'for loop' ..."
  17. start = time.clock()
  18. for x in range(1000000):
  19. y = x # do something
  20. end = time.clock()
  21. print "Time elapsed = ", end - start, "seconds"
  22.
  23. # create a tuple of local time data
  24. timeHere = time.localtime()
  25. print "\nA tuple of local date/time data using time.localtime():"
  26. print "(year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)"
  27. print timeHere
  28.
  29. # extract a more readable date/time from the tuple
  30. # eg. Sat Mar 05 22:51:55 2005
  31. print "\nUsing time.asctime(time.localtime()):", time.asctime(time.localtime())
  32. # the same results
  33. print "\nUsing time.ctime(time.time()):", time.ctime(time.time())
  34. print "\nOr using time.ctime():", time.ctime()
  35.
  36. print "\nUsing strftime():"
  37. print "Day and Date:", time.strftime("%a %m/%d/%y", time.localtime())
  38. print "Day, Date :", time.strftime("%A, %B %d, %Y", time.localtime())
  39. print "Time (12hr) :", time.strftime("%I:%M:%S %p", time.localtime())
  40. print "Time (24hr) :", time.strftime("%H:%M:%S", time.localtime())
  41. print "DayMonthYear:",time.strftime("%d%b%Y", time.localtime())
  42.
  43. print
  44.
  45. print "Start a line with this date-time stamp and it will sort:",\
  46. time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
  47.
  48. print
  49.
  50. def getDayOfWeek(dateString):
  51. # day of week (Monday = 0) of a given month/day/year
  52. t1 = time.strptime(dateString,"%m/%d/%Y")
  53. # year in time_struct t1 can not go below 1970 (start of epoch)!
  54. t2 = time.mktime(t1)
  55. return(time.localtime(t2)[6])
  56.
  57. Weekday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
  58. 'Friday', 'Saturday', 'Sunday']
  59.
  60. # sorry about the limitations, stay above 01/01/1970
  61. # more exactly 01/01/1970 at 0 UT (midnight Greenwich, England)
  62. print "11/12/1970 was a", Weekday[getDayOfWeek("11/12/1970")]
  63.
  64. print
  65.
  66. print "Calculate difference between two times (12 hour format) of a day:"
  67. time1 = raw_input("Enter first time (format 11:25:00AM or 03:15:30PM): ")
  68. # pick some plausible date
  69. timeString1 = "03/06/05 " + time1
  70. # create a time tuple from this time string format eg. 03/06/05 11:22:00AM
  71. timeTuple1 = time.strptime(timeString1, "%m/%d/%y %I:%M:%S%p")
  72.
  73. #print timeTuple1 # test eg. (2005, 3, 6, 11, 22, 0, 5, 91, -1)
  74.
  75. time2 = raw_input("Enter second time (format 11:25:00AM or 03:15:30PM): ")
  76. # use same date to stay in same day
  77. timeString2 = "03/06/05 " + time2
  78. timeTuple2 = time.strptime(timeString2, "%m/%d/%y %I:%M:%S%p")
  79.
  80. # mktime() gives seconds since epoch 1/1/1970 00:00:00
  81. time_difference = time.mktime(timeTuple2) - time.mktime(timeTuple1)
  82. #print type(time_difference) # test <type 'float'>
  83. print "Time difference = %d seconds" % int(time_difference)
  84. print "Time difference = %0.1f minutes" % (time_difference/60.0)
  85. print "Time difference = %0.2f hours" % (time_difference/(60.0*60))
  86.
  87. print
  88.
  89. print "Wait one and a half seconds!"
  90. time.sleep(1.5)
  91. print "The end!"



草原上的骆驼 2011-03-04 16:23 发表评论
]]>
Python IOhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345724.html草原上的骆驼草原上的骆驼Fri, 04 Mar 2011 08:10:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345724.htmlhttp://www.aygfsteel.com/nkjava/comments/345724.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345724.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/345724.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/345724.html

1.open

使用open打开文g后一定要记得调用文g对象的close()Ҏ。比如可以用try/finally语句来确保最后能关闭文g?/p>

file_object = open('thefile.txt')
try:
     all_the_text 
= file_object.read( )
finally:
     file_object.close( )


注:不能把open语句攑֜try块里Q因为当打开文g出现异常Ӟ文g对象file_object无法执行close()Ҏ?/p>

2.L?/span>

L本文?/h4>
input = open('data''r')
#W二个参数默认ؓr
input = open('data')

 

Mq制文g

input = open('data''rb')

 

d所有内?/h4>
file_object = open('thefile.txt')
try:
     all_the_text 
= file_object.read( )
finally:
     file_object.close( )

 

d定字?/h4>
file_object = open('abinfile''rb')
try:
    
while True:
         chunk 
= file_object.read(100)
        
if not chunk:
            
break
         do_something_with(chunk)
finally:
     file_object.close( )

 

L?/h4>
list_of_all_the_lines = file_object.readlines( )


如果文g是文本文Ӟq可以直接遍历文件对象获取每行:

for line in file_object:
     process line

 

3.写文?/span>

写文本文?/h4>
output = open('data''w')

 

写二q制文g

output = open('data''wb')

 

q加写文?/h4>
output = open('data''w+')

 

写数?/h4>
file_object = open('thefile.txt''w')
file_object.write(all_the_text)
file_object.close( )

 

写入多行

file_object.writelines(list_of_text_strings)


注意Q调用writelines写入多行在性能上会比用write一ơ性写入要高?/p>

在处理日志文件的时候,常常会遇到这L情况Q日志文件巨大,不可能一ơ性把整个文gd到内存中q行处理Q例如需要在一台物理内存ؓ 2GB 的机器上处理一?2GB 的日志文Ӟ我们可能希望每次只处理其?200MB 的内宏V?br style="line-height: normal" /> ?Python 中,内置?File 对象直接提供了一?readlines(sizehint) 函数来完成这L事情。以下面的代码ؓ例:

file = open('test.log', 'r')
sizehint
= 209715200   # 200M
position = 0
lines
= file.readlines(sizehint)
while not file.tell() - position < 0:
     position
= file.tell()
     lines
= file.readlines(sizehint)



每次调用 readlines(sizehint) 函数Q会q回大约 200MB 的数据,而且所q回的必焉是完整的行数据,大多数情况下Q返回的数据的字节数会稍微比 sizehint 指定的值大一点(除最后一ơ调?readlines(sizehint) 函数的时候)。通常情况下,Python 会自动将用户指定?sizehint 的D整成内部~存大小的整数倍?/div>

file在python是一个特D的cdQ它用于在pythonE序中对外部的文件进行操作。在python中一切都是对象,file也不例外Qfile有file的方法和属性。下面先来看如何创徏一个file对象Q?/div>

file(name[, mode[, buffering]])
file()函数用于创徏一个file对象Q它有一个别名叫open()Q可能更形象一些,它们是内|函数。来看看它的参数。它参数都是以字W串的Ş式传递的。name是文件的名字?/div>
mode是打开的模式,可选的gؓr w a UQ分别代表读Q默认) ?d 支持各种换行W的模式。用w或a模式打开文g的话Q如果文件不存在Q那么就自动创徏。此外,用w模式打开一个已l存在的文gӞ原有文g的内容会被清I,因ؓ一开始文件的操作的标记是在文件的开头的Q这时候进行写操作Q无疑会把原有的内容l抹掉。由于历史的原因Q换行符在不同的pȝ中有不同模式Q比如在 unix中是一个\nQ而在windows中是‘\r\n’Q用U模式打开文gQ就是支持所有的换行模式Q也p‘\r’ '\n' '\r\n'都可表示换行Q会有一个tuple用来存贮q个文g中用到过的换行符。不q,虽说换行有多U模式,dpython中统一用\n代替。在模式字符的后面,q可以加? b tq两U标识,分别表示可以Ҏ件同时进行读写操作和用二q制模式、文本模式(默认Q打开文g?/div>
buffering如果?表示不进行缓?如果?表示q行“行缓?#8220;;如果是一个大?的数表示~冲区的大小Q应该是以字节ؓ单位的?/div>

file对象有自q属性和Ҏ。先来看看file的属性?/div>

closed #标记文g是否已经关闭Q由close()改写
encoding #文g~码
mode #打开模式
name #文g?/div>
newlines #文g中用到的换行模式Q是一个tuple
softspace #boolean型,一般ؓ0Q据说用于print

file的读写方法:

F.read([size]) #size取的长度Q以byte为单?/div>
F.readline([size]) 
#M行,如果定义了sizeQ有可能q回的只是一行的一部分
F.readlines([size]) 
#把文件每一行作Z个list的一个成员,q返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数Qsize是表C取内容的总长Q也是说可能只d文g的一部分?/div>
F.write(str) 
#把str写到文g中,write()q不会在str后加上一个换行符
F.writelines(seq) 
#把seq的内容全部写到文件中。这个函C只是忠实地写入,不会在每行后面加上Q何东ѝ?/div>
file的其他方法:

F.close() 
#关闭文g。python会在一个文件不用后自动关闭文gQ不q这一功能没有保证Q最好还是养成自己关闭的习惯。如果一个文件在关闭后还对其q行操作会生ValueError
F.flush() 
#把缓冲区的内容写入硬?/div>
F.fileno() 
#q回一个长整型?#8221;文g标签“
F.isatty() 
#文g是否是一个终端设备文Ӟunixpȝ中的Q?/div>
F.tell() 
#q回文g操作标记的当前位|,以文件的开头ؓ原点
F.next() 
#q回下一行,q将文g操作标记位移C一行。把一个file用于for ... in fileq样的语句时Q就是调用next()函数来实现遍历的?/div>
F.seek(offset[,whence]) 
#文件打操作标记Udoffset的位|。这个offset一般是相对于文件的开头来计算的,一般ؓ正数。但如果提供了whence参数׃一定了Qwhence可以?表示从头开始计,1表示以当前位|ؓ原点计算?表示以文件末ؓ原点q行计算。需要注意,如果文g以a或a+的模式打开Q每ơ进行写操作Ӟ文g操作标记会自动返回到文g末尾?/div>
F.truncate([size]) 
#把文件裁成规定的大小Q默认的是裁到当前文件操作标记的位置。如果size比文件的大小q要大,依据pȝ的不同可能是不改变文Ӟ也可能是?把文件补到相应的大小Q也可能是以一些随机的内容加上厅R?/div>

 



]]>Python Mysql http://www.aygfsteel.com/nkjava/archive/2011/03/04/345723.html草原上的骆驼草原上的骆驼Fri, 04 Mar 2011 08:09:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345723.htmlhttp://www.aygfsteel.com/nkjava/comments/345723.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345723.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/345723.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/345723.html 

http://www.kitebird.com/articles/pydbapi.html

http://www.codegood.com/  python mysql驱动下蝲大全


the Python standard for database interfaces is the Python DB-API. Most Python database interfaces adhere to this standard.

You can choose the right database for your application. Python Database API supports a wide range of database servers:

  • GadFly
  • mSQL
  • MySQL
  • PostgreSQL
  • Microsoft SQL Server 2000
  • Informix
  • Interbase
  • Oracle
  • Sybase

Here is the list of available Python databases interfaces:

Python Database Interfaces and APIs
            

You must download a separate DB API module for each database you need to access. For example, if you need to access an Oracle database as well as a MySQL database, you must download both the Oracle and the MySQL database modules.

The DB API provides a minimal standard for working with databases, using Python structures and syntax wherever possible. This API includes the following:

  • Importing the api module.

  • Acquiring a connection with the database.

  • Issuing SQL statements and stored procedures.

  • Closing the connection

We would learn all the concepts using MySQL so let's talk about MySQLdb module only.

What is MySQLdb?

MySQLdb is an interface for connecting to a MySQL database server from Python. It implements the Python Database API v2.0, and is built on top of the MySQL C API.

How do I install the MySQLdb?

Before proceeding you make sure you have MySQLdb installed on your machine. Just type the following in your Python script and execute it:

#!/usr/bin/python
            import MySQLdb
            

If it produces following result then it means MySQLdb module is not installed:

Traceback (most recent call last):
            File "test.py", line 3, in <module>
            import MySQLdb
            ImportError: No module named MySQLdb
            

To install MySQLdb module, download it from MySQLdb Download page and proceed as follows:

$ gunzip MySQL-python-1.2.2.tar.gz
            $ tar -xvf MySQL-python-1.2.2.tar
            $ cd MySQL-python-1.2.2
            $ python setup.py build
            $ python setup.py install
            

Note: Make sure you have root privilege to install above module.

Database Connection:

Before connecting to a MySQL database make sure followings:

  • You have created a database TESTDB.

  • You have created a table EMPLOYEE in TESTDB.

  • This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.

  • User ID "testuser" and password "test123" are set to access TESTDB

  • Python module MySQLdb is installed properly on your machine.

  • You have gone through MySQL tutorial to understand MySQL Basics.

Example:

Following is the example of connecting with MySQL database "TESTDB"

#!/usr/bin/python
            import MySQLdb
            # Open database connection
            db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
            # prepare a cursor object using cursor() method
            cursor = db.cursor()
            # execute SQL query using execute() method.
            cursor.execute("SELECT VERSION()")
            # Fetch a single row using fetchone() method.
            data = cursor.fetchone()
            print "Database version : %s " % data
            # disconnect from server
            db.close()
            

While running this script, its producing following result at my Linux machine.

Database version : 5.0.45
            

If a connection is established with the datasource then a Connection Object is returned and saved into db for further use otherwise db is set to None. Next db object is used to create a cursor object which in turn is used to execute SQL queries.

Finally before coming out it ensures that database connection is closed and resources are released.

Creating Database Table:

Once a database connection is established, we are ready to create tables or records into the database tables using execute method of the created cursor.

Example:

First let's create Database table EMPLOYEE:

#!/usr/bin/python
            import MySQLdb
            # Open database connection
            db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
            # prepare a cursor object using cursor() method
            cursor = db.cursor()
            # Drop table if it already exist using execute() method.
            cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
            # Create table as per requirement
            sql = """CREATE TABLE EMPLOYEE (
            FIRST_NAME  CHAR(20) NOT NULL,
            LAST_NAME  CHAR(20),
            AGE INT,
            SEX CHAR(1),
            INCOME FLOAT )"""
            cursor.execute(sql)
            # disconnect from server
            db.close()
            

INSERT Operation:

INSERT operation is required when you want to create your records into a database table.

Example:

Following is the example which executes SQL INSERT statement to create a record into EMPLOYEE table.

#!/usr/bin/python
            import MySQLdb
            # Open database connection
            db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
            # prepare a cursor object using cursor() method
            cursor = db.cursor()
            # Prepare SQL query to INSERT a record into the database.
            sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
            LAST_NAME, AGE, SEX, INCOME)
            VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
            try:
            # Execute the SQL command
            cursor.execute(sql)
            # Commit your changes in the database
            db.commit()
            except:
            # Rollback in case there is any error
            db.rollback()
            # disconnect from server
            db.close()
            

Above example can be written as follows to create SQL queries dynamically:

#!/usr/bin/python
            import MySQLdb
            # Open database connection
            db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
            # prepare a cursor object using cursor() method
            cursor = db.cursor()
            # Prepare SQL query to INSERT a record into the database.
            sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
            LAST_NAME, AGE, SEX, INCOME) \
            VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
            ('Mac', 'Mohan', 20, 'M', 2000)
            try:
            # Execute the SQL command
            cursor.execute(sql)
            # Commit your changes in the database
            db.commit()
            except:
            # Rollback in case there is any error
            db.rollback()
            # disconnect from server
            db.close()
            

Example:

Following code segment is another form of execute where you can pass parameters directly:

..................................
            user_id = "test123"
            password = "password"
            con.execute('insert into Login values("%s", "%s")' % \
            (user_id, password))
            ..................................
            

READ Operation:

READ Operation on any databasse means to fetch some useful information from the database.

Once our database connection is established, we are ready to make a query into this database. We can use either fetchone() method to fetch single record or fetchall method to fetech multiple values from a database table.

  • fetchone(): This method fetches the next row of a query result set. A result set is an object that is returned when a cursor object is used to query a table.

  • fetchall(): This method fetches all the rows in a result set. If some rows have already been extracted from the result set, the fetchall() method retrieves the remaining rows from the result set.

  • rowcount: This is a read-only attribute and returns the number of rows that were affected by an execute() method.

Example:

Following is the procedure to query all the records from EMPLOYEE table having salary more than 1000.

#!/usr/bin/python
            import MySQLdb
            # Open database connection
            db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
            # prepare a cursor object using cursor() method
            cursor = db.cursor()
            # Prepare SQL query to INSERT a record into the database.
            sql = "SELECT * FROM EMPLOYEE \
            WHERE INCOME > '%d'" % (1000)
            try:
            # Execute the SQL command
            cursor.execute(sql)
            # Fetch all the rows in a list of lists.
            results = cursor.fetchall()
            for row in results:
            fname = row[0]
            lname = row[1]
            age = row[2]
            sex = row[3]
            income = row[4]
            # Now print fetched result
            print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
            (fname, lname, age, sex, income )
            except:
            print "Error: unable to fecth data"
            # disconnect from server
            db.close()
            

This will produce following result:

fname=Mac, lname=Mohan, age=20, sex=M, income=2000
            

Update Operation:

UPDATE Operation on any databasse means to update one or more records which are already available in the database. Following is the procedure to update all the records having SEX as 'M'. Here we will increase AGE of all the males by one year.

Example:

#!/usr/bin/python
            import MySQLdb
            # Open database connection
            db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
            # prepare a cursor object using cursor() method
            cursor = db.cursor()
            # Prepare SQL query to UPDATE required records
            sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
            WHERE SEX = '%c'" % ('M')
            try:
            # Execute the SQL command
            cursor.execute(sql)
            # Commit your changes in the database
            db.commit()
            except:
            # Rollback in case there is any error
            db.rollback()
            # disconnect from server
            db.close()
            

DELETE Operation:

DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from EMPLOYEE where AGE is more than 20.

Example:

#!/usr/bin/python
            import MySQLdb
            # Open database connection
            db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
            # prepare a cursor object using cursor() method
            cursor = db.cursor()
            # Prepare SQL query to DELETE required records
            sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
            try:
            # Execute the SQL command
            cursor.execute(sql)
            # Commit your changes in the database
            db.commit()
            except:
            # Rollback in case there is any error
            db.rollback()
            # disconnect from server
            db.close()
            

Performing Transactions:

Transactions are a mechanism that ensures data consistency. Transactions should have the following four properties:

  • Atomicity: Either a transaction completes or nothing happens at all.

  • Consistency: A transaction must start in a consistent state and leave the system is a consistent state.

  • Isolation: Intermediate results of a transaction are not visible outside the current transaction.

  • Durability: Once a transaction was committed, the effects are persistent, even after a system failure.

The Python DB API 2.0 provides two methods to either commit or rollback a transaction.

Example:

You already have seen how we have implemented transations. Here is again similar example:

# Prepare SQL query to DELETE required records
            sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
            try:
            # Execute the SQL command
            cursor.execute(sql)
            # Commit your changes in the database
            db.commit()
            except:
            # Rollback in case there is any error
            db.rollback()
            

COMMIT Operation:

Commit is the operation which gives a green signal to database to finalize the changes and after this operation no change can be reverted back.

Here is a simple example to call commit method.

    db.commit()
            

ROLLBACK Operation:

If you are not satisfied with one or more of the changes and you want to revert back those changes completely then use rollback method.

Here is a simple example to call rollback metho.

   db.rollback()
            

Disconnecting Database:

To disconnect Database connection, use close() method.

    db.close()
            

If the connection to a database is closed by the user with the close() method, any outstanding transactions are rolled back by the DB. However, instead of depending on any of DB lower level implementation details, your application would be better off calling commit or rollback explicitly.

Handling Errors:

There are many sources of errors. A few examples are a syntax error in an executed SQL statement, a connection failure, or calling the fetch method for an already canceled or finished statement handle.

The DB API defines a number of errors that must exist in each database module. The following table lists these exceptions.

Exception Description
Warning Used for non-fatal issues. Must subclass StandardError.
Error Base class for errors. Must subclass StandardError.
InterfaceError Used for errors in the database module, not the database itself. Must subclass Error.
DatabaseError Used for errors in the database. Must subclass Error.
DataError Subclass of DatabaseError that refers to errors in the data.
OperationalError Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.
IntegrityError Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.
InternalError Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.
ProgrammingError Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.
NotSupportedError Subclass of DatabaseError that refers to trying to call unsupported functionality.

Your Python scripts should handle these errors but before using any of the above exceptions, make sure your MySQLdb has support for that exception. You can get more information about them by reading the DB API 2.0 specification.



]]>
python 中文qhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345722.html草原上的骆驼草原上的骆驼Fri, 04 Mar 2011 08:07:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345722.htmlhttp://www.aygfsteel.com/nkjava/comments/345722.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345722.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/345722.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/345722.html

]]>
Python 正则表达?/title><link>http://www.aygfsteel.com/nkjava/archive/2011/03/04/345721.html</link><dc:creator>草原上的骆驼</dc:creator><author>草原上的骆驼</author><pubDate>Fri, 04 Mar 2011 08:06:00 GMT</pubDate><guid>http://www.aygfsteel.com/nkjava/archive/2011/03/04/345721.html</guid><wfw:comment>http://www.aygfsteel.com/nkjava/comments/345721.html</wfw:comment><comments>http://www.aygfsteel.com/nkjava/archive/2011/03/04/345721.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/nkjava/comments/commentRss/345721.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/nkjava/services/trackbacks/345721.html</trackback:ping><description><![CDATA[     摘要: http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html 1. 正则表达式基 1.1. 单介l?正则表达式ƈ不是Python的一部分。正则表辑ּ是用于处理字W串的强大工P拥有自己独特的语法以及一个独立的处理引擎Q效率上可能不如str自带的方法,但功能十分强大。得益于q一点,在提供了正则表达式的语言里,正则表达式的语法都是一?..  <a href='http://www.aygfsteel.com/nkjava/archive/2011/03/04/345721.html'>阅读全文</a><img src ="http://www.aygfsteel.com/nkjava/aggbug/345721.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/nkjava/" target="_blank">草原上的骆驼</a> 2011-03-04 16:06 <a href="http://www.aygfsteel.com/nkjava/archive/2011/03/04/345721.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Python Beautiful Souphttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345720.html草原上的骆驼草原上的骆驼Fri, 04 Mar 2011 08:05:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345720.htmlhttp://www.aygfsteel.com/nkjava/comments/345720.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345720.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/345720.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/345720.htmlBeautiful Soup 中文文档 http://www.crummy.com/software/BeautifulSoup/documentation.zh.html#Using%20tag%20names%20as%20members

http://www.meegoq.com/forum.php?mod=viewthread&tid=63&extra=

http://edu.codepub.com/2010/0208/20340.php

http://www.crummy.com/software/BeautifulSoup/documentation.zh.html

]]>
Python UUIDhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345718.html草原上的骆驼草原上的骆驼Fri, 04 Mar 2011 08:03:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345718.htmlhttp://www.aygfsteel.com/nkjava/comments/345718.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345718.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/345718.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/345718.htmlUUID objects (universally unique identifiers) according to RFC 4122.
UUID objects (universally unique identifiers) according to RFC 
4122.
 
This module provides immutable UUID objects (
class UUID) and the functions
uuid1(), uuid3(), uuid4(), uuid5() 
for generating version 134and 5
UUIDs as specified 
in RFC 4122.
 
If all you want 
is a unique ID, you should probably call uuid1() or uuid4().
Note that uuid1() may compromise privacy since it creates a UUID containing
the computer
's network address.  uuid4() creates a random UUID.
 
Typical usage:
 
    
>>> import uuid
 
    
# make a UUID based on the host ID and current time
    >>> uuid.uuid1()
    UUID(
'a8098c1a-f86e-11da-bd1a-00112444be1e')
 
    
# make a UUID using an MD5 hash of a namespace UUID and a name
    >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
    UUID(
'6fa459ea-ee8a-3ca4-894e-db77e160355e')
 
    
# make a random UUID
    >>> uuid.uuid4()
    UUID(
'16fd2706-8baf-433b-82eb-8c7fada847da')
 
    
# make a UUID using a SHA-1 hash of a namespace UUID and a name
    >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
    UUID(
'886313e1-3b8a-5372-9b90-0c9aee199e5d')
 
    
# make a UUID from a string of hex digits (braces and hyphens ignored)
    >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')
 
    
# convert a UUID to a string of hex digits in standard form
    >>> str(x)
    
'00010203-0405-0607-0809-0a0b0c0d0e0f'
 
    
# get the raw 16 bytes of the UUID
    >>> x.bytes
    
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t \x0b\x0c \x0e\x0f'
 
    
# make a UUID from a 16-byte string
    >>> uuid.UUID(bytes=x.bytes)
    UUID(
'00010203-0405-0607-0809-0a0b0c0d0e0f')
 
This module works with Python 
2.3 or higher.


]]>Python Urllib2http://www.aygfsteel.com/nkjava/archive/2011/03/04/345717.html草原上的骆驼草原上的骆驼Fri, 04 Mar 2011 08:02:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345717.htmlhttp://www.aygfsteel.com/nkjava/comments/345717.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345717.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/345717.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/345717.html
http://docs.python.org/library/urllib.html


讄时旉

     import socket

import urllib2

socket.setdefaulttimeout(seconds)

open = urllib2.urlopen("

qsocket.setdefaulttimeout() 讄了全局默认时旉Q从而给urllibe2.urlopen()也设|了默认的超时时?br />




抓取囄(q个例子里的Request找不刎ͼ我一般只有urllib2)
soup=urlllib2.open(url)

# Let's create a function that downloads a file, and saves it locally.
#
 This function accepts a file name, a read/write mode(binary or text),
#
 and the base url.

def stealStuff(file_name,file_mode,base_url):
    
from urllib2 import Request, urlopen, URLError, HTTPError

    
#create the url and the request
    url = base_url + file_name
    req 
= Request(url)

    
# Open the url
    try:
        f 
= urlopen(req)
        
print "downloading " + url

        
# Open our local file for writing
        local_file = open(file_name, "w" + file_mode)
        
#Write to our local file
        local_file.write(f.read())
        local_file.close()

    
#handle errors
    except HTTPError, e:
        
print "HTTP Error:",e.code , url
    
except URLError, e:
        
print "URL Error:",e.reason , url

# Set the range of images to 1-50.It says 51 because the
#
 range function never gets to the endpoint.
image_range = range(1,51)

# Iterate over image range
for index in image_range:

    base_url 
= 'http://www.techniqal.com/'
    
#create file name based on known pattern
    file_name =  str(index) + ".jpg"
    
# Now download the image. If these were text files,
    # or other ascii types, just pass an empty string
    # for the second param ala stealStuff(file_name,'',base_url)
    stealStuff(file_name,"b",base_url)


]]>
Python Stringhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345716.html草原上的骆驼草原上的骆驼Fri, 04 Mar 2011 07:52:00 GMThttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345716.htmlhttp://www.aygfsteel.com/nkjava/comments/345716.htmlhttp://www.aygfsteel.com/nkjava/archive/2011/03/04/345716.html#Feedback0http://www.aygfsteel.com/nkjava/comments/commentRss/345716.htmlhttp://www.aygfsteel.com/nkjava/services/trackbacks/345716.htmlPython-String-Function

字符串中字符大小写的变换Q?/strong>

    * S.lower()   #写
    * S.upper()   #大写
    * S.swapcase()   #大小写互?br />     * S.capitalize()   #首字母大?br />     * String.capwords(S) 
      #q是模块中的Ҏ。它把S用split()函数分开Q然后用capitalize()把首字母变成大写Q最后用join()合ƈC?br />     * S.title()    #只有首字母大写,其余为小写,模块中没有这个方?

字符串在输出时的寚wQ?

    * S.ljust(width,[fillchar]) 
      #输出width个字W,S左对齐,不部分用fillchar填充Q默认的为空根{?br />     * S.rjust(width,[fillchar])    #叛_?br />     * S.center(width, [fillchar])    #中间寚w
    * S.zfill(width)   #把S变成width长,q在叛_齐,不部分?补

字符串中的搜索和替换Q?/strong>

    * S.find(substr, [start, [end]]) 
      #q回S中出现substr的第一个字母的标号Q如果S中没有substr则返?1。start和end作用q当于在S[start:end]中搜?br />     * S.index(substr, [start, [end]]) 
      #与find()相同Q只是在S中没有substrӞ会返回一个运行时错误
    * S.rfind(substr, [start, [end]]) 
      #q回S中最后出现的substr的第一个字母的标号Q如果S中没有substr则返?1Q也是说从双v的第一ơ出现的substr的首字母标号
    * S.rindex(substr, [start, [end]])
    * S.count(substr, [start, [end]])    #计算substr在S中出现的ơ数
    * S.replace(oldstr, newstr, [count])  
      #把S中的oldstar替换为newstrQcount为替换次数。这是替换的通用形式Q还有一些函数进行特D字W的替换
    * S.strip([chars])
      #把S中前后chars中有的字W全部去掉,可以理解为把S前后chars替换为None
    * S.lstrip([chars])
    * S.rstrip([chars])
    * S.expandtabs([tabsize]) 
      #把S中的tab字符替换没空|每个tab替换为tabsize个空|默认??

字符串的分割和组合:

    * S.split([sep, [maxsplit]])
      #以sep为分隔符Q把S分成一个list。maxsplit表示分割的次数。默认的分割WؓI白字符
    * S.rsplit([sep, [maxsplit]])
    * S.splitlines([keepends])
      #把S按照行分割符分ؓ一个listQkeepends是一个bool|如果为真每行后而会保留行分割符?br />     * S.join(seq) #把seq代表的序列──字符串序列,用Sq接h

字符串的mappingQ这一功能包含两个函数Q?/strong>

    * String.maketrans(from, to)
      #q回一?56个字W组成的译表,其中from中的字符被一一对应地{换成toQ所以from和to必须是等长的?br />     * S.translate(table[,deletechars])
      #使用上面的函C后的译表,把Sq行译Qƈ把deletechars中有的字W删掉。需要注意的是,如果S为unicode字符Ԍ那么׃支持 deletechars参数Q可以用把某个字符译为None的方式实现相同的功能。此外还可以使用codecs模块的功能来创徏更加功能强大的翻译表?

字符串还有一对编码和解码的函敎ͼ

    * S.encode([encoding,[errors]])
      #其中encoding可以有多U|比如gb2312 gbk gb18030 bz2 zlib big5 bzse64{都支持。errors默认gؓ"strict"Q意思是UnicodeError。可能的D?ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 和所有的通过codecs.register_error注册的倹{这一部分内容涉及codecs模块Q不是特明白
    * S.decode([encoding,[errors]])

字符串的试函数Q这一cd数在string模块中没有,q些函数q回的都是bool|

    * S.startwith(prefix[,start[,end]])
      #是否以prefix开?br />     * S.endwith(suffix[,start[,end]])
      #以suffixl尾
    * S.isalnum()
      #是否全是字母和数字,q至有一个字W?br />     * S.isalpha()  #是否全是字母Qƈ臛_有一个字W?br />     * S.isdigit()  #是否全是数字Qƈ臛_有一个字W?br />     * S.isspace() #是否全是I白字符Qƈ臛_有一个字W?br />     * S.islower() #S中的字母是否全是写
    * S.isupper() #S中的字母是否便是大写
    * S.istitle() #S是否是首字母大写?

字符串类型{换函敎ͼq几个函数只在string模块中有Q?/strong>

    * string.atoi(s[,base])
      #base默认?0Q如果ؓ0,那么s可以是012?x23q种形式的字W串Q如果是16那么s只能是0x23?X12q种形式的字W串
    * string.atol(s[,base])  #转成long
    * string.atof(s[,base])  #转成float

*******************************************************************************************************************
Python字符串在输出时的寚wQ?/p>

  1. S.ljust(width,[fillchar])   

#输出width个字W,S左对齐,不部分用fillchar填充Q默认的为空根{?/p>

  1. S.rjust(width,[fillchar]) #  

 

叛_?/p>

  1. S.center(width, [fillchar]) #  

 

中间寚w S.zfill(width) #把S变成width长,q在叛_齐,不部分?补字符串中的搜索和替换Q?/p>

  1. S.find(substr, [start, [end]])   

#q回S中出现substr的第一个字母的标号Q如果S中没有substr则返?1。start和end作用q当于在S[start:end]中搜?/p>

  1. S.index(substr, [start, [end]])   

#与find()相同Q只是在S中没有substrӞ会返回一个运行时错误

  1. S.rfind(substr, [start, [end]])   

#q回S中最后出现的substr的第一个字母的标号Q如果S中没有substr则返?1Q也是说从双v的第一ơ出现的substr的首字母标号

  1. S.rindex(substr, [start, [end]])   
  2. S.count(substr, [start, [end]]) #  

 

计算substr在S中出现的ơ数

  1. S.replace(oldstr, newstr, [count])   

#把S中的oldstar替换为newstrQcount为替换次数。这是替换的通用形式Q还有一些函数进行特D字W的替换

**************************************************************************************************



]]>
վ֩ģ壺 | | | | | | ػ| Ҷ| | ƽ| | ɽ| ߶| | | ն| | ߷| ɽ| ɽ| | | ӡ| γ| ˮ| | | | | | | | | | | | | ƽ| ޭ| | ǭ|