1.数据库连接
#!usr/bin/python
# -*- coding:UTF-8 -*-
import MySQLdb //引入API模块,用于Python链接Mysql数据库的接口
//打开数据库连接
#db=MySQLdb.connect(
host="localhost", //数据库服务器名
user="root", //用户名
passwd="789", //密码
db="mysql", //数据库名
port=3306, //端口
charset='UTF8') //
// 获取游标
cursor=db.cursor()
//使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
//使用 fetchone() 方法获取一条数据
data=cursor.fetchone()
print "Dtatbase version : %s " % data
//关闭数据库连接
db.close()
终端显示:Dtatbase version : 5.5.61-0ubuntu0.14.04.1
2.创建表:create table 表名(字段1 类型,字段2 类型,……)
创建临时表在表前面加# :create table #表名(字段1 类型,字段2 类型,……)
sql="create table student(name char(20) not null,age char(20)) "
cursor.execute(sql)
或直接
cursor.execute("create table student(name char(20) not null,age char(20)) ")
3.插入insert into 表名 (列名) values (列值)
插入、更新、删除三种操作都需要db.commit()提交到数据库
cursor.execute("insert into student (name,age) value ('wang',10)")
cursor.execute("insert into student (name,age) value ('sun',20)")
cursor.execute("insert into student (name,age) value ('li',30)")
db.commit()//提交到数据库执行
4.查询select
使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据
cursor.execute("SELECT * FROM student")
results=cursor.fetchall() //返回所有查询结果
for row in results:
print row
终端显示:
(u’wang’, u’10’)
(u’sun’, u’20’)
(u’li’, u’30’)
5.更新
updata 表名 set 列名=更新值 where 条件
cursor.execute("update student set name='hu' where name='wang'")
db.commit()
cursor.execute("select * from student")
result=cursor.fetchall()
for row in result:
print row
终端显示:
(u’hu’, u’10’) //(u’wang’, u’10’)变了
(u’sun’, u’20’)
(u’li’, u’30’)
6.删除
delete from 表名 where
cursor.execute("delete from student where name='hu'")
db.commit()
cursor.execute("select * from student")
result=cursor.fetchall()
for row in result:
print row
终端显示:
(u’sun’, u’20’)
(u’li’, u’30’)
事务应该具有4个属性:原子性、一致性、隔离性、持久性
原子性(atomicity)。一个事务是一个不可分割的工作单位,事务中包括的诸操作要么都做,要么都不做。
一致性(consistency)。事务必须是使数据库从一个一致性状态变到另一个一致性状态。一致性与原子性是密切相关的。
隔离性(isolation)。一个事务的执行不能被其他事务干扰。即一个事务内部的操作及使用的数据对并发的其他事务是隔离的,并发执行的各个事务之间不能互相干扰。
持久性(durability)。持续性也称永久性(permanence),指一个事务一旦提交,它对数据库中数据的改变就应该是永久性的。接下来的其他操作或故障不应该对其有任何影响。