Django+Nginx+MongoDB+Mysql+uWsgi的搭建

搭建目標以下:html

          圖:系統架構圖python

這個系統能夠提供web服務及其它查詢應用服務,我用其作一個二手房信息蒐集、處理及分發的系統,能夠經過瀏覽器訪問,也能夠經過定製的客戶端進行訪問。mysql

1、安裝篇nginx

一、下載安裝pythongit

複製代碼
# 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安裝工具,能夠方便的安裝所缺模塊github

python的包管理setuptools安裝web

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

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

# 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 安裝readlinemongodb

# sudo pip install readline

二、下載安裝Djangoshell

# 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

三、下載安裝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

若是沒有返回錯誤,則代表安裝成功。

四、下載安裝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開關,默認爲關

五、下載安裝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

2、配置篇

一、配置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;
    }
複製代碼

二、配置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
複製代碼

三、配置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

四、配置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的使用在此很少介紹。

五、配置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'。

3、啓動篇

一、啓動Django服務

啓動Django服務進程

# python manage.py runserver 0.0.0.0:8000

二、啓動mongoDB服務進程

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

三、啓動mysql服務

# /etc/init.d/mysqld start

4、實例篇

一、經過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),
)
複製代碼

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

二、使用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)
)
複製代碼

最終的結果爲:

三、將數據庫數據以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)
)
複製代碼

最終效果爲:

四、經過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)
)
複製代碼

最終結果爲

5、性能

因爲系統中有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)也對效率有必定影響。

固然,這只是把全部服務都部署在一臺服務器上,對資源的搶佔也影響了系統的效率。

6、其它介紹

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]) 

設置列輸出的緩衝值

相關文章
相關標籤/搜索