#
-*- encoding: gb2312 -*-
import
os, sys, string
import
MySQLdb
#
Á¬½ÓÊý¾Ý¿â
try
:
conn
=
MySQLdb.connect(host
=
'
localhost
'
,user
=
'
root
'
,passwd
=
'
xxxx
'
,db
=
'
test1
'
)
except
Exception, e:
print
e
sys.exit()
#
»ñÈ¡cursor¶ÔÏóÀ´½øÐвÙ×÷
cursor
=
conn.cursor()
#
´´½¨±í
sql
=
"
create table if not exists test1(name varchar(128) primary key, age int(4))
"
cursor.execute(sql)
#
²åÈëÊý¾Ý
sql
=
"
insert into test1(name, age) values ('%s', %d)
"
%
(
"
zhaowei
"
,
23
)
try
:
cursor.execute(sql)
except
Exception, e:
print
e
sql
=
"
insert into test1(name, age) values ('%s', %d)
"
%
(
"
ÕÅÈý
"
,
21
)
try
:
cursor.execute(sql)
except
Exception, e:
print
e
#
²åÈë¶àÌõ
sql
=
"
insert into test1(name, age) values (%s, %s)
"
val
=
((
"
ÀîËÄ
"
,
24
), (
"
ÍõÎå
"
,
25
), (
"
ºéÁù
"
,
26
))
try
:
cursor.executemany(sql, val)
except
Exception, e:
print
e
#
²éѯ³öÊý¾Ý
sql
=
"
select * from test1
"
cursor.execute(sql)
alldata
=
cursor.fetchall()
#
Èç¹ûÓÐÊý¾Ý·µ»Ø£¬¾ÍÑ»·Êä³ö, alldataÊÇÓиö¶þάµÄÁбí
if
alldata:
for
rec
in
alldata:
print
rec[0], rec[
1
]
cursor.close()
conn.close()
0.ÒýÈëMySQLdb¿â
import MySQLdb
1.ºÍÊý¾Ý¿â½¨Á¢Á¬½Ó
conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable")
ÌṩµÄconnect·½·¨ÓÃÀ´ºÍÊý¾Ý¿â½¨Á¢Á¬½Ó,½ÓÊÕÊý¸ö²ÎÊý,·µ»ØÁ¬½Ó¶ÔÏó.
±È½Ï³£ÓõIJÎÊý°üÀ¨
host:Êý¾Ý¿âÖ÷»úÃû.ĬÈÏÊÇÓñ¾µØÖ÷»ú.
user:Êý¾Ý¿âµÇ½Ãû.ĬÈÏÊǵ±Ç°Óû§.
passwd:Êý¾Ý¿âµÇ½µÄÃØÃÜ.ĬÈÏΪ¿Õ.
db:Ò