Python数据库操作

本文参考资料:点击打开链接

--------------------------------------------------------------------------创建数据库表

import MySQLdb



#打开数据库连接
db=MySQLdb.connect("localhost","root","root","tg_test")
#使用cursor()方法获取操作游标
cursor=db.cursor()
#如果数据库已经存在则使用 execute()方法删除表
cursor.execute("drop table if exists tab_dept")
#创建数据表SQL语句
sql = """create table tab_dept(
         id int(4) not null primary key auto_increment,
         dept_name char(20) not null,
         dept_address char(225) not null,
         dept_superior_id int(4),
         create_time datetime,
         create_man char(60),
         update_man char(60),
         update_time datetime,
         rac_statu int(2) not null default '1'
         
)"""
#执行SQL语句
cursor.execute(sql)
#关闭数据库连接

db.close()


附说明:

 not null                 不能为空

 primary key          主键

auto_increment    自增长

default '1'               默认值为1 


---------------------------------------------------------------查询数据

# -*- coding:utf8 -*-  
import MySQLdb


#打开数据库连接
db=MySQLdb.connect(host="localhost",user="root",passwd="root",db="tg_test",charset="utf8")
#使用cursor()方法获取操作游标
cursor=db.cursor()
#sql查询语句
sql="select * from tab_dept"
try:

#执行sql语句
    cursor.execute(sql)

#获取到查询结果集
    results=cursor.fetchall()

#循环输出
    for row in results:
        id=row[0]
        deptName=row[1]
        deptAddress=row[2]
        print"id=%s,deptName=%s,deptAddress=%s" % \
                                                (id,deptName,deptAddress)


except:
    print "Error:unable to fecth data"

#关闭数据库连接
db.close

-------------------------------------------------------------- 插入数据(修改 、删除)

# -*- coding:utf8 -*-  
import MySQLdb


#打开数据库连接
db=MySQLdb.connect(host="localhost",user="root",passwd="root",db="tg_test",charset="utf8")                   # charset="utf8"解决中文插入数据库表中乱码问题
#使用cursor()方法获取操作游标
cursor=db.cursor()
#sql 插入语句
sql =""" insert into tab_dept(dept_name,dept_address,dept_superior_id,create_time,create_man)
         values('400服务中心','南通',0,sysdate(),'sys')
"""
try:
    cursor.execute(sql)
    db.commit()     #提交数据库执行
except:
    db.rollback()           #发生异常回滚


db.close()


附:使用变量向SQL语句中传递参数

deptName = "400服务中心'"
deptAddress = "南通"

superiorId=0
createMan = "sys"


con.execute('insert into  tab_dept(dept_name,dept_address,dept_superior_id,create_time,create_man) values("%s", "%s", "%s", "%s", "%s", "%s")' % \
             (deptName,deptAddress ,superiorId,sysdate(),createMan))


----------------------------------------事务----------------------------------------------------------------

对于支持事务的数据库, 在Python数据库编程中,当游标建立之时,就自动开始了一个隐形的数据库事务。

commit()方法游标的所有更新操作,rollback()方法回滚当前游标的所有操作。每一个方法都开始了一个新的事务

事务机制可以确保数据一致性。

事务应该具有4个属性:原子性、一致性、隔离性、持久性。这四个属性通常称为ACID特性。

  • 原子性(atomicity)。一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
  • 一致性(consistency)。事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
  • 隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
  • 持久性(durability)。持续性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。

Python DB API 2.0 的事务提供了两个方法 commit 或 rollback。


例:
#sql 插入语句
sql =""" insert into tab_dept(dept_name,dept_address,dept_superior_id,create_time,create_man)
         values('400服务中心','南通',0,sysdate(),'sys')
"""
try:
    cursor.execute(sql)
    db.commit()     #提交数据库执行
except:
    db.rollback()           #发生异常回滚
#关闭数据库连接
db.close()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiegenZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值