From: http://www.yiibai.com/python/python_mysql.html

Python标准的数据库接口的Python DB-API(包括Python操作MySQL)。大多数Python数据库接口坚持这个标准。
 
 

Python标准的数据库接口的Python DB-API。大多数Python数据库接口坚持这个标准。.

你可以选择适合您应用的数据库。Python数据库API支持范围广泛的数据库服务器:

  • GadFly
  • mSQL
  • MySQL
  • PostgreSQL
  • Microsoft SQL Server 2000
  • Informix
  • Interbase
  • Oracle
  • Sybase

下面是可用的Python数据库接口的列表:

Python Database Interfaces and APIs 

你必须下载一个单独的DB API的模块,你需要访问的每个数据库。例如,如果你需要访问Oracle数据库以及MySQL数据库,你必须下载Oracle和MySQL数据库模块.

DB API提供了与数据库的工作,尽可能使用Python的结构和语法的最低标准。这个API包括以下:

  • 导入API模块.

  • 获取与数据库的连接.

  • 发出SQL语句和存储过程.

  • 关闭连接

我们这里将仅学习使用MySQL的所有概念,所以让我们来谈谈MySQLdb模块.

什么是MySQLdb?

MySQLdb的是一个接口连接到MySQL数据库服务器从Python。它实现了Python数据库API V2.0,并建上的MySQL C API的顶端.

我怎么安装MySQLdb?

在进行之前,您确认您已经MySQLdb的机器上安装。只是在你的Python脚本键入以下命令并执行它:

#!/usr/bin/python

import MySQLdb

如果它产生以下结果,那么它意味着未安装MySQLdb模块:

Traceback (most recent call last):
File "test.py", line 3, inimport MySQLdb
ImportError: No module named MySQLdb

安装MySQLdb模块,MySQLdb的下载页面下载并进行如下,

window平台可以到http://www.codegood.com/archives/4下载:

$ gunzip MySQL-python-1.2.2.tar.gz
$ tar -xvf MySQL-python-1.2.2.tar
$ cd MySQL-python-1.2.2
$ python setup.py build
$ python setup.py install

注: 确保你有root权限来安装上述模块.

数据库连接:

连接到一个MySQL数据库之前确保以下:

  • 你已经创建了一个数据库TESTDB.

  • 你已经创建了一个EMPLOYEE表在TESTDB中.

  • EMPLOYEE表有以下几个字段: FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.

  • “testuser的”用户ID和密码“test123”设置用来访问TESTDB。

  • Python模块MySQLdb在你的机器上正确安装.

  • 你已通过MySQL的教程,了解MySQL基础

例子:

以下是连接MySQL数据库“TESTDB”例子

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method
cursor = db.cursor() # execute SQL query using execute() method.
cursor.execute("SELECT VERSION()") # Fetch a single row using fetchone() method.
data = cursor.fetchone() print "Database version : %s " % data # disconnect from server
db.close()

而在我的Linux机器运行此脚本,其产生的结果如下.

Database version : 5.0.45

如果连接建立的数据源,然后返回一个Connection对象,并保存成数据库,为进一步利用,否则DB设置为None。下一步db对象是用来创建一个游标对象,而这又是用来执行SQL查询.

最后出来之前,它确保数据库连接被关闭,资源被释放.

创建数据库表:

一旦建立一个数据库连接,我们已经准备好创建表或记录到数据库中使用表创建的游标的执行方法.

例子:

首先,让我们创建数据库表Employee:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method
cursor = db.cursor() # Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # Create table as per requirement
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )""" cursor.execute(sql) # disconnect from server
db.close()

插入操作:

INSERT操作时,需要你想创建一个数据库表记录.

例子:

以下是执行SQL INSERT语句创建一个记录到EMPLOYEE表的例子.

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method
cursor = db.cursor() # Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback() # disconnect from server
db.close()

上面的例子可以写成如下动态创建SQL查询:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method
cursor = db.cursor() # Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
LAST_NAME, AGE, SEX, INCOME) \
VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
('Mac', 'Mohan', 20, 'M', 2000)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback() # disconnect from server
db.close()

例子:

下面的代码段是另一种形式执行,在那里你可以直接传递参数:

..................................
user_id = "test123"
password = "password" con.execute('insert into Login values("%s", "%s")' % \
(user_id, password))
..................................

读取操作:

任何databasse读取运作手段从数据库中获取一些有用的信息.

我们的数据库建立连接后,我们准备进入这个数据库查询。我们可以使用fetchone()方法来获取单个记录或者fetchAll方法fetech从数据库表的多个值.

  • fetchone(): 这种方法获取查询结果集的下一行。结果集是一个对象时,将返回一个游标对象用于查询表.

  • fetchall(): 这种方法获取结果集的所有行。如果某些行已经从结果集中提取,fetchAll()方法检索结果集的其余行.

  • rowcount: 这是一个只读属性,返回受影响的行数execute()方法.

例子:

以下是程序查询雇员年薪超过1000表的所有记录.

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method
cursor = db.cursor() # Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
WHERE INCOME > '%d'" % (1000)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# Now print fetched result
print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname, lname, age, sex, income )
except:
print "Error: unable to fecth data" # disconnect from server
db.close()

这将产生以下结果:

fname=Mac, lname=Mohan, age=20, sex=M, income=2000

更新操作:

对任何数据库更新操作意味着更新已经可以在数据库中的一个或多个记录。以下是更新所有的记录为“M”SEX的过程。在这里,我们将所有男性年龄增加一年.

例子:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method
cursor = db.cursor() # Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback() # disconnect from server
db.close()

删除操作:

DELETE操作是必需的,当你想从数据库中删除一些记录。以下是程序删除雇员的所有记录,其中年龄超过20岁.

例子:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" ) # prepare a cursor object using cursor() method
cursor = db.cursor() # Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback() # disconnect from server
db.close()

执行事务:

事务是机制,以确保数据的一致性,事务应该有以下四个属性:

  • 原子性: 无论是事务结束或什么也没有发生在所有.

  • 一致性: 必须启动一个事务一致的状态和离开系统是一致的状态.

  • 隔离性: 在当前事务外,事务的中间结果是不可见的.

  • 持久性: 一旦事务提交,效果是持久的,即使系统发生故障后.

对Python DB API 2.0提供两种方法来提交或回滚事务.

例子:

你已经看到我们是如何实施事务。这是一次类似的例子:

# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()

提交操作:

提交是操作给出了一个绿色的信号数据库来完成的变化,没有变化,此操作后可以恢复.

下面是一个简单的例子,调用commit方法.

    db.commit()

回滚操作:

如果您不满意与一个或更多的变化,你想恢复这些变化完全使用rollback方法.

下面是一个简单的例子,调用rollback方法.

   db.rollback()

断开数据库:

要断开数据库连接,使用close()方法.

db.close()

如果连接到一个数据库是由用户使用close()方法关闭,任何未完成的事务都将回滚数据库。然而,您的应用程序,而不是取决于任何DB的低层次的实现细节上,将更好地调用commit或显式使用rollback.

错误处理:

有许多错误的来源。举几个例子是在执行SQL语句的语法错误,连接失败,或已经取消或完成的语句句柄调用获取方法.

DB API定义了一些错误,必须存在于每个数据库模块。下表列出了这些异常.

Exception Description
Warning Used for non-fatal issues. Must subclass StandardError.
Error Base class for errors. Must subclass StandardError.
InterfaceError Used for errors in the database module, not the database itself. Must subclass Error.
DatabaseError Used for errors in the database. Must subclass Error.
DataError Subclass of DatabaseError that refers to errors in the data.
OperationalError Subclass of DatabaseError that refers to errors such as the loss of a connection to the database. These errors are generally outside of the control of the Python scripter.
IntegrityError Subclass of DatabaseError for situations that would damage the relational integrity, such as uniqueness constraints or foreign keys.
InternalError Subclass of DatabaseError that refers to errors internal to the database module, such as a cursor no longer being active.
ProgrammingError Subclass of DatabaseError that refers to errors such as a bad table name and other things that can safely be blamed on you.
NotSupportedError Subclass of DatabaseError that refers to trying to call unsupported functionality.

你的Python脚本应该处理这些错误,但在使用上述任何例外之前,确保您的MySQLdb的支持该异常。你可以得到更多关于他们的信息,通过阅读DB API 2.0规范.

Python MySQL(MySQLdb)的更多相关文章

  1. Python安装MySQLdb并连接MySQL数据库

    当然了,前提是你已经安装了Python和MySQL.我的Python是2.6版本的. Python2.6的“Set”有点兼容性问题,自己照着改一下: http://sourceforge.net/fo ...

  2. Ubuntu安装MySQL和Python库MySQLdb步骤

    一.安装MySQL服务器和客户端 执行以下命令: sudo apt-get install mysql-server-5.6 mysql-client-5.6 sudo apt-get install ...

  3. python之MySQL MySQLdb 推荐使用姿势,解决中文乱码

    0.目录 2.setup(1) 安装步骤,可以顺带安装mysql administrator和mysql query browser(2) 安装完毕,修改 my.ini(3) 重启 mysql 服务: ...

  4. Python之路-python(mysql介绍和安装、pymysql、ORM sqlachemy)

    本节内容 1.数据库介绍 2.mysql管理 3.mysql数据类型 4.常用mysql命令 创建数据库 外键 增删改查表 5.事务 6.索引 7.python 操作mysql 8.ORM sqlac ...

  5. Python—>Mysql—>Dbvisualizer

    MySQLdb: https://pypi.python.org/pypi/MySQL-python/1.2.4 import MySQLdb 1.Download Connector/Python: ...

  6. Python Mysql 篇

    Python 操作 Mysql 模块的安装 linux: yum install MySQL-python window: http://files.cnblogs.com/files/wupeiqi ...

  7. python mysql desc

    #!/usr/bin/python import MySQLdb try: conn=MySQLdb.connect(host='localhost',user='root',passwd='your ...

  8. Python MySQL ORM QuickORM hacking

    # coding: utf-8 # # Python MySQL ORM QuickORM hacking # 说明: # 以前仅仅是知道有ORM的存在,但是对ORM这个东西内部工作原理不是很清楚, ...

  9. Python的MySQLdb模块安装,连接,操作,增删改

    1. 首先确认python的版本为2.3.4以上,如果不是需要升级python的版本     python -V   检查python版本 2. 安装mysql, 比如安装在/usr/local/my ...

随机推荐

  1. Docker 入门(Mac环境)- part 3 服务(services)

    part-3 服务(services) 简介 一个应用的规模的扩大是很常见的事情,会经常用到负载均衡这些,如要实现这些功能,我们就会用到docker中更高一层的东西-service(服务). 比如说一 ...

  2. Python3.5 执行发邮件脚本失败【惑】==>【搞定】

    Python发邮件的代码如下: 只需要填写好加粗字体,即可正常使用. from exchangelib import DELEGATE, Account, Credentials, Message, ...

  3. jetty 7.0 笔记

    codehaus  download:http://dist.codehaus.org/jetty/ 找到7.0  tar.gz 解压 拉取 Lib下jar 和  Lib--jsp下jar 代码同启动 ...

  4. java 多线程 33: 多线程组件之 Callable、Future和FutureTask

    Callable Callable和rRunnable差不多,两者都是为那些其实例可能被另一个线程执行的类而设计的,最主要的差别在于Runnable不会返回线程运算结果,Callable可以(假如线程 ...

  5. java 多线程 24 : 线程组

    线程组 可以把线程归属到某一个线程组中,线程组中可以有线程对象,也可以有线程组,组中还可以有线程,这样的组织结构有点类似于树的形式,如图所示: 线程组的作用是:可以批量管理线程或线程组对象,有效地对线 ...

  6. kylin的状态栏(启动器)改成ubuntu之前的样子

    ylin的状态栏(启动器)改成ubuntu之前的样子,ubuntu是在左边的,kylin在底部.占空间. 执行命令 gsettings set com.canonical.Unity.Launcher ...

  7. django 部署,gunicorn、virtualenv、nginx

    声明: 1.本篇文章是我边写命令边写的,请尊重我的劳动成果,转载请加上链接. 2.我既然公开写出来,是希望大家遇到问题的时候有个参考,所以,大家可以免费转载,使用该文章 3.但是,如果你要用这篇文章来 ...

  8. Android Retrofit2 网路编程

    Android里面本身有OKHttp,不过不是很好用,这里就用Retrofit2,简单好用. 首先,需要加入网络权限: <uses-permission android:name="a ...

  9. Ubuntu 12.04 LTS(64 bit) + RTL8188CU无线网卡驱动

    . . . . . 之前家里台式机上安装的是win7+CentOS双系统,但是CentOs的无线网卡驱动不知为何无论如何都安装不上,再加上这段时间一直很忙,所以一直使用着win.这几天事情忙得差不多了 ...

  10. WPF通过EventTrigger改变其他控件的值

    场景:点击TextBox后弹出Poppup 原理:使用EventTrigger后触发StoryBoard,通过StoryBoard改变其他控件的值. 参考代码: <Grid> <Gr ...