要求:使用python訪問遠程服務器中的SQL Server,而且插入數據 html
環境:python2.7; windows XP;sql server 2000 python
參數(虛擬):服務器ip=1.2.3.4; 端口port=1; sql
訪問sql server的庫,知道的有pyodbc以及pymssql,可是pymssql最高版本到py2.6,因此選擇pyodbc。第一次使用python訪問數據庫,折騰了好久,主要是參數中,遠程服務器和端口的格式不知道。 數據庫
pyodbc下載地址:http://code.google.com/p/pyodbc/downloads/list windows
安裝便可使用。import pyodbc 服務器
具體使用方法能夠參考幫助文檔(GettingStarted, Wiki),這裏只記錄一下本人在使用過程當中遇到的麻煩。 python2.7
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=1.2.3.4;DATABASE=testdb;UID=me;PWD=pass')不知道,網上不少都沒有說端口怎麼處理,也不知道做爲參數的端口該怎麼寫。看到有將 「PORT=1」添加到參數字符串中的,可是個人老是沒有成功。
本身在本地安裝了Sql Server 2000,在dos下使用sqlcmd訪問遠程數據庫1.2.3.4成功,因此應該是本身的參數寫錯了。以前connect函數的參數爲 函數
'DRIVER={SQL Server};SERVER=1.2.3.4;PORT=1;DATABASE=testdb;UID=me;PWD=pass'
各類錯,錯誤編號有(17)以及(53). google
改成 spa
'DRIVER={SQL Server};SERVER=1.2.3.4,1;DATABASE=testdb;UID=me;PWD=pass'
鏈接成功。
不過本地的話,若SERVER=localhost,還沒連上,暫時沒有去實驗鏈接本地sqlServer。
def AccessSqlServer(serverName, portNumber, databaseName, userName, password, tableName, phone, content): connStr = '' connStr += 'DRIVER={SQL Server};' connStr += 'SERVER=' + serverName + ',' + portNumber + ';' connStr += 'DATABASE=' + databaseName + ';' connStr += 'UID=' + userName + ';' connStr += 'PWD=' + password try: conn = pyodbc.connect(connStr) except Exception as e: return False try: cursor=conn.cursor() except Exception as e: return False execStr = "insert into " + tableName + " (phone, content) values ({0}, '{1}') ".format(phone, content) try: cursor.execute(execStr) conn.commit() #must commit except Exception as e: return False conn.close() return True