python连接数据库(以mysql为例,pymysql为python连接mysql的驱动模块)

import pymysql

# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="123456", database="test_python")

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

添加数据到数据库,sql语句就是mysql的sql语句

# 添加数据
sql = "insert into t_test(name) values('zhangsan')"
def insert(sql):
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
    except:
        # 如果发生错误则回滚
        db.rollback()
    finally:
        # 关闭数据库连接
        db.close()

查询数据

# 执行sql语句
sql = "select * from table"
cursor.execute(sql)

数据库数据进行修改的操作执行(execute)后还需要提交(commit),查询只需要执行即可获得数据(execute)

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