Home Backend Development Python Tutorial python网络编程学习笔记(九):数据库客户端 DB-API

python网络编程学习笔记(九):数据库客户端 DB-API

Jun 06, 2016 am 11:31 AM
python

一、DB-API概述

      python支持很多不同的数据库。由于不同的卖家服务器导致和数据库通信的网络协议各有不同。在python的早期版本中,每一种数据库都带有自己的python模块,所有这些模块以不同的方式工作,并提供不同的函数。这种方法不便于编写能够在多种数据库服务器类型中运行的代码,于是DB-API库函数产生。在DB-API中,所有连接数据库的模块即便是底层网络协议不同,也会提供一个共同的接口。这一点和JAVA中的JDBC和ODBC类似。
      DB-API下载地址:http://wiki.python.org/moin/DatabaseProgramming,目前版本是2.0,支持数据库包括IBM DB2、Firebird (and Interbase) 、Informix、Ingres、MySQL、Oracle 、PostgreSQL 、SAP DB (also known as "MaxDB") 、Microsoft SQL Server 、Sybase 等。

二、数据库连接

1、PostgreSQL

      有几个模块可以完成python与PostgreSQL的联接,这里主要介绍使用psycopg。
下载地址是:http://initd.org/psycopg/download/。如果没有PostgreSQL,可以从以下地址下载:http://www.postgresql.org/。(关于PostgreSQL的安装等更加详细的介绍,可以见http://wenku.baidu.com/view/8e32d10c6c85ec3a87c2c500.html。)连接PostgreSQL数据库:

代码如下:


import psycopg2
print "connecting to test"##test为数据库名
dbh=psycopg2.connect('dbname=test user=postgres')
print "connection successful"



2、MySQL

对于MySQL,python的接口是已知的MySQLdb或者MySQL-Python,下载地址:http://sourceforge.net/projects/mysql-python/。与PostgreSQL不同的是,MySQLdb connect()函数可以带各种参数,具体如下:

参数 说明
user 用户名,默认为当前登录用户。
passwd 用户密码,没有默认的。
db 连接的数据库名。
host 数据库主机名。
port TCP端口,默认是3306。

举例,连接test数据库:

代码如下:


import MySQLdb
print "connecting..."
dbh=MySQLdb.connect(db="test")
print "connection successful."
dbh.close()

三、简单操作(以PostgreSQL为例)

这里以PostgreSQL为例介绍创建表、查询表等操作。例子中数据库名为test,用户名为postgres,输入一个表名,向表中插入数据并进行查询。具体如下,已进行了注示:

代码如下:


import psycopg2
print "connecting to test"
dbh=psycopg2.connect('dbname=test user=postgres')
print "connection successful"
cur=dbh.cursor()#建立一个cursor对象,返回数据为字典形式
a=raw_input('table list:')#输入表名
cur.execute("CREATE TABLE %s(myid integer UNIQUE,filename varchar(255))" %a)#生成表,包含一个字段filename
b=1c='201210310540'
cur.execute("INSERT INTO %s VALUES (%d,%s)"%(a,b,c))#向表中插入记录b,c
cur.execute("SELECT * FROM %s " %a)#查询表中内容
rows=cur.fetchall()#获得结果集中的所有行
for row in rows:
    print row
dbh.commit()#以上对数据库的操作事务生效
dbh.close()

1、事务

多数数据库支持事务,事务可以将多条对数据库的改动放在一条命令中。在上面的例子中,当未曾执行commit()命令时,以上对数据库的操作均不会生效。另外还有一个函数rollback(),这个函数可以有效的放弃上一次执行commit()或者rollback()之后的改动。这个函数在发现错误,并想放弃已经发出的事务时,非常有效。对于不支持事务的数据库,改变会立刻执行,commit()什么也不做,但rollback()会报错。

2、效率

执行事件的性能很大程序上取决于不同的服务器,一般来说,在每个单独的命令后都提交是更新数据库最慢的方法,但如果一次提交很大数据又会使服务器产生buffer溢出。因此,应该合理处理提交的数量。

四、参数风格
在上面的例子中,使用了printf()一样的类型格式。但实际上,在DB-API中,不同的数据库所支持的参数风络不同,必须选择合适的方法,否则程序不会执行。下面的方法,可以知道当前所支持的类型格式。

