What's the simplest way to access mssql with python or ironpython?

前端 未结 8 2034
忘了有多久
忘了有多久 2020-12-04 16:56

I\'ve got mssql 2005 running on my personal computer with a database I\'d like to run some python scripts on. I\'m looking for a way to do some really simple access on the d

相关标签:
8条回答
  • 2020-12-04 17:40

    PyPyODBC (http://code.google.com/p/pypyodbc) works under PyPy, Ironpython and CPython.

    This article shows a Hello World sample of accessing mssql in Python.

    PyPyODBC has almostly same usage as pyodbc, as it can been seen as a re-implemenation of the pyodbc moudle. Because it's written in pure Python, it can also run on IronPython and PyPy.

    Actually, when switch to pypyodbc in your existing script, you can do this:

    #import pyodbc               <-- Comment out the original pyodbc importing line
    
    import pypyodbc as pyodbc    # Let pypyodbc "pretend" the pyodbc
    
    pyodbc.connect(...)          # pypyodbc has 99% same APIs as pyodbc
    
    ...
    
    0 讨论(0)
  • 2020-12-04 17:45

    If you are want the quick and dirty way with CPython (also works for 3.X python):

    Install PYWIN32 after you install python http://sourceforge.net/projects/pywin32/files/pywin32/

    Import the following library: import odbc

    I created the following method for getting the SQL Server odbc driver (it is slightly different in naming depending on your version of Windows, so this will get it regardless):

    def getSQLServerDriver():
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\ODBC\ODBCINST.INI")
        sqlServerRegExp =  re.compile('sql.*server', re.I | re.S)
    
        try:
            for i in range(0, 2048):
                folder = winreg.EnumKey(key, i)
                if sqlServerRegExp.match(folder):
                    return folder.strip()
        except WindowsError:
            pass
    

    Note: if you use the above function, you'll need to also import these two libraries: winreg and re

    Then you use the odbc API 1 information as defined here: http://www.python.org/dev/peps/pep-0248/

    Your connection interface string should look something like this (assuming you are using my above method for getting the ODBC driver name, and it is a trusted connection):

    dbString = "Driver={SQLDriver};Server=[SQL Server];Database=[Database Name];Trusted_Connection=yes;".replace('{SQLDriver}', '{' + getSQLServerDriver() + '}')
    

    This method has many down sides. It is clumsy because of only supporting ODBC API 1, and there are a couple minor bugs in either the API or the ODBC driver that I've run across, but it does get the job done in all versions of CPython in Windows.

    0 讨论(0)
提交回复
热议问题