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()
posted @ 2020-08-10 22:45  徐12  阅读(298)  评论(0编辑  收藏  举报