python-操作DB

python --mysql

python3: pymysql
python2: MySQLdb

步骤:
1,  建立数据库连接对象
    db = pymysql.connect("dbaddress","username","password","dbname",charset = "utf8")
    
2, 创建游标对象
    cursor = db.cursor()
3, 使用游标对象的方法操作数据库
    cursor.execute("command;");
4, 提交commit
    db.commit();
5, 关闭游标对象
    cursor.close()
6, 关闭数据库连接
    db.close();
    
    
db连接对象支持的方法:
1, cursor() 创建游标对象
2, commit() 提交方法
3, rollback()回滚方法
4,close() 关闭连接    

cursor对象支持的方法:
1, execute("SQL命令") 执行SQL命令
2, fetchone() 取得结果集的第一条记录
3,fetchmany(n)取得结果集的n条记录        
4, fetchall()取得结果集的所有记录
5, close() 关闭游标对象

import pymysql

# python操作mysql 步骤:
# 1, 建立数据库连接
# 2, 创建游标对象
# 3, 使用游标对象的方法操作数据库
# 4, 提交commit
# 5, 关闭游标对象
# 6, 关闭数据库连接

try:
    #创建db连接对象
    db = pymysql.connect("192.168.10.16","wang","123456","wang",charset = "utf8")

    #创建游标对象
    cursor = db.cursor()

    #cursor.execute("create database wang;")

    #如果连接的时候未指定库名,则必须use db
    cursor.execute("use wang;")

    #执行语句
    # sql_create = "create table t3(id int auto_increment, name varchar(30) default '', age int default 0, score int default 0,primary key(id))engine = innodb;"
    # cursor.execute(sql_create)
    sql_insert = "insert into t3(name,age,score) values('llj',20,100),('wanghuan',18,99);"
    cursor.execute(sql_insert)

    #查询语句
    sql_query = "select * from wang.t3 limit 5;"

    #执行查询语句;执行后,结果集保存在cursor中
    cursor.execute(sql_query)


    # 将结果集赋值给变量,并打印
    data = cursor.fetchall()
    print("查询结果集为:")
    for I in data:
        print(I)

    #事物操作,必须要提交,也可以rollback()
    db.commit()

finally:
    #关闭连接
    cursor.close()
    db.close()
import pymysql

host = "192.168.10.16"
user = "wang"
password = "123456"
dbname = "wang"
ch = "utf8"

db = pymysql.connect(host, user, password, dbname, charset = ch)
cur = db.cursor()

try:
    sql_update_1 = "update t3 set age = age + 1 where name = 'llj';"
    sql_update_2 = "update t3 set age = age + 2 where name = 'wanghuan';"
    cur.execute(sql_update_1)
    cur.execute(sql_update_2)
    db.commit()

    print("execute successfully;")

except Exception as e:
    db.rollback()
    print("execute failed, command has been rollback")

cur.close()
db.close()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值