Nginx+uWsgi+Django+Python+MongoDB+mySQL服務器搭建


搭建目標如下:

          圖:系統架構圖

這個系統可以提供web服務及其它查詢應用服務,我用其做一個二手房信息搜集、處理及分發的系統,可以通過瀏覽器訪問,也可以通過定制的客戶端進行訪問。

一、安裝篇

1、下載安裝python

# wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tgz
#
# tar xvfz Python-2.7.3.tgz
# cd Python-2.7.3
#./configure
# make
# sudo make install

下面是一些python安裝工具,可以方便的安裝所缺模塊

python的包管理setuptools安裝

# wget http://peak.telecommunity.com/dist/ez_setup.py
# python ez_setup.py

python的包管理pip安裝(需要先安裝setuptools)

# wget http://python-distribute.org/distribute_setup.py
# python distribute_setup.py
# wget https://github.com/pypa/pip/raw/master/contrib/get-pip.py
# python get-pip.py

下面使用pip 安裝readline

# sudo pip install readline

2、下載安裝Django

# wget https://www.djangoproject.com/download/1.4.3/tarball/
#
# tar xvfz Django-1.4.3.tar.gz
# cd Django-1.4.3
# sudo python setup.py install

3、下載安裝MongoDB

l  先下載安裝scons

# wget http://sourceforge.net/projects/scons/files/scons/2.1.0.alpha.20101125/scons-2.1.0.alpha.20101125.tar.gz/download
#
# tar xvfz scons-2.1.0.alpha.20101125.tar.gz
# cd scons-2.1.0.alpha.20101125
# sudo python setup.py install

l  下載安裝MongoDB

# wget http://downloads.mongodb.org/src/mongodb-src-r2.2.2.tar.gz
#
# tar xvfz mongodb-src-r2.2.2.tar.gz
# cd mongodb-src-r2.2.2
# scons all
# sudo scons --prefix=/usr/local/mongodb --full install

l  下載安裝pyMongo

# wget wget http://pypi.python.org/packages/source/p/pymongo/pymongo-2.4.2.tar.gz
# 
# tar xvfz pymongo-2.4.2.tar.gz
# cd pymondo-2.4.2
# sudo python setup.py install

測試pyMongo是否安裝成功

# python
> import pymongo

如果沒有返回錯誤,則表明安裝成功。

l  下載安裝mongoengine【暫時沒有用到】

# wget http://github.com/mongoengine/mongoengine/tarball/v0.6.20 --no-check-certificate
# 
# tar xvfz v0.6.20
# cd MongoEngine-mongoengine-9cc6164
# sudo python setup.py install

測試mongoengine是否安裝成功

# python
> from mongoengine import connect

如果沒有返回錯誤,則表明安裝成功。

4、下載安裝MySQL

l  先下載安裝cmake:

# wget http://www.cmake.org/files/v2.8/cmake-2.8.8.tar.gz
#
# tar xvfz cmake-2.8.8.tar.gz
# cd cmake-2.8.8
#./configure
# make
# sudo make install

l  下載安裝mysql

# wget http://cdn.mysql.com/Downloads/MySQL-5.5/mysql-5.5.29.tar.gz
#
# tar xvfz mysql-5.5.29.tar.gz
# cd mysql-5.5.29
# cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/usr/localmysql/data/ -DMYSQL_UNIX_ADDR=/usr/localmysql/data/mysqld.sock -DWITH_INNOBASE_STORAGE_ENGINE=1 -DSYSCONFDIR=/etc -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_unicode_ci -DWITH_DEBUG=0
# make
# sudo make install

l  下載安裝mysql-python

# wget http://sourceforge.net/projects/mysql-python/files/mysql-python/1.2.3/MySQL-python-1.2.3.tar.gz
# 
# tar xvfz MySQL-python-1.2.3.tar.gz
# cd MySQL-python-1.2.3