代码如下:


>>> import psycopg2
>>> print psycopg2.paramstyle

pyformat这一结果可以看出,当前支持pyformat格式。

针对DB-API说明书,以使用频度由小变大的顺序介绍:

qmark 表示question-mark风格。指令字符串中的数据的每一位都被用一个问号替换,参数以list或tuple的形式给出。例如:INSERT INTO ch14 VALUES (?, ?)。
format 使用和printf()一样的类型格式,不支持对于指定参数Python的扩展名。它带一个list或tuple来转换。例如:INSERT INTO ch14 VALUES(%d, %s)
numeric 表示numeric风格。指令字符串中的数据的每一位都被一个后面是数字的冒号替换(数字以1开始),参数以list或tuple的形式给出。例如:INSERT INTO ch14 VALUES(:1, :2)
named 表示named风格。和numeric类似,但是在冒号后面用名称取代数字。带一个dictionary用来转换。例如:INSERT INTO ch14 VALUES(:number, :text)
pyformat 支持Python风格的参数,带dictionary用来转换。例如:INSERT INTO ch14 VALUES(%(number)d, %(text)s)。

五、重复指令
1、execute和executemany()

例子:

将下面的数据插入到test数据库中:

12 Twelve
13 Thirteen
14 Fourteen
15 Fifteen

(1)execute一条条插入

代码如下:


cur.execute("INSERT INTO test VALUES (12, 'Twelve')")
cur.execute("INSERT INTO test VALUES (13, 'Thirteen')")
cur.execute("INSERT INTO test VALUES (14, 'Fourteen')")
cur.execute("INSERT INTO test VALUES (15, 'Fifteen')")

这种方法过于低效。

(2)executemany()函数带一个指令和一列指令运行的记录。列表上的每条记录要么是一个list,要么是一个dictionary。

代码如下:


import psycopg2
print "connecting to test"
dbh=psycopg2.connect('dbname=test user=postgres')
print "connection successful"
cur=dbh.cursor()
rows = ({'num': 0, 'text': 'Zero'},
         {'num': 1, 'text': 'Item One'},
         {'num': 2, 'text': 'Item Two'},
         {'num': 3, 'text': 'Three'})
cur.executemany("INSERT INTO test VALUES (%(num)d, %(text)s)", rows)
dbh.commit()
dbh.close()

executemany()主要的缺点是,在需要执行指令前把所有的记录放在内存中。如果数据大的话,这就是一个问题,它会占有系统的所有内存资源。如果executemany()不能满足需要,那么除了execute()之外,还是有可能取得性能优化的。根据DB-API说明,当execute()被周期性调用时,数据库后端可以执行优化。但是它的第一个参数必须指向同一个对象,而不是一个含有相同值的字符串,即在内存中的同一个字符串对象。和executemany()一样,这样并不能保证优化,并且也不能期望execute()运行得比executemany()快。但是如果不能使用executemany(),这就是一个最好的选择。

六、fetchall、fetchmany、fetchone获取数据

fetchall(self):接收全部的返回结果行。

fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据。

fetchone(self):返回一条结果行。

七、获取metadata(元数据)

元数据的英文名称是“Metadata",它是“关于数据的数据”。如在上面的例子中,Metadata的结果为:

Column(name='id', type_code=23, display_size=None, internal_size=4, precision=None, scale=None, null_ok=None)
Column(name='filename', type_code=1043, display_size=None, internal_size=255, precision=None, scale=None, null_ok=None)

代码如下:


import psycopg2
print "connecting to bbstime"
dbh=psycopg2.connect('dbname=bbstime user=postgres')
print "connection successful"
cur=dbh.cursor()

cur.execute("SELECT * FROM asd")

for column in cur.description:
    print column

dbh.close()

八、计算行数
方法有两种,一种是用len(),一种是用rowcount。

代码如下:


import psycopg2
print "connecting to bbstime"
dbh=psycopg2.connect('dbname=bbstime user=postgres')
print "connection successful"
cur=dbh.cursor()
cur.execute("SELECT * FROM test")
rows=cur.fetchall()
print len(rows)#利用len来计算行数
print "rows:",cur.rowcount#利用rowcount来计算行数
dbh.close()

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles