python使用pyodbc,freetds鏈接azure數據庫

簡介:java

微軟azure平臺推出sqldatabase paas服務。如今使用python語言鏈接azure數據庫的小demo。python

準備環境:linux

1,azure sqldatebase數據庫建立,參考http://www.windowsazure.cn/starter-guide/ sql

第三課,建立雲端的數據庫,數據庫

2,建立demo表,我是使用管理工具建立,sql語句代碼爲:ubuntu

IF NOT EXISTS (SELECT * FROM sys.objects
        WHERE object_id = OBJECT_ID(N'[dbo].[demo1]')
        AND type in (N'U'))
    BEGIN
    CREATE TABLE [dbo].[demo1](
        id [int] IDENTITY(1,1) NOT NULL,
        name varchar(30) not null
     CONSTRAINT [PK_demo] PRIMARY KEY CLUSTERED
    (
    [id] ASC
    )WITH (IGNORE_DUP_KEY = OFF)
    )
    END;
    GO

須要注意的事項爲:sqldatabase必須有一列爲聚合鍵,若是沒有,建立表會失敗,臨時表沒有該限制。windows

能夠參考http://azure.microsoft.com/en-us/documentation/articles/data-management-azure-sql-database-and-sql-server-iaas/ api

3,1臺azure linux虛擬機,我使用的ubuntu14.04 LTSide

4,1個csv文件,只包含1列中文工具


開始動手

1,安裝包python,pyodbc,unixodbc,freetds-bin

2,開始配置,

(1)配置freetds.conf,常見位置/etc/freetds,/usr/local/etc/

# server specific section
[global]
        # TDS protocol version
	tds version = 7.2
	client charset = UTF-8
	# Whether to write a TDSDUMP file for diagnostic purposes
	# (setting this to /tmp is insecure on a multi-user system)
;	dump file = /tmp/freetds.log
;	debug flags = 0xffff

	# Command and connection timeouts
;	timeout = 10
;	connect timeout = 10
	
	# If you get out-of-memory errors, it may mean that your client
	# is trying to allocate a huge buffer for a TEXT field.  
	# Try setting 'text size' to a more reasonable limit 
	text size = 64512

[azure]
	host = hostname.database.chinacloudapi.cn
	port = 1433
	tds version = 7.2

其中,tds version選擇了7.2,添加了client charset,這是爲了防止中文亂碼

(2)配置odbcinst.ini位置在/etc

[FreeTDS]
Description = FreeTDS Driver
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
UsageCount = 1

(3)配置odbc.ini位置在/etc

[azure_odbc]
Driver = FreeTDS
Servername = azure
Database = azureea

其中azure_odbc爲odbc的dsn,Servername爲freetds配置節點,Driver爲odbcinst的配置節點,Database爲azure數據庫名稱

3,開始調試,調試的python代碼爲:

#coding:utf-8
#!/usr/bin/env python
import pyodbc
import csv
from datetime import datetime
conn = pyodbc.connect('DSN=azure_odbc;UID=username@host;PWD=xxxxx;CHARSET=utf8;')
cursor = conn.cursor()
csvfile=file('name.csv','rb')
reader=csv.reader(csvfile)
for line in reader:
    print line[0]
    name=line[0]
    cursor.execute("insert into demo1(name) values (?);",name)
conn.commit()
conn.close()
csvfile.close()

到此,一個採集數據的小案例就完成了。

相關文章
相關標籤/搜索