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()