python 操作数据库

官方文档:https://www.python.org/dev/peps/pep-0249/

1、创建connection,建立网络连接

  MySQLdb.Connect(host,port,user,passwd,db, charset)

    host:mysql服务器地址字符串

    port:mysql服务器端口号,数字

    user:连接数据库用户名

    passwd:连接数据库密码

    db:数据库名称

    charset:连接编码,一般用utf8,防止乱码

  connection对象支持方法:

    1、cursor():使用该连接创建并返回游标

    2、commit():提交当前事物

    3、rollback():回滚当前事物

    4、close():关闭连接

2、获取cursor,用来交互对象

  游标对象:用于执行查询和获取结果

  cursor支持以下方法:

    execute(op[, args]):执行一个数据库查询和命令

      execute执行一条sql语句,mysql服务器执行sql语句然后生成结果集,并返回给客户端,存储在客户端缓冲区

    fetchone():获取结果集的下一行

    fetchmany(size):获取结果集的下几行

    fetchall():获取结果集中剩下的所有行

      上面三个fetch方法,可以对结果集进行遍历。移动rownumber,返回数据

    rowcount():最近一次execute返回数据的行数或影响的行数

    close():关闭游标对象

3、执行查询,执行命令,获取数据,处理数据

4、关闭cursor,关闭connection

import MySQLdb
conn = MySQLdb.Connect(host='127.0.0.1', port=3306, user='root', passwd='1234567890', db='testdb', charset='utf8')
cursor = conn.cursor()
# 测试增删改查及事务回滚
try:
sql_insert = 'insert into test(id, username) values(7,"name7")'
sql_update = 'update test set username="name6" where id=6'
sql_delete = 'delete from test1 where id<3'  # 此处test1表不存在,所以会报错
cursor.execute(sql_insert)
cursor.execute(sql_update)
cursor.execute(sql_delete)
conn.commit()
except Exception as e:
print(e)
conn.rollback()

  cursor.close()
  conn.close()
原文地址:https://www.cnblogs.com/fiona-zhong/p/10172901.html