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")

python 使用pymssql连接sql server数据库(转)的更多相关文章

  1. python 使用pymssql连接sql server数据库

    python 使用pymssql连接sql server数据库   #coding=utf-8 #!/usr/bin/env python#------------------------------ ...

  2. python连接sql server数据库实现增删改查

    简述 python连接微软的sql server数据库用的第三方模块叫做pymssql(document:http://www.pymssql.org/en/stable/index.html).在官 ...

  3. NetBeans连接SQL server数据库教程

    不废话,直接开始 1.下载sqljdbc.jar 可以从微软中国官方网站下载 SQLJDBC微软中国 笔者提供一个网盘链接Sqljdbc.jar 4个压缩包视版本选择,SQL 2012 用sqljdb ...

  4. 【转】PowerShell 连接SQL Server 数据库 - ADO.NET

    转至:http://www.pstips.net/connect-sql-database.html PowerShell 通过ADO.NET连接SQL Server数据库,并执行SQL脚本.工作中整 ...

  5. JDBC连接sql server数据库及其它

    JDBC连接sql server数据库的步骤如下: 1.加载JDBC驱动程序: 在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Java虚拟机), 这通过java.lang.Class类的 ...

  6. ThinkPHP连接sql server数据库

    亲身经历,在网上找连接sql server数据库的方法,还是不好找的,大多数都是照抄一个人的,而这个人的又写的不全,呵呵,先介绍一下我连接的方法吧.如果你是用THINKPHP连接,那么最重要的就是配置 ...

  7. JDBC连接sql server数据库的详细步骤和代码

    JDBC连接sql server数据库的详细步骤和代码 JDBC连接sql server数据库的步骤如下: 1.加载JDBC驱动程序: 在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Ja ...

  8. 详解连接SQL Server数据库的方法,并使用Statement接口实现对数据库的增删改操作

    总结一下,连接SQL Server数据库需要以下几个步骤: 1. 导入驱动Jar包:sqljdbc.jar 2. 加载并注册驱动程序 3. 设置连接路径 4. 加载并注册驱动 5. 连接数据库 6. ...

  9. Windows 2008服务器环境PHP连接SQL Server数据库的配置及连接方法

    背景: PHP程序常用的数据库是Mysql数据库,但是由于实际项目需要,要求PHP网站连接SQL Server数据库查询一些必要信息.因此,本文就来给大家介绍一下如何安装及配置PHP扩展,可以实现PH ...

随机推荐

  1. Exponentiation(求高精度幂)

    Exponentiation Time Limit: 500MS   Memory Limit: 10000K Total Submissions: 175340   Accepted: 42341 ...

  2. Android的内部存储

    路径:/data/data/包名/ this.getCacheDir() = /data/data/com.example.qq/cache/ getFilesDir() = /data/data/c ...

  3. python从入门到放弃之Tensorflow(一)

    Tensorflow使用错误集锦: 错误1 : FutureWarning: Conversion of the second argument of issubdtype from ‘float’ ...

  4. linux的dos开关机命令

    常用:halt.reboot CentOS关机命令: 重启命令 reboot shutdown -r now 立刻重启 shutdown -r 10 过10分钟自动重启 shutdown -r 20: ...

  5. Linux批量处理常用方式

    批量处理思路在工作中使用的频率比较高,比如批量清理进程.批量删除文件.批量机器执行脚本等. 一.批量清理带java字样的进程 方式1:使用shell while语法. ${line}; done sh ...

  6. React Native安卓代码混淆和打包

    一上午就整了个React Native的打包,中间还遇到各种问题,这里还是记录下吧: 文档链接: http://reactnative.cn/docs/0.45/signed-apk-android. ...

  7. Redis4.0新特性 -Lazy Free

    Redis4.0新增了非常实用的lazy free特性,从根本上解决Big Key(主要指定元素较多集合类型Key)删除的风险.笔者在redis运维中也遇过几次Big Key删除带来可用性和性能故障. ...

  8. USACO 1.2 Friday the Thirteenth

    注意闰月的部分细节很多. /* ID:Starry21 LANG:C++ TASK:friday */ #include<iostream> #include<string> ...

  9. 调用存储在session属性里的东西

    将对象放在session里面 request.getSession().setAttribute("username", username); //放到会话里 永EL表达式调用 $ ...

  10. prometheus 监控elasticsearch

    1.安装: 如果有elk单独用户,切换到该用户下, wget下载,进入到es安装目录,执行 ./elasticsearch-plugin install file://$(pwd)/../../ela ...