import pymysqlimport pandasfrom IPython.core.display import displaydb = pymysql.connect( host=‘localhost‘, port=3306, user=‘root‘, password=‘root‘, db=‘test‘, charset=‘utf8‘)cursor = db.cursor()sql = "select * from user"result = cursor.execute(sql)# result 接收的是总条数 是一个 int 值print(result)data = cursor.fetchone()# print(data)# fet** 系列的方法 是提取结果,不是拷贝resultSet = cursor.fetchall()print(resultSet)for i in resultSet: print(i)print(len(resultSet))print(resultSet[0])resultSet2 = cursor.fetchall()print(resultSet2)for i in range(len(resultSet)): print(i) print(resultSet[i])cursor.execute(sql)resultSet = cursor.fetchall()for a,b,c in resultSet: print(" 我的名字是{} ,编号是 {} , 这是我的密码{}".format(b,a,c))# 用表格显示df1 = pandas.read_sql(sql,db)display(df1)sqlinsert = ‘insert into user (uname,pwd)values ("牛魔王","123123")‘try: cursor.execute(sqlinsert) db.commit()except: print("insert failed") db.rollback()sqlinsert2 = ‘insert into user (uname,pwd)values (%s,%s)‘insertdata = [("孙悟空","123456"),("唐僧","123123")]try: cursor.executemany(sqlinsert2,insertdata) db.commit()except: print("insertFailed") db.rollback()sqlupdate = ‘update user set pwd=%s where name=%s‘try: cursor.execute(sqlupdate,[90000,"玉皇大帝"]) db.commit()except: print("update failed") db.rollback()db.close();
总结: