#!/usr/bin/env
python
#-*-encoding:UTF-8-*-
"""
测试MySQL的连接及操作
"""
import MySQLdb
connstring="host=localhost,port=3306,user=root,passwd=*****,db=python"
#连接字符串
try:
conn=MySQLdb.connect(connstring)
except Exception,e:
print e
break
mycursor=conn.cursor()
#获取游标,用游标操作数据库
#创建表
ctable="""CREATE TABLE test if not exists(name VARCHAR(30),uid INT(10)
primary key)"""
mycursor.execute(ctable)
#插入数据
insert1="""INSERT INTO test(name=aaa,uid=111)"""
insert2="""INSERT INTO test(name=bbb,uid=222)"""
insert3="""INSERT INTO test(name=ccc,uid=333)"""
inserts=[]
inserts[0].append(insert1)
inserts[1].append(insert2)
inserts[2].append(insert3)
for insert in inserts:
try:
mycursor.execute(insert)
except Exception,e:
print
e
#删除数据
#注释掉,下边查询要用到数据,只记录操作
#mycursor.execute("""DELETE FROM test
WHERE name=aaa""")
#多表删除
#delmany=""""DELETE FROM
table1,table2,table3 WHERE table1.uid=XXX AND
table2.uid=table3.uid"""
#mycursor.execute(delmany)
|