在安裝前,需要修改site.py中mysql_config的路徑(為mysql安裝路徑下的/bin/mysql_config),

# site.py
mysql_config = /usr/local/mysql/bin/mysql_config

更改完后,可以進行編譯和安裝了

# python setup.py build
# sudo python setup.py install

通過測試import MySQLdb來判斷是否安裝成功,這里還需要將mysql安裝路徑下的lib加入到環境變量LD_LIBRARY_PATH中。

# export LD_LIBRARY_PATH=/usr/local/mysql/lib/:$LD_LIBRARY_PATH

注:cmake選項說明

選項

說明

-DCMAKE_INSTALL_PREFIX

mysql安裝的主目錄。默認為/usr/local/mysql

-DMYSQL_DATADIR

mysql數據保存的路徑自定義

-DMYSQL_UNIX_ADDR

系統Socket文件(.sock)設置基於該文件路徑進行Socket連接必要為絕對路徑

-DWITH_INNOBASE_STORAGE_ENGINE

存儲引擎設置

-DSYSCONFDIR

mysql配置文件my.cnf地址默認/etc下

-DMYSQL_TCP_PORT

數據庫服務器TCP/IP連接的監聽端口默認為3306

-DEXTRA_CHARSETS

-DDEFAULT_CHARSET

-DDEFAULT_COLLATION

數據庫編碼設置

-DENABLED_LOCAL_INFILE

默認為關閉這里開啟

-DWITH_DEBUG

DEBUG開關,默認為關

5、下載安裝uWsgi

# wget http://projects.unbit.it/downloads/uwsgi-1.2.3.tar.gz
#
# tar xvfz uwsgi-1.2.3.tar.gz
# cd uwsgi-1.2.3
# python uwsgiconfig.py --build

二、配置篇

1、配置nginx(配置nginx.conf)

server {
        listen        8080;
        server_name django;

        location / {
            root  /data/htdocs/django;
            include uwsgi_params;
            uwsgi_pass 127.0.0.1:8000;
        }

        access_log  /data/htdocs/django/access.log;
    }

2、配置uWsgi

可以將uwsgi的配置文件做成ini格式的,也可以直接在命令行進行輸入,下面給出了ini文件形式的配置

#uwsgi.ini
[uwsgi]
socket = 127.0.0.1:8000
file=/data/htdocs/django/django_uwsgi.py
pidfile = /data/htdocs/django/django_uwsgi.pid
master = true
workers = 4
daemonize = /data/htdocs/django/django_uwsgi.log

其中django.py是我們需要自己定義的,它是用來將uwsgi與django進行連接的。

#django_uwsgi.py
#!/usr/bin/python

import os, sys
from django.core.handlers.wsgi import WSGIHandler

if not os.path.dirname(__file__) in sys.path[:1]:
    sys.path.insert(0, os.path.dirname(__file__))

os.environ['DJANGO_SETTINGS_MODULE'] = 'mysites.settings'    #設置配置文件

application = WSGIHandler()                      #調用django的處理函數WSGIHandler

3、配置mySQL

在安裝完成后,創建mysql用戶,並將mysql的目錄擁有者換成mysql和mysql所屬的group,並設置數據庫的用戶名和data的路徑。

# groupadd mysql   
# useradd -g mysql mysql 
# chown mysql.mysql -R /service/mysql/
# /usr/local/mysql/scripts/mysql_install_db --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data

將配置文件拷貝到/etc/下,並重命名為my.conf

# cp /usr/local/mysql/support-files/my-medium.cnf /etc/my.cnf

4、配置Django連接MySQL

在安裝完成后,需要創建運行環境

# python manage.py startproject 

執行后,會在創建一個文件manage.py和一個目錄mysite,mysite目錄中有urls.py,__init__.py,settings.py和wsgi.py文件。我們通過修改settings.py文件中的部分配置來連接mysql數據庫。

       假設在mysql中,創建了一個數據庫test_python,並添加了一個用戶名python_user且密碼為python_user,而我們連接地址為192.168.1.2的mysql服務器,端口為3306(默認),則更改settings.py如下:

