cursor = cnn.cursor() try: sql_query = 'select name,age from stu ;' cursor.execute(sql_query) for name, age in cursor: print (name, age) except mysql.connector.Error as e: print('query error!{}'.format(e)) finally: cursor.close() cnn.close()
获取全部数据
1 2 3 4 5 6 7 8
cmd = conn.cursor() # 执行一条原生的SQL语句,执行结果保存在cmd中,没有返回值 cmd.execute("select id, name, age from stu") # 可以使用fetchall(),获取所有的查询结果集,返回值为一个tuple,每一个元素是一个list res = cmd.fetchall() print(res) # [(1, 'LiMing', 20), (2, 'XiaoHua', 30), (3, 'LiLei', 10)]
cmd = conn.cursor() # 注意,在SQL中的占位符,统一写%s, 具体的类型,是在tuple中,传入的参数元素类型决定 cmd.execute("select * from stu where id=%s and name=%s", (1, 'LiMing')) res = cmd.fetchall() print(res) # [(1, 'LiMing', 20)]
# 如果占位符只有一个,则tuple中要有一个逗号,这是tuple定义需要注意的 cmd.execute("select * from stu where id=%s ", (1,)) res = cmd.fetchall() print(res) # [(1, 'LiMing', 20)]
更新、删除
1 2 3 4 5 6 7 8 9 10
# 删除 cmd.execute("delete from stu where id=%s ", (2,)) # 注意,如果是更新操作一定要执行commit,否则数据库不会更新 cmd.execute("update stu set name='lisi' where id=%s ", (1,)) conn.commit() # 如果占位符只有一个,则tuple中要有一个逗号,这是tuple定义需要注意的 cmd.execute("select * from stu where id=%s ", (1,)) res = cmd.fetchall() print(res) # [(1, 'lisi', 20)]