首页 > 代码库 > python连接数据库。

python连接数据库。

准备工作。需要安装pymssql 。。具体怎么安装请自行百度。教程很多。最简单的就是pip install myssql  但是可能会出现版本不兼容的问题。导致导入后不能improt。也可能导致打包的时候出错。

 

需要三个文件。

1.解析配置文件,连接数据库

# -*- coding: utf-8 -*-__author__ = heroimport pymssqlimport xml.dom.minidomimport osimport syscurPath = os.path.abspath(os.path.dirname(__file__))rootPath = os.path.split(curPath)[0]sys.path.append(rootPath)class ExchangeData(object):    global CONFIGTYPE_RETEST    global CONFIGTYPE_PING    global CONFIGTYPE_AGETEST    global CONFIGTYPE_IPX    CONFIGTYPE_RETEST = RETEST    CONFIGTYPE_PING = PING    CONFIGTYPE_AGETEST = AGETEST    CONFIGTYPE_IPX = IPX    ###加载数据库连接数据    def loadDBConfig(self,dbType):        xmlDoc = xml.dom.minidom.parse(os.getcwd() +\\conf\\/DBConfig.xml‘#此处路径为配置文件的路径        root = xmlDoc.documentElement        sql_element = root.getElementsByTagName(dbType)[0]        return sql_element    def __exchangeDataByDBConnection(self):        sqlInfo = self.loadDBConfig(MSSQL)        db_host = sqlInfo.getElementsByTagName(HOST)[0].firstChild.data        db_database = sqlInfo.getElementsByTagName(DATABASE)[0].firstChild.data        db_user = sqlInfo.getElementsByTagName(USERNAME)[0].firstChild.data        db_pwd = sqlInfo.getElementsByTagName(PASSWORD)[0].firstChild.data        conn = pymssql.connect(user=db_user,password=db_pwd,database=db_database,host=db_host)        conn.autocommit(True)        return conn    ###读取数据###    def getDataBySql(self,sqlStr):        try:            conn = self.__exchangeDataByDBConnection()            if not conn:                raise(NameError,数据库连接失败)            else:                cur = conn.cursor()                cur.execute(sqlStr)                resList = cur.fetchall()                conn.close()                return resList        except Exception,e:            print(e)            raise(NameError,数据库操作失败)    ###更改数据库###    def setDataBySql(self,sqlStr):        try:            conn = self.__exchangeDataByDBConnection()            if not conn:                raise(NameError,数据库连接失败)                return False            else:                cur = conn.cursor()                cur.execute(sqlStr)                conn.commit()                conn.close()                return True        except Exception,e:            print(e)            raise(NameError,数据库操作失败)            return Falseif __name__ == __main__:    pn = BYAUX-CTN0003    sqlStr = "select * from producttype where productNo = ‘"+pn+""    edata = ExchangeData()    resList = edata.getDataBySql(sqlStr=sqlStr)    for dataRow in resList:        print(dataRow[0])

 

2.进行增删改查操作,文件

  1 #coding=gbk  2   3 from exchangeData import *  4 import time  5   6 ###数据库相关操作  7 class DataBaseOP(object):  8     ###根据用户名密码,验证用户权限返回值不同,权限不同###  9     def loginApTester(self,username,password): 10         loginSql = SELECT rid FROM bdcomemployee WHERE bdcomLoginName = \‘+username+\‘ AND bdcomPassword = \‘+password+\‘ 11         loginSql = self.dbTrim(loginSql) 12         eData =http://www.mamicode.com/ ExchangeData() 13         dataRows = eData.getDataBySql(loginSql) 14         if len(dataRows)==0 or dataRows[0] is None: 15             return 0 16         elif dataRows[0][0]==17: 17             return 2 18         else: 19             return 1 20  98    127     ###修改密码###128     def resetDBPwd(self,userName,oldPwd,newPwd):129         igStatus = self.loginApTester(userName,oldPwd)130         if igStatus>0:131             setSql = UPDATE bdcomemployee SET bdcomPassword = \‘+newPwd+\‘ WHERE bdcomLoginName = \‘+userName+\‘ AND bdcomPassword = \‘+oldPwd+\‘132             self.dbTrim(setSql)133             eData =http://www.mamicode.com/ ExchangeData()134             return eData.setDataBySql(setSql)135         else:136             return False;137 138 139     155   169 170     def dbTrim(self,trimStr):171         return str(trimStr).replace(\t,‘‘).replace(\n,‘‘).replace(\r,‘‘)172 173 if __name__ == __main__:174     dbop = DataBaseOP()175     dbop.loginApTester(liuke_ap,liuke)

 

3.配置文件

 

1 <?xml version="1.0" encoding="UTF-8"?>2 <JDBC>3     <MSSQL>4         <HOST>192.168.1.1</HOST>5         <DATABASE>abcd</DATABASE>6         <USERNAME>root</USERNAME>7         <PASSWORD>root</PASSWORD>8     </MSSQL>9 </JDBC>

 

python连接数据库。