...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'test_python',                      # Or path to database file if using sqlite3.
        'USER': 'python_user',                      # Not used with sqlite3.
        'PASSWORD': 'python_user',                  # Not used with sqlite3.
        'HOST': '192.168.1.2',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '3306',                      # Set to empty string for default. Not used with sqlite3.
    }
}
...

通過django中的manage.py進行驗證

# python manage.py shell
>> from django.db import connection
>> cursor = connection.cursor()

如果成功,則表明連接數據庫成功,其余的關於django的使用在此不多介紹。

5、配置Django連接MongoDB

這里可以直接使用PyMongo模塊,也可以使用第三方的中間件mongoengine,PyMongo使用方法的介紹有很多,可以直接查看官方文檔http://api.mongodb.org/python/current/api/pymongo/connection.html

這里主要介紹mongoengine的配置方法

首先,要在settings中設置一個包含數據庫信息的別名,在連接時會用到

DATABASES = {
...
'MongoDB': {
        'ENGINE': 'django_mongodb_engine',
        'NAME':'test',
    }
}
...

其中NAME指的是database的名字。

如果你想使用 django 的 session 和 authentication 這兩個框架, 還要加入

# add session
SESSION_ENGINE = 'mongoengine.django.sessions'

# add authentication
AUTHENTICATION_BACKENDS = ('mongoengine.django.auth.MongoEngineBackend',
             )

然后就可以使用mongoengine了。

from mongoengine import *
from mysite.settings import DATABASES
conn = connect('MongoDB', ip="127.0.0.1", port=27017)

這里使用了settings中定義的別名'MongoDB'。

三、啟動篇

1、啟動Django服務

啟動Django服務進程

# python manage.py runserver 0.0.0.0:8000

2、啟動mongoDB服務進程

# /usr/local/mongodb/bin/mongod --port=27000 --dbpath=$HOME/data/ --logpath=$HOME/data/mongo.log

3、啟動mysql服務

# /etc/init.d/mysqld start

四、實例篇

1、通過django的模板和mysql數據庫中的數據,生成一個包含人名及信息表格的html頁面

首先,我們先在數據庫中建立一個表peoples,並插入三條數據

mysql> create table peoples (id int auto_increment primary key, name char(30), age int, birth date);
mysql> 
mysql> insert into peoples(name, age, birth) values('zhangsan', 30,' 1983-1-1'),('lisi', 29, '1984-1-1'), ('wangwu', 28, '1985-1-1');

然后做一個html頁面模板,名為peoples_list.html,內容如下:

<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>Peoples List</head>
<body>
<br><br>
<table border="1">
<tr>
<th>Name</th><th>Age</th><th>Birth</th>
</tr>
{% for people in peoples_list %}
<tr>
      <td>{{ people.0 }}</td>
      <td>{{ people.1 }}</td>
      <td>{{ people.2 }}</td>
</tr>
{% endfor %}
</table>
</body>
</html>

接下來是完成業務邏輯,保存在文件peoples.py中(使用了django自帶的數據庫管理模塊)

#!/bin/python

#!/bin/python2
# -*- coding: utf-8 -*- 

from django.db import connection
from django.shortcuts import render_to_response

def peoples_list(request):
    cursor = connection.cursor()
    cursor.execute('select name,age,birth from peoples')
    peoples = cursor.fetchall()
return render_to_response('peoples_list.html', {'peoples_list':peoples})

最后修改urls.py中的配置,標紅的就是修改的內容

from django.conf.urls import patterns, include, url

from peoples import peoples_list

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'peoples_list/$', peoples_list),
)

通過瀏覽器訪問對應的地址就能看到最終的結果

2、使用MySQLdb來完成上面的業務邏輯

業務邏輯保存在peoples_mysqldb.py中

