http://www.tuicool.com/articles/yqayEv
1 import pymysql 2 conn = pymysql.connect(host='localhost', port=3306,user='root',passwd='root',db='DeliveryAddress',charset='UTF8') 3 cur = conn.cursor() 4 cur.execute("INSERT INTO `ProvinceCityCountyTown` VALUES ('3', '0', '上海')") 5 conn.commit()#这里是用conn提交的,很让人不解,为什么不用cur提交呢?害得我baidu都没找到例子, 6 cur.close() 7 conn.close()
try: #获取一个数据库连接,注意如果是UTF-8类型的,需要制定数据库 conn = pymysql.connect(host=host,user=user,passwd=passwd,db=db,port=port,charset=charset) cur = conn.cursor()#获取一个游标 cur.execute('select * from user') data=cur.fetchall() for d in data : #注意int类型需要使用str函数转义 print("ID: "+str(d[0])+' 名字: '+d[1]) cur.close() conn.close() except: print("db except")
数据库操作的API文档连接: http://legacy.python.org/dev/peps/pep-0249/