python3 对mysql数据库的常见操作(查询,插入,更新,删除)简单案例

 

环境:python3.6

库:pip install pymysql

 

链接mysql数据库的常用方法↓↓↓:

import pymysql

#python3中不支持mysqldb
conn=pymysql.connect(host='数据库地址',
                     user='name',
                     passwd='****',
                     db='库名',
                     port=3306,
                     charset='utf8')

cur=conn.cursor() #光标
SQL="""sql语句"""
cur.execute(SQL)
conn.commit()#提交事务
conn.close()# 断开与数据库的链接
案例表格
id username password
10 zhangsan 12345
11 liushan 22222
12 zhaowu 35f4y5

 

查询操作↓↓↓

在tablename表中查看id=10,id=11,id=12的这些数据

sql = "select * from tablename where id in ('10','11','12')"
try:
    cur.execute(sql)  # 执行sql语句  

    results = cur.fetchall()  # 获取查询的所有记录  
    print("id", "username", "password")
    # 遍历结果  
    for row in results:
        id = row[0]
        username = row[1]
        password = row[2]
        print(id, username, password)
except Exception as e:
    raise e
finally:
    db.close()  # 关闭连接

 

插入操作↓↓↓

将两条数据插入tablename表中

sql_insert ="""insert into tablename (id,username,password) values(4,'liu','1234')(5,'zhang','2234)"""  
  
try:  
    cur.execute(sql_insert)  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close()

 

更新操作↓↓↓

将tablename表中id=10的这条数据,username更新为'liusan'

sql_update ="update tablename set username = '%s' where id = %s"%('liusan','10')  
  
try:  
    cur.execute(sql_update % ("xiongda",3))  #像sql语句传递参数  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close()

 

删除操作↓↓↓

删除tablename表中id=10 的数据

sql_delete ="delete from tablename where id = '10'"  
  
try:  
    cur.execute(sql_delete % (3))  #像sql语句传递参数  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章