数据库模块封装完毕

上一篇 / 下一篇  2006-08-03 17:00:18 / 天气: 晴朗 / 心情: 高兴 / 个人分类:程序设计

   昨天晚上加上今天白天完成了图书管理系统数据库操作模块的封装。准备明天开始做GUI前端,先学先做,估计要1周。再次感叹Python果然强大。天空博客}D;R'i w+f0b)d

5w/BQ,Kf0J%Z1r0
'BW2U5u)Y0以下是我写的数据库模块
o@ FOQfD0天空博客xI8@C yEBv
天空博客?"P*J X"i)h
import MySQLdb
B#DhT$R2f,f6t)Sw0class db:天空博客 P%v7dQ'Ee!o
#构造函数,其中连接了数据库天空博客3Crk8Hf!n @(bv
def __init__(self , host , user , passwd):天空博客/U+^2z6Y&_4Wp
try:
-Hr%tpaw1|,s0print "Open the Database"天空博客 K,A)t:Y ~4`8V
self.conn = MySQLdb.connect(host , user , passwd)
"X `$Nz z M5s T0except MySQLdb.OperationalError ,error:
X*]{vA/y,EE0print "Error %d: %s" % (error[0] , error[1])天空博客"g A0g;U{
#关闭数据库天空博客w?4M Sg*`o
def db_close(self):天空博客2v-@.c;x5qE
self.conn.close()
X#? kE4w0print "close the database"
7D XQd#\7B6k DlU0
(X&x3?xp1A0#使用数据库
+E_!?+Q` E^_f0def db_use(self , name):天空博客k pFp*R%v.t
str = "use " + name天空博客([4D AK9A,j
result = self.db_execute_SQL(str)
`.o*V `6Q rrEZ EW0return result天空博客6zj ?S'I J,p7n
#查询数据库
c3}L&qO%P#Z&]0def db_select(self , name , *arg):天空博客-}n){)QH
str = "SELECT * FROM " + name + self.__str_join__(" " , arg)
-bA{ITR0result = self.db_execute_SQL(str)天空博客"h3v0}&U-f8Y8uTyv N
return result
7t7qY{s.V F b0
?BK,c'y"E0#向数据库添加数据
%gb#v LXV*s d ['Y0def db_insert(self , name , *value ):天空博客 v d/gP#w@"S
str = "INSERT INTO " + name + " VALUES (" + self.__str_join__("," , value) + ")"
w2}({U*k0J D1G0result = self.db_execute_SQL(str)天空博客v0x g^ w,^ ]
return result
`k2] c\[]| [0天空博客$I)yj#De
#删除数据库中的数据天空博客u6j } L_{N0R v S
def db_delete(self , name , ID ):天空博客9[j&K]J&mVY?
str = "DELETE FROM " + name + " WHERE id = " + ID
D"}R5U(MO$Hw3B0result = self.db_execute_SQL(str)
\'P-?MX W0return result
(Fk Oa!wf/H0#修改数据库中的记录天空博客WO&y"CyM4I1@u fL
def db_update(self , name , id , *arg):
s{&A^E0str = "UPDATE " + name + " SET " + self.__str_join__("," , arg) + " WHERE id = " + id天空博客WT"tff%AXk.V l
result = self.db_execute_SQL(str)
7UpLm!}'l5];nN0return result天空博客jXO Gb&X&A(e(B0o
#向数据库中添加表天空博客#o}5}0yiM
def db_create_table(self , name , *arg):
{7tn4Vo#n&O.K2m0str = "CREATE TABLE " + name + "(" + self.__str_join__("," , arg) + ")"
bxJ.Eo9f,^0result = self.db_execute_SQL(str)天空博客4S_"N+D0_!R6I
return result天空博客&S&F@{^~
天空博客/fe`#O7lE
#删除数据库中的表天空博客\Sz8trUG Ek;n
def db_drop_table(self , name):天空博客-C/c0|`.e R
str = "DROP TABLE " + name天空博客vV!UOyl'gT }"M
result = self.db_execute_SQL(str)天空博客8Z].Mr:D7G
return result天空博客 r/RpD[1?g?
天空博客w3xq#V[h J PK;V*L
#修改数据库中的表
+W+r7K n%K0def db_alter_table(self , name , type , arg):
ORHV{2J do0TYPE = ("ADD" , "DROP" , "RENAME")天空博客&`A]lY{6c sST
if type in TYPE:天空博客p%U]L['t
str = "ALTER TABLE " + name + " " + type + " " + arg
'w"C p6hWK(?q0result = self.db_execute_SQL(str)天空博客]AANo/{7}+i
else:
t qz"o*n+m0print "You have an error in your SQL syntax;"天空博客zE!Y g0{%^h\.KM]
return False天空博客#N9dvalyC0u
return result天空博客lr p6H] _QU7j
#察看表的结构
O7b j!~4o)i?-{)\2h0def db_describe(self , name):
Q| ~'c:d1k fq0str = "DESCRIBE " + name天空博客aD5~3}-Nm0j3A
result = self.db_execute_SQL(str)天空博客!Y!D![k0?+E
return result天空博客]*@%BnJ8_p
天空博客h#i F m[3B3Tk*U4e
#执行SQL
A eO*B N0def db_execute_SQL(self , str):
S-C&Gp{;mG0cursor = self.conn.cursor()
.lV$t R)Z ~0UJ#h Q/^3yw0try:天空博客6u7F}D [&eI%A
print str天空博客phA}.w/YH
cursor.execute(str)
EM"M4lWE0self.conn.commit()天空博客O LAF,x/O#Won
allRecords = cursor.fetchall()天空博客4[6G'eQ`0w
except MySQLdb.ProgrammingError , error:
*Q(T5rc@7B0print "You have an error in your SQL syntax;"
+`D Y{b-oo"\8_0return False
5kX R+y;NM:UA0except MySQLdb.OperationalError , error:天空博客*cX LC8V*lFh|
print "Error %d: %s" % (error[0] , error[1])天空博客4~:z1u8L Y5r
return False
0pRQ8fN/M,Yr0if allRecords == ():
L}9~v'\K _0return True天空博客 SUkQF#^(xp^
else:天空博客vLw^VY%Ju*}P
return allRecords天空博客:MY/Y]yP[3\|t(G*b9`
#用于连接SQL命令天空博客uCUm(i
def __str_join__(self , symbol , arg):
'D_o:fIe/r*`/Z0s = " "天空博客R4~;ieh"\
for i in arg:天空博客5Mso'RP5|
if s != " ":天空博客'`t-s/?KNe
s += symbol
J A R j?n0s += i天空博客 [ CFC1Ea gOs_ p
return s天空博客dv/ha5i s:w
天空博客IdV;]$jxj*XO
#用于测试的模块天空博客#ga^/C_m
if __name__=='__main__':
V'pqj s_0con = db("localhost" , "root" , "xxxxxxxxxxx")天空博客Z3x@YKbL
con.db_execute_SQL("CREATE DATABASE books")
l8N"gV%\(p0con.db_use("books")天空博客&?C \{0V(k Gx
con.db_create_table("books" , "id int" , "Title CHAR(20)" , "Author CHAR(20)")
Mp#EQz1]n(s/O0con.db_insert("books" , '3' , "'dd'" , '"LeYan"')天空博客g*RS8Z$nE1G
con.db_insert("books" , "4" , '"JanusLe"' , '"fff"')
[ ~jB%kE0print con.db_select("books")天空博客3}1nk7l n2K'S
con.db_delete("books" , "4")天空博客k S7\C-b#J:~T
print con.db_select("books")天空博客} h] Z^j
con.db_update("books" , "3" , 'Author = "NoName"')
6pSC.s'z;A0print con.db_select("books")
e3xf5eW'v0con.db_alter_table("books" , "ADD" , "tttt varchar(20)")天空博客/Du&D!]6|#_%T
print con.db_describe("books")天空博客&SE4H*r#AL3g
con.db_alter_table("books" , "DROP" , "tttt")
/H/y/[ln W#n#i@&H p0print con.db_describe("books")天空博客2^*IoF(l"z B
con.db_close()天空博客#|I@?%v

~ GYRBy?qq0天空博客M Dv*b!]2_h

OdG-I&F"vh|0天空博客.Ozg%{8d%[y2j1HM
天空博客0U8{G-M#Z{(I5R k
天空博客)}T)~ D5OP{
天空博客X Q3L6TV.j O*P$\/b

TAG: 程序设计

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2009-07-05  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 14830
  • 日志数: 134
  • 图片数: 1
  • 建立时间: 2006-05-27
  • 更新时间: 2007-05-19

RSS订阅

Open Toolbar