python串連sql server亂碼的解決方案

來源:互聯網
上載者:User

vi /etc/freetds/freetds.conf

複製代碼 代碼如下:[global]
# TDS protocol version
tds version = 8.0
client charset = UTF-8
# A typical Microsoft server
[Server55]
host = 192.168.1.55
port = 1433
tds version = 8.0
vi /etc/odbc.ini
[DSN55]
Description=my dsn
Driver=TDS
Database=qq99
Servername=Server55

tsql -S Server55 -U qq -P 123456 -D qq99複製代碼 代碼如下:#coding=utf-8
#!/usr/bin/python
import pyodbc
cnxn = pyodbc.connect("DSN=DSN55;UID=qq;PWD=123456")
cursor = cnxn.cursor()
cursor.execute('select * from orders where username=?','qq')
a=cursor.fetchall()
print 'pyodbc',a

關閉串連:複製代碼 代碼如下:csr.close()
del csr
conn.close()

python 使用pymssql串連sql server資料庫

複製代碼 代碼如下:#coding=utf-8
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: pymssqlTest.py
# Purpose: 測試 pymssql庫,該庫到這裡下載:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
#
# Author: scott
#
# Created: 04/02/2012
#-------------------------------------------------------------------------------

import pymssql

class MSSQL:
"""
對pymssql的簡單封裝
pymssql庫,該庫到這裡下載:http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
使用該庫時,需要在Sql Server Configuration Manager裡面將TCP/IP協議開啟

用法:

"""

def __init__(self,host,user,pwd,db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db

def __GetConnect(self):
"""
得到串連資訊
返回: conn.cursor()
"""
if not self.db:
raise(NameError,"沒有設定資料庫資訊")
self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")
cur = self.conn.cursor()
if not cur:
raise(NameError,"串連資料庫失敗")
else:
return cur

def ExecQuery(self,sql):
"""
執行查詢語句
返回的是一個包含tuple的list,list的元素是記錄行,tuple的元素是每行記錄的欄位

調用樣本:
ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
resList = ms.ExecQuery("SELECT id,NickName FROM WeiBoUser")
for (id,NickName) in resList:
print str(id),NickName
"""
cur = self.__GetConnect()
cur.execute(sql)
resList = cur.fetchall()

#查詢完畢後必須關閉串連
self.conn.close()
return resList

def ExecNonQuery(self,sql):
"""
執行非查詢語句

調用樣本:
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()
"""
cur = self.__GetConnect()
cur.execute(sql)
self.conn.commit()
self.conn.close()

def main():
## ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
## #返回的是一個包含tuple的list,list的元素是記錄行,tuple的元素是每行記錄的欄位
## ms.ExecNonQuery("insert into WeiBoUser values('2','3')")

ms = MSSQL(host="localhost",user="sa",pwd="123456",db="PythonWeiboStatistics")
resList = ms.ExecQuery("SELECT id,weibocontent FROM WeiBo")
for (id,weibocontent) in resList:
print str(weibocontent).decode("utf8")

if __name__ == '__main__':
main()

注意事項:
使用pymssql進行中文操作時候可能會出現中文亂碼,我解決的方案是:
檔案頭加上 #coding=utf8
sql語句中有中文的時候進行encode
insertSql = "insert into WeiBo([UserId],[WeiBoContent],[PublishDate]) values(1,'測試','2012/2/1')".encode("utf8")
串連的時候加入charset設定資訊
pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8")

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.