python连接多库_python连接数据库

# import pymysql.cursors

import pymysql

# 连接数据库

connect = pymysql.Connect(

host='host',

port=3306,

user='user',

passwd='password',

db='db',

charset='utf8'

)

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

cursor = connect.cursor();

# 使用 execute() 方法执行 SQL 查询

# cursor.execute("select * from login_v2")

# 使用 fetchone() 方法获取单条数据.

# data = cursor.fetchone()

# 或者使用下面方法获取所有数据

sql = "select * from login_v2";

# SQL 插入语句

sqlinsert = """INSERT INTO login_v2(name,password, note)VALUES ('xf', '1122', 203333)"""

# SQL 更新语句

sqlupdata = "UPDATE login_v2 SET note = 6666 WHERE name = '%c'" % (0)

# SQL 删除语句

sqldalete = "DELETE FROM login_v2 WHERE id = %s" % (0)

try:

# 执行数据库查询操作

cursor.execute(sql)

# 获取所有记录列表

results = cursor.fetchall()

for row in results:

id = row[0]

name = row[1]

password = row[2]

print("id=%s,name=%s,password=%s" % \

(id, name, password )) #打印结果

# 执行插入操作

# cursor.execute(sqlinsert)

# connect.commit()

# 执行更新操作

# cursor.execute(sqlupdata)

# connect.commit()

# 执行删除操作

# cursor.execute(sqldalete)

# connect.commit()

except Exception: # 异常处理

print("-------------数据库执行出错------------")

# 发生错误时回滚

connect.rollback()

# 关闭连接

cursor.close()

connect.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值