python连接数据库

1.使用pymysql可以进行数据库的相关操作

安装 :pip3 install PyMySQL

import pymysql #导入pyMySQL包

db = pymysql.connect("host","username","password","databasename",charset = "utf8") #连接数据库

cursor = db.cursor() #创建一个游标 数据库连接对象

查询语句:

select_sql = "select * from tb_union_user where mobile = '%s'"%("17878787877") #需要执行的啥sql语句

cursor.execute(select_sql)

data = cursor.rowcount  #返回条数

data1 = cursor.fetchall()  #使用数组的形式展示查询出的数据

db.close()

更新语句:

update_sql = "update user set name = '张扬' where id = '%d' " %("123456")

try:

  cursor.execute(update_sql)

  db.commit()

except:

  db.rollback()

finally:

  db.close()


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容