#!/bin/python
# -*- coding: utf8 -*-

from django.shortcuts import render_to_response
import MySQLdb

def peoples_list_mysqldb(request):
    conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='python_user', passwd='python_user', db='test_python', charset='utf8')
    cursor = conn.cursor()
    sqlComm = "select name, age, birth from peoples"
    cursor.execute(sqlComm)
    peoples = cursor.fetchall()
    cursor.close()
    conn.close() 
return render_to_response('peoples_list.html', {'peoples_list':peoples})

修改urls.py

from django.conf.urls import patterns, include, url


#from view import current_datetimefrom peoples_mysqldb import peoples_list_mysqldb

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'peoples_list_mysqldb/$', peoples_list_mysqldb)
)

最終的結果為:

3、將數據庫數據以json形式返回

主要是業務邏輯代碼的編寫:test_json.py

# coding: utf-8
#!/bin/python

from django.utils import simplejson
from django.http import HttpResponse
from django.db import connection


def json_peoples(request):
    cursor = connection.cursor()
    cursor.execute('select name, age, birth from peoples')
    peoples = cursor.fetchall()
    i = 0
    json_peoples = {}
    names = locals()
    for people in peoples:
        tag = 'person%s' % i
        names[tag] = {'name':people[0], 'age':people[1], 'birth':str(people[2])}
        json_peoples[tag] = names[tag]
        i = ((i+1))

    json = {'person':i}
    
    json['person_info'] = json_peoples
    cursor.close()

    return HttpResponse(simplejson.dumps(json, ensure_ascii=False, sort_keys=True))

向urls中添加該對應關系

from django.conf.urls import patterns, include, url

#from view import current_datetime
from json_test import json_peoples

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'peoples_json/$', json_peoples)
)

最終效果為:

4、通過pymongo模塊訪問mongodb,將結果返回成一個頁面

模板還是使用第一個例子的,只要重新寫一個業務邏輯即可mongodb_test.py

#!/bin/python2
# -*- coding: utf-8 -*-

from django.db import connection
from django.shortcuts import render_to_response

def peoples_list(request):
    cursor = connection.cursor()
    cursor.execute('select name,age,birth from peoples')
    peoples = cursor.fetchall()
    print peoples
return render_to_response('peoples_list.html', {'peoples_list':peoples})

向urls.py中添加對應關系

from django.conf.urls import patterns, include, url

#from view import current_datetime
from mongodb_test import mongodb_peoples

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^mysite/', include('mysite.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'peoples_mongo/$', mongodb_peoples)
)

最終結果為

五、性能

由於系統中有nginx,uwsgi,django,mysql和mongodb模塊,所以分別對幾種情況下做了一下簡單的性能測試。

       測試工具使用了SuperWebBench,具體介紹可以查看http://www.oschina.net/p/superwebbench上的介紹。

       測試環境:2核Intel(R) Xeon(R) CPU E5645,4G內存,上述所有模塊在一台服務器上運行。

       采用了並發500,持續30秒的測試壓力。

測試nginx:

./superwebbench -c 500 -t 30 http://127.0.0.1:8000/

SuperWebBench - Advanced Simple Web Benchmark 0.1
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Modified By Davelv 2011-11-03

Benchmarking:GET http://127.0.0.1:8000/ (using HTTP/1.1)

500 clients, running 30 sec.

Speed=6080 pages/sec, 4998280 bytes/sec.
Requests: 182419 ok, 0 http error, 0 failed.

測試nginx+uwsgi:(將uwsgi的文件指向一個直接返回http響應的python腳本)

用於返回包含當前時間的HTML頁面的Python腳本:

# coding: utf-8
#!/usr/local/bin/python

import datetime

def application(environ, start_response):
    cur = datetime.datetime.now()
    response_body = """<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>Current Datetime</head>
<body>It is now %s</body>
</html>""" % cur
    status = '200 OK'
    response_headers = [('Content-Type', 'text/plain'), ('Content-Length', str(len(response_body)))]

    start_response(status, response_headers)
