Python connection SQL server messy code solution
- 2020-04-02 09:46:35
- OfStack
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
Close the connection:
csr.close()
del csr
conn.close()
Python USES pymssql to connect to SQL server databases
#coding=utf-8
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: pymssqlTest.py
# Purpose: test pymssql Library, the library to download here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
#
# Author: scott
#
# Created: 04/02/2012
#-------------------------------------------------------------------------------
import pymssql
class MSSQL:
"""
right pymssql Simple encapsulation
pymssql Library, the library to download here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pymssql
When using the library, you need to Sql Server Configuration Manager There will be TCP/IP Agreement on
Usage:
"""
def __init__(self,host,user,pwd,db):
self.host = host
self.user = user
self.pwd = pwd
self.db = db
def __GetConnect(self):
"""
Get the connection information
return : conn.cursor()
"""
if not self.db:
raise(NameError," No database information is set ")
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," Database connection failed ")
else:
return cur
def ExecQuery(self,sql):
"""
Execute query statement
It returns a contain tuple the list . list Is the record line, tuple Is the field for each row of records
Call example:
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()
# The connection must be closed after the query is completed
self.conn.close()
return resList
def ExecNonQuery(self,sql):
"""
Execute a non-query statement
Call example:
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")
## # It returns a contain tuple the list . list Is the record line, tuple Is the field for each row of records
## 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()
Notes:
When using pymssql for Chinese operations, there may be Chinese gargoysms. My solution is:
File header plus #coding=utf8
Encode when there is Chinese in the SQL statement
InsertSql = "insert into WeiBo([UserId],[WeiBoContent],[PublishDate]) values(1,' test ','2012/2/1')".encode("utf8")
Add charset Settings when connecting
Pymssql. Connect (host = self. The host, user = self. The user and password = self. PWD, database = self. The db, charset = "utf8")