python 使用pymssql 连接MSSQL数据库(带端口)

本文介绍了一种在Python中连接非默认端口数据库的方法,并通过示例展示了如何使用pymssql模块执行读写操作。此外,还提供了一个具体的连接实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

知识点:如果连接数据库不使用默认端口,需要在连接host地址上加上端口

如cacelbert01.mysql.alibabalabs.com:3306

#coding=gbk

##############################################################
# Copyright (C), 2009-2010, aliyun
# FileName: dbunit.py
# Author: elbert.chenh
# Version: 0.1
# History:
# <Author/Maintainer> <Date> <Modification>
# elbert.chenh 10/07/11 Create this file
#############################################################
import sys
import ConfigParser
import datetime,time
import binascii
import os
import types
import os
import pdb
import pymssql

class DBUnit:
def __init__(self,user=None,passwd=None,host=None,database=None):
try:
self.connection = pymssql.connect(host=host, user = user, password =passwd, database=database)
self.cursor= self.connection.cursor()
except:
print "Could not connect to DB server."
exit(0)




def __del__(self):
self.cursor.close()
self.connection.close()

def read(self,Sql,param=None):
'''Exec select sql , return type is Tuple,use len fun return select row num
use param like this:
Sql=select * from table where param=%s and param1=%s
param=(value1,valuei2)
'''
try:
cursor = self.connection.cursor()
if param==None:
cursor.execute(Sql)
rs = cursor.fetchall()
cursor.close()
else:
cursor.execute(Sql,param)
rs = cursor.fetchall()
cursor.close()
except Exception,e:
print e
rs = ()
return rs

def write(self,sql,param,iscommit=True):
try:
cursor = self.connection.cursor()
print sql
n = cursor.executemany(sql,param)
if iscommit :
self.connection.commit()
return n
except Exception,e:
print e
self.connection.rollback()
return -1
def writeOneRecord(self,sql):
try:
cursor = self.connection.cursor()
n = cursor.execute(sql)
self.connection.commit()
return int(cursor.lastrowid)
except:
self.connection.rollback()
return -1



if __name__ == '__main__':
a = time.time()
db = DBUnit('accelbert08','a1234561','cacelbert01.mysql.alibabalabs.com:3306','elbert08') //不使用默认端口
rs = db.read("select count(*) from t_file")
print rs
#db.delete(dictinu)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值