return [response_body]

結果:

./superwebbench -c 500 -t 30 http://127.0.0.1:8000/

SuperWebBench - Advanced Simple Web Benchmark 0.1
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Modified By Davelv 2011-11-03

Benchmarking:GET http://127.0.0.1:8000/ (using HTTP/1.1)

500 clients, running 30 sec.

Speed=4417 pages/sec, 1351734 bytes/sec.
Requests: 132523 ok, 0 http error, 0 failed.

測試nginx+uwsgi+mysql:

用於返回包含mysql數據的HTML頁面的Python腳本:

# coding: utf-8
#!/usr/local/bin/python

import datetime
import MySQLdb

def application(environ, start_response):
    conn = MySQLdb.connect(host='127.0.0.1', port=3306, user='python_user', passwd='python_user', db='test_python', charset='utf8')
    cursor = conn.cursor()
    sqlComm = "select name, age, birth from peoples"
    cursor.execute(sqlComm)
    peoples = cursor.fetchall()
    cursor.close()
    conn.close()
    body = "<table border=\"1\"><tr><th>Name</th><th>Age</th><th>Birth</th></tr>"
    for people in peoples:
        person = "<tr><td>%s</td><td>%s</td><td>%s</td></tr>" % (str(people[0]), str(people[1]), str(people[2]))
        body = body + person
    body = body +"</table>"
    response_body = """<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>People List</head>
<body>%s</body></html>""" % body
    
    status = '200 OK'
    print response_body
    response_headers = [('Content-Type', 'text/plain'), ('Content-Length', str(len(response_body)))]
    print response_headers
    start_response(status, response_headers)
    return [response_body]

結果

./superwebbench -c 500 -t 30 http://127.0.0.1:8000/

SuperWebBench - Advanced Simple Web Benchmark 0.1
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Modified By Davelv 2011-11-03

Benchmarking:GET http://127.0.0.1:8000/ (using HTTP/1.1)

500 clients, running 30 sec.

Speed=1078 pages/sec, 539381 bytes/sec.
Requests: 32345 ok, 13 http error, 0 failed.

測試nginx+uwsgi+django:

./superwebbench -c 500 -t 30 http://127.0.0.1:8000/time/

SuperWebBench - Advanced Simple Web Benchmark 0.1
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Modified By Davelv 2011-11-03

Benchmarking:GET http://127.0.0.1:8000/time/ (using HTTP/1.1)

500 clients, running 30 sec.

Speed=652 pages/sec, 176182 bytes/sec.
Requests: 19558 ok, 7 http error, 0 failed.

測試nginx+uwsgi+django+mysql:

./superwebbench -c 500 -t 30 http://127.0.0.1:8000/peoples_list/

SuperWebBench - Advanced Simple Web Benchmark 0.1
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Modified By Davelv 2011-11-03

Benchmarking:GET http://127.0.0.1:8000/peoples_list/ (using HTTP/1.1)

500 clients, running 30 sec.

Speed=321 pages/sec, 204044 bytes/sec.
Requests: 9615 ok, 23 http error, 0 failed.

測試nginx+uwsgi+django+mongodb:

./superwebbench -c 500 -t 30 http://127.0.0.1:8000/peoples_mongo/

SuperWebBench - Advanced Simple Web Benchmark 0.1
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.
Modified By Davelv 2011-11-03

Benchmarking:GET http://127.0.0.1:8000/peoples_mongo/ (using HTTP/1.1)

500 clients, running 30 sec.

Speed=355 pages/sec, 221449 bytes/sec.
Requests: 10648 ok, 15 http error, 0 failed.

    總結一下,可以看出nginx的處理速度極快,而uwsgi同樣也不慢,最大的瓶頸在於django,效率大概下降了70%多,而數據庫查詢(無論是mysql還是mongodb)也對效率有一定影響。

