import pymysql,os,sys
mydb=pymysql.connect(host='localhost',user='root',password='',db='mydb',charset='utf8')
cursor=mydb.cursor()
try:
try:
data=(9,'newname','python5',34)
sql="insert into mytable values(%d,'%s','%s',%d);" % (data)
print(sql)
m=cursor.execute(sql)
##增删查改必須要做事務送出
mydb.commit()
print("成功添加條數:" + str(cursor.rowcount) +" "+str(m)) # 或用m,其中m=cursor.execute(***)
except Exception:
##出錯的話必須要事務復原
mydb.rollback()
print("寫入失敗")
print(Exception)
cursor.execute('select * from mytable order by id;')
print(cursor)
data=cursor.fetchall()
print(data)
dataone=cursor.fetchone()
print(dataone)
except Exception:
print("sql error")
finally:
print("總共資料條數是:" + str(cursor.rowcount))
cursor.close()