python操作MYsql

import  pymysql

connect = pymysql.connect( #导入参数,建立连接
host = "127.0.0.1",
port = 3306,
user = "root",
password = "123456",
db = "t1",
charset = "utf8"
)
cursor = connect.cursor() #建立游标对象cursor()

def select_mysql(): #查询操作
sql = "select * from tb1"
cursor.execute(sql) #使用cursor执行查询语句
print(cursor.rowcount) #打印最近一次execute返回数据的行数
rs = cursor.fetchall()
for r in rs:
print(r)
# print(rs) # 打印游标对象剩余的所有行
# rs = cursor.fetchone()
# print(rs) #打印游标对象的首行
# rs = cursor.fetchmany(3)
# print(rs) #打印游标对象的下3行
# rs = cursor.fetchall()
# print(rs) #打印游标对象剩余的所有行

def update_delete_insert(): #执行更新,删除,插入操作
sql_insert = "insert into tb1 values(25,'Jack',7500)"
sql_update = "update tb1 set username ='zhangliangshan' where age=55"
sql_delete = "delete from tb1 where age=22"
sql_insert = "insert into tb1 values(25,'Jack',7500)"
try:
cursor.execute(sql_insert) #执行插入
cursor.execute(sql_update) #执行更新
cursor.execute(sql_delete) #执行删除

connect.commit() #操作无异常,保存
print("update ok~")
except Exception as e:
print(e) #打印异常
connect.rollback() #出现错误进行回滚

#update_delete_insert()
select_mysql()

cursor.close()
connect.close() #关闭cursor和connect 释放资源
posted @ 2019-01-07 22:36  Bambooboo  阅读(123)  评论(0编辑  收藏  举报