當然,這只是把所有服務都部署在一台服務器上,對資源的搶占也影響了系統的效率。

六、其它介紹

1、編碼問題

需要注意編碼問題,否則會出現亂碼或者執行錯誤。

有四個部分需要統一編碼格式(以utf8為例):

(1)    mysql數據庫的編碼設置(charset = ‘utf8’)

(2)    python文件的編碼設置(# -*- coding:utf8 -*-)

(3)    連接mysql數據庫時要加上參數charset=’utf8’

(4)    如果使用django,則需要在settings.py中添加DEFAULT_CHARSET = 'utf8'。

2Python通過MySQLdbMySQL的操作

導入MySQLdb模塊

import MySQLdb

與數據庫建立連接

conn=MySQLdb.connect([host="localhost",][port=3306,] user="root", passwd="passwd",db="database_name"[, charset=’utf8’])

其中host為mysql主機名,port為端口號,user為用戶名,passwd為密碼,db為數據庫名,charset為編碼類型

獲取游標

cursor = conn.cursor()

數據庫命令

插入命令

insertComm = ‘insert into table_name(...) values(...)’
cursor.execute(insertComm,...)

如:(注意最后要調用commit來提交這次命令)

insertComm = 'insert into peoples(name, age, birth) values(%s, %s, %s)'
param = ('zhengliu', 27, '1986-1-1')
cursor.execute(insertComm, param)
conn.commit()

更新命令

updateComm = ‘update table_name set column1=value1[,...] where column=value[,...]’
cursor.execute(updateComm)

如:(注意最后要調用commit來提交這次命令)

updateComm = "update peoples set age=%s,birth=%s where name='zhengliu'"
param = (26, '1987-1-1')
cursor.execute(updateComm, param)
conn.commit()

刪除命令

deleteComm = ‘delete from table_name where column1=value1[,...]’
cursor.execute(deleteComm)

如:(注意最后要調用commit來提交這次命令)

deleteComm = "delete from peoples where name=%s"
param=('zhengliu')
cursor.execute(deleteComm, param)
conn.commit()

查詢命令

selectComm = ‘select name, age, birth from peoples [where column1=values1,...]’
cursor.execute(selectComm)
result = cursor.fetchall()

如:

queryComm = 'select name, age, birth from peoples'
cursor.execute(queryComm)
peoples = cursor.fetchall()

提交和回滾

在對數據庫進行修改操作時,需要進行commit命令來最終提交數據庫,如果想要取消這次操作,則要在commit前先調用rollback進行回滾操作。

conn.commit()
conn.rollback()

關閉命令

關閉游標

cursor.close()

關閉連接

conn.close()

cursor游標對象屬性及方法

  屬性方法

 描述

arraysize

使用fetchmany()方法時一次取出的記錄數,默認為1

connection

創建此游標的連接(可選)

discription

返回游標的活動狀態,包括(7元素):(name,type_code, display_size,internal_size,precision,scale,null_ok) 其中name,type_code是必須的。

lastrowid

返回最后更新行的ID(可選),如果數據庫不支持,返回None

rowcount

最后一次execute()返回或影響的行數

callproc(func[,args])

調用一個存儲過程

close()

關閉游標

execute(op[,args])

執行sql語句或數據庫命令

executemany(op,args)

一次執行多條sql語句,執行的條數由arraysize給出

fetchone()

匹配結果的下一行

fetchall()

匹配所有剩余結果

fetchmany(size-cursor,arraysize)

匹配結果的下幾行

__iter__()

創建迭代對象(可選,參考next())

messages

游標執行好數據庫返回的信息列表(元組集合)

next() 

使用迭代對象得到結果的下一行

nextset()

移動到下一個結果集(如果支持的話)

rownumber

當前結果集中游標的索引(從0行開始)

setinput-size(sizes)

設置輸入最大值

setoutput-size(sizes[,col]) 

設置列輸出的緩沖值

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM