V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
qile1
V2EX  ›  Python

python 的 mssql 数据连接配置无法使用,大神帮看看,代码如下,提示数据库连接函数为空!只要是在读取 ini 文件就报错

  •  
  •   qile1 · 2016-10-25 19:09:04 +08:00 · 3009 次点击
    这是一个创建于 2980 天前的主题,其中的信息可能已经有所发展或是发生改变。

    -- coding:utf-8 --

    import pymssql import _mssql import time import os import ConfigParser import logging import win32api import win32con import threading import win32gui_struct import traceback import itertools import glob import uuid import decimal decimal.version uuid.ctypes.version _mssql.version try: import winxpgui as win32gui except ImportError: import win32gui from logging.handlers import RotatingFileHandler

    config = ConfigParser.ConfigParser() config.readfp(open("DEC.INI")) mainfile = os.getcwd()

    logging.basicConfig(level=logging.INFO) logging.info("读取 dec.ini 配置文件开始")

    ########数据库设置############# SQLSERVER1 =str(config.get("DATA", "SQLSERVER"))

    = '127.0.0.1'

    USER = str(config.get("DATA", "USER"))

    'sa'

    PASSWORD = str(config.get("DATA", "PASSWORD"))

    'ruimeilis6.0'

    DATABASE = str(config.get("DATA", "DATABASE"))

    SQLSERVER = SQLSERVER1 USER = 'test' PASSWORD = 'test' DATABASE = 'test' g_Conn = None

    datastr="""server="""+SQLSERVER +""", port='1433', user="""+USER+""", password="""+PASSWORD+""", database="""+DATABASE+""",charset='UTF-8'""" print datastr datastr="""host='127.0.0.1',port='1433',user='test',password='test',database='test',charset='UTF-8'""" print datastr g_Conn = None

    LoggingLevel = "INFO" LoggingLevelTxt = '设置日志级别,日志级别大小关系为: CRITICAL > ERROR > WARNING(默认) > INFO > DEBUG > NOTSET' ##time.strftime('%Y-%m-%d',time.localtime()) #################################################################################################

    定义一个 RotatingFileHandler ,最多备份 5 个日志文件,每个日志文件最大 10M

    Rthandler = RotatingFileHandler(os.path.join(mainfile, "dec1.log"), maxBytes=10 * 1024 * 1024, backupCount=3) Rthandler.setLevel(logging.INFO) # 此处级别设置无效 formatter = logging.Formatter('%(asctime)s: %(levelname)-8s %(message)s') Rthandler.setFormatter(formatter) logging.getLogger('').addHandler(Rthandler)

    ################################################################################################

    def openDB():

    global g_Conn
    print '准备打开数据库连接'
    print 'host=',SQLSERVER,"user=",USER,"password=",PASSWORD,"database=",DATABASE
    #g_Conn = pymssql.connect(host=SQLSERVER,port="1433",user=USER,password=PASSWORD,database=DATABASE,charset="UTF-8")
    #global g_Conn
    
    #pymssql.connect(host=SQLSERVER,user=USER,password=PASSWORD,database=DATABASE)
    #g_Conn = pymssql.connect(server=SQLSERVER,port='1433',user=USER,password=PASSWORD,database=DATABASE,charset="UTF-8")
    global datastr
    g_Conn = pymssql.connect(datastr)
    #g_Conn = pymssql.connect(server="127.0.0.1", port="1433", user="test", password="test", database="master",charset="UTF-8")
    #g_Conn =pymssql.connect(server=SQLSERVER,port="1433",user=USER,password=password,database=DATABASE,charset="UTF-8")
    #pymssql.connect(host=SQLSERVER,user=USER,password=PASSWORD,database=DATABASE,charset="UTF-8")
    # pymssql.connect(server="127.0.0.1",port="1433",user="test",password="test",database="master",charset="UTF-8")
    # pymssql.connect(host=SQLSERVER,user=USER,password=PASSWORD,database=DATABASE)
    

    def closeDB(): global g_Conn g_Conn.close()

    def query(sql): try: openDB() global g_Conn print "dkai" cursor = g_Conn.cursor() ret = cursor.execute(sql) rows = cursor.fetchall() return rows except: raise Exception, 'query database has wrong' finally: closeDB()

    def insert_many(sql, params): ''' 新增多条记录, params: sql:执行的 sql 语句 parmas:一个 list , listitem 为一个参数元组 ''' try: openDB() global g_Conn cursor = g_Conn.cursor() for param in params: sql_temp = sql % param cursor.execute(sql_temp) g_Conn.commit() return True except Exception, ex: print '%s:%s' % (Exception, ex) g_Conn.rollback() raise Exception, 'insert database has wrong' return False finally: closeDB()

    def insert(sql): try: openDB() global g_Conn cursor = g_Conn.cursor() cursor.execute(sql) g_Conn.commit() except: g_Conn.rollback() raise Exception, 'query database has wrong' finally:

        closeDB()
    

    SQLSYS_SEQUENCE_update = """update SYS_SEQUENCE Set NOW_VAL =NOW_VAL + 1 Where SEQ_CODE ='%s'""" SQLSYS_SEQUENCE_NOW_VAL = """SELECT NOW_VAL From SYS_SEQUENCE Where SEQ_CODE ='%s'"""

    def SYS_SEQUENCE_NOW_VAL_1(SEQ_CODE): SYS_SEQUENCE_NOW_VAL11 = insert(SQLSYS_SEQUENCE_update % (SEQ_CODE)) SYS_SEQUENCE_NOW_VAL1 = query(SQLSYS_SEQUENCE_NOW_VAL % (SEQ_CODE)) # print SQLSYS_SEQUENCE_NOW_VAL %(SEQ_CODE) while SYS_SEQUENCE_NOW_VAL1[0]: # print baa[0] NOW_VAL = SYS_SEQUENCE_NOW_VAL1[0][0][0] print NOW_VAL break; else: print "更新并获取 SYS_SEQUENCE 对应表 id 最大值错误!"

        NOW_VAL = ''
    return NOW_VAL
    

    def SYS_SEQUENCE_NOW_VAL_2(SEQ_CODE): # 更新并获取 SYS_SEQUENCE 对应表 id 最大值! SYS_SEQUENCE_NOW_VAL1 = insert(SQLSYS_SEQUENCE_NOW_VAL % (SEQ_CODE)) print SQLSYS_SEQUENCE_NOW_VAL % (SEQ_CODE) while SYS_SEQUENCE_NOW_VAL1[0]: # print baa[0] NOW_VAL = SYS_SEQUENCE_NOW_VAL1[0][0][0] print NOW_VAL break; else: print "更新并获取 SYS_SEQUENCE 对应表 id 最大值错误!"

        NOW_VAL = ''
    return NOW_VAL
    

    def plus(a, b): z = a + 1 c = b + 5 print a + b return c, z

    --- and instrserial='%s'

    sql_insert = """INSERT INTO Size (Size_nbr,SizeName) VALUES (37,'3 风 dsf 扇地方')""";

    sql1 = "select * from Size";

    import logging.config

    def teststrRead(text): # logging.INFO() # logging.info(sqlOtheRpt %(instrid,instrno)) logging.info("开始连接数据库。。。。。。") print sql, (text) a = query(sql % (text)) print a # b = insert(sql_insert) # print ("tbale1:%s,"%(str(a[0]))) # print sql % (str(INSTR_ID),destinstr) return a

    file_object = open(fpath, 'r')

    print "usesysdate::",usesysdate

    def runReadFile(a): pass

    ###############################

    class SysTrayIcon(object): '''TODO''' QUIT = '退出解码' SPECIAL_ACTIONS = [QUIT]

    FIRST_ID = 1023
    
    def __init__(self,
                 icon,
                 hover_text,
                 menu_options,
                 on_quit=None,
                 default_menu_index=None,
                 window_class_name=None, ):
    
        self.icon = icon
        self.hover_text = hover_text
        self.on_quit = on_quit
    
        menu_options = menu_options + (('退出', None, self.QUIT),)
        self._next_action_id = self.FIRST_ID
        self.menu_actions_by_id = set()
        self.menu_options = self._add_ids_to_menu_options(list(menu_options))
        self.menu_actions_by_id = dict(self.menu_actions_by_id)
        del self._next_action_id
    
        self.default_menu_index = (default_menu_index or 0)
        self.window_class_name = window_class_name or "dec-1800i"
    
        message_map = {win32gui.RegisterWindowMessage("TaskbarCreated"): self.restart,
                       win32con.WM_DESTROY: self.destroy,
                       win32con.WM_COMMAND: self.command,
                       win32con.WM_USER + 20: self.notify,}
        # Register the Window class.
        window_class = win32gui.WNDCLASS()
        hinst = window_class.hInstance = win32gui.GetModuleHandle(None)
        window_class.lpszClassName = self.window_class_name
        window_class.style = win32con.CS_VREDRAW | win32con.CS_HREDRAW;
        window_class.hCursor = win32gui.LoadCursor(0, win32con.IDC_ARROW)
        window_class.hbrBackground = win32con.COLOR_WINDOW
        window_class.lpfnWndProc = message_map  # could also specify a wndproc.
        classAtom = win32gui.RegisterClass(window_class)
        # Create the Window.
        style = win32con.WS_OVERLAPPED | win32con.WS_SYSMENU
        self.hwnd = win32gui.CreateWindow(classAtom,
                                          self.window_class_name,
                                          style,
                                          0,
                                          0,
                                          win32con.CW_USEDEFAULT,
                                          win32con.CW_USEDEFAULT,
                                          0,
                                          0,
                                          hinst,
                                          None)
        win32gui.UpdateWindow(self.hwnd)
        self.notify_id = None
        self.refresh_icon()
    
        win32gui.PumpMessages()
    
    def _add_ids_to_menu_options(self, menu_options):
        result = []
        for menu_option in menu_options:
            option_text, option_icon, option_action = menu_option
            if callable(option_action) or option_action in self.SPECIAL_ACTIONS:
                self.menu_actions_by_id.add((self._next_action_id, option_action))
                result.append(menu_option + (self._next_action_id,))
            elif non_string_iterable(option_action):
                result.append((option_text,
                               option_icon,
                               self._add_ids_to_menu_options(option_action),
                               self._next_action_id))
            else:
                print 'Unknown item', option_text, option_icon, option_action
            self._next_action_id += 1
        return result
    
    def refresh_icon(self):
        # Try and find a custom icon
        hinst = win32gui.GetModuleHandle(None)
        if os.path.isfile(self.icon):
            icon_flags = win32con.LR_LOADFROMFILE | win32con.LR_DEFAULTSIZE
            hicon = win32gui.LoadImage(hinst,
                                       self.icon,
                                       win32con.IMAGE_ICON,
                                       0,
                                       0,
                                       icon_flags)
        else:
            print "Can't find icon file - using default."
            hicon = win32gui.LoadIcon(0, win32con.IDI_APPLICATION)
    
        if self.notify_id:
            message = win32gui.NIM_MODIFY
        else:
            message = win32gui.NIM_ADD
        self.notify_id = (self.hwnd,
                          0,
                          win32gui.NIF_ICON | win32gui.NIF_MESSAGE | win32gui.NIF_TIP,
                          win32con.WM_USER + 20,
                          hicon,
                          self.hover_text)
        win32gui.Shell_NotifyIcon(message, self.notify_id)
    
    def restart(self, hwnd, msg, wparam, lparam):
        self.refresh_icon()
    
    def destroy(self, hwnd, msg, wparam, lparam):
        if self.on_quit: self.on_quit(self)
        nid = (self.hwnd, 0)
        win32gui.Shell_NotifyIcon(win32gui.NIM_DELETE, nid)
        win32gui.PostQuitMessage(0)  # Terminate the app.
    
    def notify(self, hwnd, msg, wparam, lparam):
        if lparam == win32con.WM_LBUTTONDBLCLK:
            self.execute_menu_option(self.default_menu_index + self.FIRST_ID)
        elif lparam == win32con.WM_RBUTTONUP:
            self.show_menu()
        elif lparam == win32con.WM_LBUTTONUP:
            pass
        return True
    
    def show_menu(self):
    
        menu = win32gui.CreatePopupMenu()
        self.create_menu(menu, self.menu_options)
        # win32gui.SetMenuDefaultItem(menu, 1000, 0)
    
        pos = win32gui.GetCursorPos()
        # See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/menus_0hdi.asp
        win32gui.SetForegroundWindow(self.hwnd)
        win32gui.TrackPopupMenu(menu,
                                win32con.TPM_LEFTALIGN,
                                pos[0],
                                pos[1],
                                0,
                                self.hwnd,
                                None)
        win32gui.PostMessage(self.hwnd, win32con.WM_NULL, 0, 0)
    
    def create_menu(self, menu, menu_options):
        for option_text, option_icon, option_action, option_id in menu_options[::-1]:
            if option_icon:
                option_icon = self.prep_menu_icon(option_icon)
    
            if option_id in self.menu_actions_by_id:
                item, extras = win32gui_struct.PackMENUITEMINFO(text=option_text,
                                                                hbmpItem=option_icon,
                                                                wID=option_id)
                win32gui.InsertMenuItem(menu, 0, 1, item)
            else:
                submenu = win32gui.CreatePopupMenu()
                self.create_menu(submenu, option_action)
                item, extras = win32gui_struct.PackMENUITEMINFO(text=option_text,
                                                                hbmpItem=option_icon,
                                                                hSubMenu=submenu)
                win32gui.InsertMenuItem(menu, 0, 1, item)
    
    def prep_menu_icon(self, icon):
        # First load the icon.
        ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON)
        ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON)
        hicon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, ico_x, ico_y, win32con.LR_LOADFROMFILE)
    
        hdcBitmap = win32gui.CreateCompatibleDC(0)
        hdcScreen = win32gui.GetDC(0)
        hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y)
        hbmOld = win32gui.SelectObject(hdcBitmap, hbm)
        # Fill the background.
        brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU)
        win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush)
        # unclear if brush needs to be feed.  Best clue I can find is:
        # "GetSysColorBrush returns a cached brush instead of allocating a new
        # one." - implies no DeleteObject
        # draw the icon
        win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL)
        win32gui.SelectObject(hdcBitmap, hbmOld)
        win32gui.DeleteDC(hdcBitmap)
    
        return hbm
    
    def command(self, hwnd, msg, wparam, lparam):
        id = win32gui.LOWORD(wparam)
        self.execute_menu_option(id)
    
    def execute_menu_option(self, id):
        menu_action = self.menu_actions_by_id[id]
        if menu_action == self.QUIT:
            win32gui.DestroyWindow(self.hwnd)
        else:
            menu_action(self)
    

    def non_string_iterable(obj): try: iter(obj) except TypeError: return False else: return not isinstance(obj, basestring)

    Minimal self test. You'll need a bunch of ICO files in the current working

    directory in order for this to work...

    icons = itertools.cycle(glob.glob('*.ico')) #icons=(os.path.join(mainfile, "DEC.ico"),os.path.join(mainfile, "DEC2.ico")) hover_text = "com1 9600 n 8 1 \n load: "

    def hello(sysTrayIcon): print "Hello World."

    def simon(sysTrayIcon): print "Hello Simon."

    def rehandle(sysTrayIcon): print "rehandling......" global file_tell file_tell = 0

    def switch_icon(sysTrayIcon): sysTrayIcon.icon = icons.next() sysTrayIcon.refresh_icon()

    def stop(sysTrayIcon): t.stop() menu_options = (('打印状态', icons.next(), hello), ('停止处理', icons.next(), simon), ('切换图标', None, switch_icon), ('重新处理今日数据', icons.next(), rehandle), ('其他设置', icons.next(), (('设置 1', icons.next(), simon), (hover_text, icons.next(), switch_icon), )) )

    def bye(sysTrayIcon): print '退出.已停止'

    """ on_quit=bye default_menu_index=1

    t=threading.Thread(target=SysTrayIcon,args=(icons.next(), hover_text, menu_options,on_quit, default_menu_index))

    #将线程设置为守护线程 t.setDaemon(True) #线程准备就绪,随时等候 cpu 调度 t.start()

    创建锁

    #mutex = threading.Lock() t=threading.Thread(target=runReadFile,args=(1,)) #将线程设置为守护线程 t.setDaemon(True) #线程准备就绪,随时等候 cpu 调度 t.start() """

    print "读取配置文件完成,测试数据库连接" sql = """select getdate(), '%s' as txt""" text='teststreeerrrooo' teststr=teststrRead(text) print '执行函数获得 teststr 为:',teststr

    SysTrayIcon(icons.next(), hover_text, menu_options, on_quit=bye, default_menu_index=1)

    """ while 1==1: strqq='' strqq = input("Enter your input: ") print "Received inpu is : ", strqq """

    dec.ini 文件内容为

    [DATA] sqlserver = '127.0.0.1' user = 'test' password = 'test' database = 'test' g_conn = None

    第 1 条附言  ·  2016-10-25 20:33:56 +08:00

    --coding:utf-8 --

    import pymssql
    import ConfigParser
    cf=ConfigParser.ConfigParser()
    cf.read("conf.ini")
    DATABASE=cf.get("app_info","DATABASE")
    USER=cf.get("app_info","USER")
    PASSWORD=cf.get("app_info","PASSWORD")
    HOST=cf.get("app_info","HOST")
    PORT=cf.get("app_info","PORT")
    def mssql(sql):
        try:
            #conn=pymssql.connect(server="127.0.0.1", port="1433", user="test", password="test", database="master",charset="UTF-8")
            conn=pymssql.connect(host=HOST,user=USER,passwd=PASSWORD,db=DATABASE,port=PORT)
            cur = conn.cursor()
            cur.execute(sql)
            rows = cur.fetchall()
            conn.commit()
            cur.close()
            conn.close()
            return rows
        except pymssql.Error,e:
            print "Mysql Error %d: %s" % (e.args[0], e.args[1])
    
    def operation():
        select = mssql('select getdate(), \'kkkk\' as txt')
        return select #我返回这个是为了下面发送邮件用的,顺便增加个发送邮件的功能
    dddd=operation()
    print dddd
    
    7 条回复    2016-10-25 23:16:36 +08:00
    qile1
        1
    qile1  
    OP
       2016-10-25 20:35:07 +08:00
    cfing.ini 文件内容

    [app_info]
    DATABASE=test
    USER=test
    PASSWORD=test
    HOST=127.0.0.1
    PORT=1433
    [mail]
    host=smtp.163.com
    [email protected]
    password=654321
    [email protected];[email protected]
    Magician
        2
    Magician  
       2016-10-25 21:25:42 +08:00 via iPhone
    stackoverflow
    wellsc
        3
    wellsc  
       2016-10-25 21:42:24 +08:00
    莫名喜感
    qile1
        4
    qile1  
    OP
       2016-10-25 21:54:02 +08:00
    第一次发代码,发完下班断网断电,回来就没法编辑了,下面补了一个简化的代码,提示如下内容
    File "pymssql.pyx", line 505, in pymssql.connect (pymssql.c:7589)
    def connect(server='.', user='', password='', database='', timeout=0,
    TypeError: connect() got an unexpected keyword argument 'passwd
    orange88
        5
    orange88  
       2016-10-25 22:15:00 +08:00 via Android
    passwd<>password ?
    Ge4Los
        6
    Ge4Los  
       2016-10-25 23:15:11 +08:00
    @qile1 passwd 的参数名错了。另外你的邮箱密码暴露啦
    qile1
        7
    qile1  
    OP
       2016-10-25 23:16:36 +08:00
    stackoverflow 上面查了下,有这个例子,我把 password 改成 passwd 也报错!
    把链接字符串拼接成一个字符串传入也不对
    print 'host=',SQLSERVER,"user=",USER,"password=",PASSWORD,"database=",DATABASE
    g_Conn = pymssql.connect(host=SQLSERVER,user=USER,password=PASSWORD,database=DATABASE)
    输出正常值,在初始化连接的时候报错

    @staticmethod
    def connect():
    servers = ["server1", "server2", "server3"]
    conn = None
    for server in servers:
    try:
    conn = pymssql.connect(server, settings.MSSQL_USERNAME, settings.MSSQL_PASSWORD, settings.MSSQL_DB_NAME, charset="ISO-8859-1")
    break
    except:
    logger.info("Failed to connect to MSSQL Server: " + server)

    if conn:
    return conn
    else:
    logger.info("Failed to connect to ALL MSSQL servers")
    return conn




    结果多次测试已经算是解决了吧
    配置文件读取后显式的调用下可以使用了

    cf=ConfigParser.ConfigParser()
    cf.read("conf.ini")
    DATABASE=cf.get("app_info","DATABASE")
    USER=cf.get("app_info","USER")
    PASSWORD=cf.get("app_info","PASSWORD")
    HOST=cf.get("app_info","HOST")
    PORT=cf.get("app_info","PORT")
    #HOST = '127.0.0.1'
    USER = 'test'
    PASSWORD = 'test'
    #DATABASE = 'test'
    PORT='1433'
    HOST1 = '127.0.0.1'
    USER1 = 'test'
    PASSWORD1 = 'test'
    #DATABASE1 = 'test'
    PORT1=PORT
    HOST1 = HOST
    USER1 = USER
    PASSWORD1 =PASSWORD
    DATABASE1 = DATABASE
    PORT1=PORT



    conn=pymssql.connect(host=HOST1,user=USER1,password=PASSWORD1,database=DATABASE1,port=PORT1)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2645 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 15:20 · PVG 23:20 · LAX 07:20 · JFK 10:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.