Home

PDF version - eGenix.com

image

Contents

1. Accordingly eGenix com specifically disclaims any express or implied warranty of fitness for High Risk Activities Licensee agree that eGenix com will not be liable for any claims or damages arising from the use of the Software or any software tool process or service that was developed using the Software in such applications mxODBC Python ODBC Database Interface 14 15 186 General Nothing in this License Agreement affects any statutory rights of consumers that cannot be waived or limited by contract Nothing in this License Agreement shall be deemed to create any relationship of agency partnership or joint venture between eGenix com and Licensee If any provision of this License Agreement shall be unlawful void or for any reason unenforceable such provision shall be modified to the extent necessary to render it enforceable without losing its intent or if no such modification is possible be severed from this License Agreement and shall not affect the validity and enforceability of the remaining provisions of this License Agreement This License Agreement shall be governed by and interpreted in all respects by the law of Germany excluding conflict of law provisions It shall not be governed by the United Nations Convention on Contracts for International Sale of Goods This License Agreement does not grant permission to use eGenix com trademarks or trade names in a trademark sense to endorse or promote products
2. ORDINAL _ POSITION SMALLINT not NULL Column sequence number in the primary key starting with 1 PK_NAME VARCHAR 128 Primary key identifier NULL if not applicable to the data source procedures qualifier None owner None procedure None Query the data source for information on procedures stored in a data source procedure Can be used to limit the results to a set of procedures or a single procedure The method is useful for determining the availability of stored procedures and also for database schema introspection purposes The catalog method generates a result set having the following schema Column Name Column Datatype Comment PROCEDURE CAT VARCHAR 128 Always NULL PROCEDURE_SCHEMA VARCHAR 128 The name of the schema containing PROCEDURE_NAME PROCEDURE NAME VARCHAR 128 not NULL The name of the procedure NUM_INPUT_PARAMS INTEGER not NULL Number of input parameters NUM_OUTPUT PARAMS INTEGER not NULL Number of output parameters NUM RESULT SETSNUM INTEGER not NULL _RESULT_ SETS Number of result sets returned by the procedure REMARKS VARCHAR 254 Contains the descriptive information about the procedure PROCEDURE_TYPE SMALLINT Defines the procedure type SQL PT UNKNOWN It cannot be determined whether the procedure returns a value SQL PT PROCEDURE The returned object mxODBC Pytho
3. from test Column 4 TABLE TABLE TABLE TABLE TABLE TABLE TABLE TABLE mx ODBC i1ODBC DriverConnect DSN database UID user PWD passwd Column 5 Columna 5 makes it an ideal basis for writing cross platform database applications 160 15 Examples 161 Note When connecting to a database with transaction support you should explicitly do a rollback or commit prior to closing the connection In the example this was omitted since the used MySQL database backend does not support transactions and we were only reading from the database mxODBC Python ODBC Database Interface 16 162 Testing the Database Connection The package includes a test script that checks some of the database s features As side effect this also provides a good regression test for the mxODBC interface To start the test simply run the script in mx ODBC Misc test pyc python mx ODBC Misc test pyc The script will generate a few temporary tables named mx0DBC0001 mxODBC0002 etc no existing tables will be overwritten and then test the interface database communication including many database related features such as data types and support of various SQL dialects The tables are automatically removed after the tests have run through 17 mxODBC Package Structure 17 mxODBC Package Structure This is the Python package structure setup when installing mxODBC ODBC Doe
4. Improved Sybase ASE driver compatibility this only supports Python type binding which is now enabled per default Added work around for PostgreSQL driver which doesn t support scrollable cursors Add support for MS SQL Server ODBC Driver 1 0 for Linux to mx ODBC Improved compatibility of the mxODBC native Unicode string format handling with Unix ODBC drivers when running UCS4 builds of Python This allows using the NVARCHAR and NCHAR types of SQL Server with the new MS SQL Server Native Client for Linux with UCS4 Python builds UCS2 Python builds don t exhibit this issue mxODBC 3 2 now always uses direct execution with the FreeTDS ODBC driver This results in better compatibility with SQL Server and faster execution across the board mxODBC Python ODBC Database Interface 170 Add work around to have FreeTDS work with 64 bit integers outside the 32 bit signed integer range Fixed linker error in FreeTDS subpackage Note that this is not supported please use the unixODBC ODBC packages instead FreeTDS rowcount attribute gave misleading values for SELECTs This now always returns 1 until they hopefully fix the driver to return usable data Fixes Better error message in case executemany parameters is found not to be a sequence Enhanced error message when passing non sequence items in a parameters list to cursor executemany Fixed a small memory leak in the mxODBC connection constructor Added back mx
5. cccccccnooocccnncccnnncnnocccnncncnnnnnos 47 Actual Technologies Mac OS X ODBC Driver for Sybase 47 Postres O liinda 47 Available ODBCDIVE Ssss 47 Postres OL ODBC DIVET esaea a a a sa dap ens vactsenusivewns 47 DIVER NOTO SN A ao coe oe 48 Example Configuration for UNiX coccccnnonoocconnnccnnonanaccnnncncnnnannnos 48 EasySoft ODBC Driver for PostgreSQL ssecceeeeeesessnneeeeeeeeeeeees 49 OpenLink ODBC Driver for PostgreSQL ccccccnnnnnoccnnncccnnnconannnnnos 49 DataDirect ODBC Driver for PostgreSQL ooooooocccccccncoooooccnncncnnnnannss 49 Actual Technologies Mac OS X ODBC Driver for PostgreSQL 49 MYSO rene a 49 Avalable ODBC DVE S ras 49 NWSOLODEC DE Versos 49 DAVE Notes a 49 Example Configuration for UNiX cocccccnnonoccnnnncnnnnnnnocnnonaninnnnnnnos 50 OpenLink ODBC Driver for MySQL ccoocconoccccnccnonononcccnnnncnnnnanancnnnos 51 DataDirect ODBC Driver for MySQL cccccononococcncccnnnonononcnnnncnnnnannos 51 Actual Technologies Mac OS X ODBC Driver for MySQL 51 Genera NOE a 51 SAP MaxDB 7 SAPD Bis 51 Available ODBC DOVES cando 51 MaxDB ODBC UV ninas 51 Example Configuration for UNiX cocccccnnnnocconnncnnnnnanocncnncncnnnnannss 52 General Database Note Sunstar aa 52 Warnings when deleting update more than one row at a time 52 Trad 53 Available ODBC DrIVETS A 53 teradata ODBC DNVET cido 53 DAVE NOE a 53 Example Configuration for UNiX coccccnnnnnncc
6. COLUMN SIZE INTEGER If the DATA_TYPE column value denotes a character or binary string then this column contains the maximum length in characters for the column For date time timestamp data types this is the total number of characters required to 101 mxODBC Python ODBC Database Interface 102 Column Name Column Datatype Comment display the value when converted to character For numeric data types this is either the total number of digits or the total number of bits allowed in the column depending on the value in the NUM_PREC_RADIX column in the result set LITERAL PREFIX VARCHAR 128 Prefix for a literal of this data type This column is NULL for data types where a literal prefix is not applicable LITERAL SUFFIX VARCHAR 1 28 Suffix for a literal of this data type This column is NULL for data types where a literal prefix is not applicable CREATE PARAMS VARCHAR 1 28 The text of this column contains a list of keywords separated by commas corresponding to each parameter the application may specify in parenthesis when using the name in the TYPE_NAME column as a data type in SQL The keywords in the list can be any of the following LENGTH PRECISION SCALE They appear in the order that the SQL syntax requires that they be used NULL is returned if there are no parameters for the data type definition such as INTEGER Note The in
7. SOL WCHAR SOL WVARCHAR SOL WLONGVARCHAR TEXT BLOB or LONG in SQL String or Unicode or stringified object The conversion truncates the string at the SQL field length Note that currently only very few ODBC drivers can handle native Unicode The only way to store Unicode data in a non Unicode aware database is by encoding it using e g UTF 8 The handling of Unicode depends on the setting of the stringformat attribute In EIGHTBIT STRINGFORMAT and UNICODE STRINGPORMAT mode Unicode is converted to an 8 bit string before passing it to the ODEC driver using the connection s character encoding setting Strings are passed as is In all other modes Unicode is passed to the ODBC driver as native Unicode Strings are converted to Unicode before passing them to the ODEC driver using the connection s character encoding setting Unlike for SQL CHAR and SQL BINARY there is no special case for mxDateTime or mxDateTimeDelta objects mxODBC Python ODBC Database Interface SQL Type Python Type Comments SOL BINARY SOL VARBINARY SOL LONGVARBINARY SQL BLOB or LONG BYTE in buffer memoryview or String Truncation at the SQL field length These columns can contain embedded 0 bytes and other special characters Handling of these column types is database dependent Please refer to the database s documentation for details Many databases store the passed in data as
8. Column Name Column Datatype Comment UPDATE_RULE SMALLINT Action to be applied to the foreign key when the SQL operation is UPDATE SQL RESTRICT SQL NO_ACTION SQL CASCADE SQL SET NULL DELETE_RULE SMALLINT Action to be applied to the foreign key when the SQL operation is DELETE SQL CASCADE SQL NO_ ACTION SQL RESTRICT SQL SET DEFAULT SQL SET NULL FK_NAME VARCHAR 128 Foreign key identifier NULL if not applicable to the data source PK_NAME VARCHAR 128 Primary key identifier NULL if not applicable to the data source DEFERRABILITY SMALLINT Possible values SQL INITIALLY DEFERRED SQL INITIALLY IMMEDIATE SQL NOT_DEFERRABLE gettypeinfo sqltype Query the data source for information on a supported data type sqltype sqltype must be one of the SQL type codes as returned in cursor description 1 See section 8 Data Types supported by mxODBC for a list of SQL type codes and details about their use This method is useful to determine characteristics of the given SQL data type and how it is defined in the SQL dialect supported by the data source The catalog method generates a result set having the following schema Column Name Column Datatype Comment TYPE_NAME VARCHAR 128 not NULL Character representation of the SQL data type name e g VARCHAR DATE INTEGER DATA TYPE SMALLINT not NULL SQL data type of column identified by COLUMN_ NAME
9. Python ODBC Database Interface 80 Parameters in SQL statements used on cursor execute methods are marked with a colon followed by a name e g a or 1 The variables are bound to these parameter locations using a name based mapping Parameter values for a SQL statement must be specified as mapping normally a dictionary and are bound to the locations based on the names used in the SQL statement Example SELECT FROM MyTable WHERE A a AND B b used with a parameter dictionary a 1 b 2 would result in the database executing the query SELECT FROM MyTable WHERE A 1 AND B 2 sStringformart Use this attribute to set or query the default input and output handling for string columns of all cursors created using this connection object Data conversion on input is dependent on the input binding type Possible values are see the Constants section 10 5 for details EIGATBIT STRINGFORMAT default This format tells mxODBC to convert all data passed to and read from the ODBC driver to 8 bit strings On input Python 8 bit strings are passed to the ODBC driver as is Unicode objects are converted to Python 8 bit strings assuming the connection s encoding setting see the encoding attribute of connection objects prior to passing them to the ODBC driver On output all string columns are fetched as strings and passed back as Python 8 bit string objects Unicode data from the database is converted to Python 8 bit st
10. mxODBC FUN ctiOns ccccccsssssscscccccscscscssseses 144 S bpackage PUNCHONS eta 144 Daa Oarces stato oie 144 setenvalMOPUO ica 144 setenvattr option vale ni ii ici 144 AO ds 145 mx O DBC FUNCUOA Si 145 Contents format_resultset cursor headers None colsep headersep stringify repr ccocccnonocccnnncnonononcccnnncnnnnnnancnnnnos 145 print_resultset cursor headers None ecccceeeeeeeeeeeeees 145 12 mxODBC Globals and Constants 146 12 1 Subpackage Globals and ConstantS cccccccccccncnnncncnnns 146 DO E A dada a O 146 CNEOT CIES S toldos 146 BOIL DG waste PEE E E E E T 146 CHAR VARCHAR LONGVARCHAR BINARY VARBINARY LONGVARBINARY TINYINT SMALLINT INTEGER BIGINT DECIMAL NUMERIC BIT REAL FLOAT DOUBLE DATE TIME TIMESTAMP CLOB BLOB TYPE_DATE TYPE TIME TYPE TIMESTAMP UNICODE UNICODE LONGVARCHAR UNICODE VARCHAR WCHAR WVARCHAR WELONGVARCHAR Dorsser nen Ee E ate 146 reads ale sinni on ena aerate 146 E o sbivaaeh E E seas E 147 BD LLIN NS YL taria eat 147 BIND USING SQLTYPE BIND USING PYTHONTYPE 147 DATETIME DATETIMEFORMAT PYDATETIME DATETIMEFORMAT TIMEVALUE DATETIMEFORMAT TUPLE _DATETIMEFORMAT STRING DATETIMEFORMAT cisco 147 EIGHTBIT_STRINGFORMAT MIXED _STRINGFORMAT UNICODE STRINGFORMAT NATIVE UNICODE STRINGFORMAT ccccescssecessecerseceeeeceeeee 147 ERROR _WARNINGFORMAT WARN _WARNINGFORMAT IGNOR
11. 13 2 mx ODBC Manager Generic ODBC Driver Manager In order to make writing cross platform application easier with mxODBC the package provides a meta subpackage to access the default platform ODBC driver manager 149 mxODBC Python ODBC Database Interface 13 3 13 3 1 150 Windows Platforms mxODEC selects the subpackage by trying to import the available ODBC driver subpackages in the following order 1 mx ODBC Windows No other subpackage is currently tried since the Windows ODBC manager is always present in all recent Windows versions Unix Platforms mxODEC selects the subpackage by trying to import the available ODBC driver subpackages in the following order 1 mx ODBC unixODBC 2 mx ODBC 1ODBC 3 mx ODBC DataDirect The mx ODBC Manager package then behaves just like the driver manager chosen by this process Please note The order was changed in mxODBC 3 2 Previous mxODBC versions preferred ODBC over unixODBC Since unixODBC is widely supported nowadays and provides better Unicode support selecting unixODBC over ODBC when both are present provides a better user experience mx ODBC Windows Windows ODBC Driver Manager Tested with Windows XP Vista 7 mxODBC links against the Windows ODBC driver manager on Windows This is the only mxODBC interface subpackage available on Windows Connecting to a Database Always use the DriverConnect API to connect to the data source if you need t
12. 22 BSN less CONMMECUONS o A teen thes 23 Pros and Cons of using DSN less ConnectionsS ccccccnonoccccncncnnns 23 DNS less Connection STINE i 23 Accessing Databases from UNIX sssssssssssssssssssssssssssssssses 24 Looking tor Unix ODBC Drives Corina 24 mxODBC Connect a general purpose client server solution 25 installing Unix ODBC Drivers ia 25 Setting up an ODBC Data SOUFCE occccccnnnooccccncccnnnononinonnnccnnncnananiniccnnnss 26 ODBC Configuration FICS seccatid cados 26 etc odbc ini System ODBC Data Source Configuration 26 OBBE sais 27 ODBC Data SOULCES iia iaa 27 odbc ini User ODBC Data Source Configuration ooooooccccc 27 etc odbcinst ini System ODBC Driver Configuration 27 ODBC Aaa os at egotism etaeae 27 ODBC DIVER 28 odbcinst ini User ODBC Driver Configuration eceeee 28 Environment Variables ODBCINI and ODBCINSTINI 28 ODE GIN Estan ia 28 OD BCING TIN icsscassccsceassosaacssotenensecaasaedeoaatecusesaauienaeteumesatenssens 28 mxODBC Python ODBC Database Interface 3 3 6 3 3 7 4 1 4 1 1 4 1 2 4 2 Available Data Source Types DSNS ccconoooccconcccnnnonoocnnnnnnccnnnnnnncnnnnnncnnns 29 User Data Sources User DSN scuciesivoctuarcns avatar aeia a 29 System Data Sources System DSN osiris 29 File Data Sources File DSN oooconoonocccnncccnnonocnnnnnnnnnnnnnncnnnnnncnnnnnnos 30 D
13. 4 11 2 OpenLink Homepage http www openlinksw com OpenLink maintains the open source ODBC manager ODEC 4 11 3 DataDirect Homepage http www datadirect com DataDirect drivers ship their own ODBC manager Since this ODBC manager is not compatible with unixODBC or iODBC please use the mx ODBC DataDirect driver manager package when accessing the DataDirect drivers through the DataDirect ODBC manager The mx ODBC DataDirect package is currently only available for Linux 32 bit and 64 bit systems If you need the package on other platforms please write to support egenix com for assistance 4 11 4 Other Vendors For a fairly large list of sources for ODBC drivers have a look on the SQLSummit list of ODBC drivers 4 11 5 Alternative solution mxODBC Connect 57 If you would like to connect to a database for which you don t have a Unix ODBC driver you can also try our mxODBC Connect Python Database Interface which just needs an ODBC driver on the server side and provides a cross platform networked interface to this for the client side This makes it very easy to connect to e g a Windows based database from Unix BSD or Mac OS X mxODBC Python ODBC Database Interface 5 1 5 1 1 50 mxODBC Overview mxODBC is structured as Python package to support interfaces to many different ODBC managers and drivers Each of these interfaces is accessible as subpackage of the mx opBc Python package e g on Windows you d
14. The following mappings are used for input variables in Python type input binding mode connection bindmethod set to BIND USING PYTHONTYPE The table shows how the different Python types are converted to SQL types SQL WLONGVARCHAR wchar_t Python Type SQL Type Comments String SQL VARCHAR The conversion truncates the string at the SQL SQL LONGVARCHAR field length If the string contains binary data SQL VARBINARY SQL VARBINARY is used for passing the data to SOL LONGVARBINARY the ODBC driver manager Char The long variants are used for strings longer than 256 characters Unicode SOL WVARCHAR The conversion truncates the string at the SQL field length Note that not all ODBC drivers managers support Unicode data at C level This binding is used for all cursors which do not have the stringformat attribute set to EIGHTBIT STRINGFORMAT or UNICODE STRINGFORMAT In EIGHTBIT STRINGFORMAT mode default and UNICODE STRINGFORMAT mode Unicode objects are converted to a 8 bit strings first and then passed to the ODBC driver manager The long variant is used for Unicode data longer than 256 code points 8 Data Types supported by mxODBC 127 Python Type SQL Type Comments buffer or memoryview SOL VARBINARY SOL LONGVARBINARY char The conversion truncates the string at the SQL field length The string may contain binary data If the ODBC driver manager doesn t suppor
15. command This method returns the command as it would have been modified by the driver to pass to the database engine It is a direct interface to the ODBC API SOLNativeSql In many cases it simply returns the command string unchanged Some drivers unescape ODBC escape sequences in the command string Syntax checking is usually not applied by this method and errors are only raised in case of command string truncation Not all mxODBC subpackages support this API rollback In case the database connection has transactions enabled this method causes the database to roll back any changes to the start of the current transaction Closing a connection without committing the changes first will cause an implicit rollback to be performed This method is only available if the ODBC driver database subpackage was compiled with transaction support For ODBC manager subpackages it is always available but may raise a NotSupportedError in case the connection does not support transactions setconnectoption option value This method lets you set some ODBC integer options to new values e g to set the transaction isolation level or to turn on auto commit option must be an integer Suitable option values are available through the SQL object e g SOL ATTR _AUTOCOMMIT corresponds to the SQL option SOL ATTR AUTOCOMMIT in C see the Constants section 10 5 for details The method is a direct interface to the ODBC soLSetConnectOption
16. mxODBC supports Python versions 2 3 2 7 on most platforms Python Build Architecture 32 bit or 64 bit On most platforms eGenix com supports x86 32 bit and x86_64 AMD64 EM64T 64 bit versions of Python To find out which Python version you are using run the following command python lt import struct print struet calcelize e 6 bic This will print out 32 bit or 64 bit mxODBC Python ODBC Database Interface 2 2 Unicode Variant UCS2 or UCS4 On Unix and Mac OS X Python can be built using two different Unicode variants UCS2 and UCS4 Windows builds are always UCS2 builds To find out which variant your Python version was compiled with run the following command python c print UCS s len u x encode unicode internal This will either print out UCS2 or UCS4 Installation using Windows installers The installers provided by eGenix com for use on Windows only include the mx ODBC Windows subpackage of mxODBC This subpackage interfaces directly to the Microsoft ODBC Manager so you can use all available Windows system tools to configure your ODBC data sources 2 2 1 Prerequisites e Please make sure that you have a working installation of the egenix mx base distribution prior to continuing with the installation of the egenix mxodbc add on You can easily check this by checking the Windows Software Setup dialog for an entry of the form Python x x eGenix com mx Base D
17. of the timestampresolution setting which defines the resolution of the timestamps in nanoseconds mxODBC will round the timestamp s second value to the nearest nanosecond fraction defined by this setting in order to avoid issues with float second values which sometimes cannot be represented with full accuracy If not mxODBC Python ODBC Database Interface 128 Python Type SQL Type Comments set the timestampresolution attribute defaults to 1 nanosecond so rounding usually is done to the nearest nanosecond which is also the smallest fraction supported by the ODBC standard DateTimeDelta SOL TIME Converts the DateTimeDelta instance into a TIME struct defined by the ODBC standard Fractions of a second will be lost in this conversion datetime date SOL DATE Converts the datetime date instance into a DATE struct defined by the ODBC standard Note that some database backends don t support date column types and give an error when using datetime date objects MS SQL Server 2000 and 2005 are examples MS SQL Server 2008 introduced a date column type datetime time SOL TIME Converts the datetime time instance into a TIME struct defined by the ODBC standard datetime datetime SOL TIMESTAMP Converts the datetime datetime instance into a TIMESTAMP struct defined by the ODBC standard Seconds are rounded to the nearest nanosecond in order to avoid issues with float seco
18. usr local lib libmyodbc5 so setup Edit the odbc ini file based and add a mysql section the location of the driver file may be different on your system It is also necessary to point LD LIBRARY PATH to the directory where the driver itself is located myodbc Driver usr local lib libmyodbc5 so Description MySQL 5 Server Server mysql example net Port Specifying a database is necessary for MySQL since you ll otherwise won t be able to connect Database mydb Allow big packets for BLOBs etc option 8 Socket Using these settings you can then connect to MySQL using a simple connection string such as DSN mysql UID username PWD password 4 Accessing Popular Databases 4 7 2 4 3 4 8 1 51 OpenLink ODBC Driver for MySQL Homepage http www openlinksw com DataDirect ODBC Driver for MySQL Homepage http www datadirect com Actual Technologies Mac OS X ODBC Driver for MySQL Homepage http www actualtech com When using the driver on Mac OS X 10 6 Snow Leopard be sure to use version 3 0 9 or higher since earlier versions had a problem with fetching data General Notes Depending on whether you use a transactional MySQL storage backend or not clearing the auto commit flag at connection time which is normally done per default by the connection constructors will not work Be sure to set clear auto commit 0 if you know that the storage backend cannot handle transactions
19. 7 Python Build Architecture 32 bit or 64 bit oooooooocucnccccnnncononacanononons 7 Unicode Variant UCS2 or UCS 4 ecooooooocccucunanononnnnnnnnnnnnnnnnnanccnnnnnnnnnos 8 22 Installation using Windows installers eee 8 sra dde UL Le APPEAR OPM A 0 8 222 51 0 dd VOU 1 1 5 OPE PE N E arenes eeniiaenane 8 Boreae lin nia ara 8 Mo AA A PR 9 2 2 3 Step by step Installation Guide se eeeeesseeeceeeeeeeeeesneeeeeeeeeeeeeseaees 9 mxODBC Python ODBC Database Interface 2 2 4 23 ye os pie Fee 2 3 4 2 4 2 4 1 2 4 2 2 4 3 3 1 3 1 1 J2 EP AAA nn E aabbarenecueesiees 10 O a a a 10 E DA A E A E E E E O th E tosis 10 Uninstall 10 Installation using egg package archives cooomommmmmmmmmm o 11 oj U1 8 016 ume er pe Ue rene TS mR Re re Wenn oer sea ney ee er eat ee Te aCe te 11 Before Yow ola 1 PO OO POCO yn5uI O e ea sesh 11 UPN 11 eense PILES cassava atracoea 11 Step by step Installation Guide oooooooooccnncccnonononccnncnnnnnnnanccccnncnncnnnannnos 12 A O o o E 12 A eee RE ee ee reer ee Ve ee Ere er ere ne eee ere eer 12 o e E E folk anes ae A E E iausabeds 13 SECO esia a a entrees Saanich mre ae aasuameecsbiean te 13 Uninstall 14 Installation using prebuilt package archives 14 Belore YOU Sd 14 OO 14 censo les is 14 Step by step Installation Guide ooooooocccnnocccnnnnonocccnnnnnnnnnnnncccnnnnncnnnnnnos 15 Se tdo oe 15 A ta E T TA 15 SED S
20. ERROR WARNINGFORMAT default Report warnings in the usual DB API 2 0 way and raise a Warning exception WARN WARNINGFORMAT Instead of raising a Warning exception issue a mx ODBC DatabaseWarning which is a Python Warning subclass and can be filtered using the standard Python warnings module mechanisms IGNORE WARNINGFORMAT Silently ignore the database warning The warning will still be added to the message attribute but no further action is taken 10 mxODBC Exceptions and Error Handling 10 6 2 Custom Warning Error Handler 143 If you need a more fine grained approach to dealing with warnings you can also setup a special error handler which then overrides the behavior of the default handler If you want to mask only certain Warnings simply set a connection errorhandler like the one below to disable raising exceptions for database warnings Error handler function def myerrorhandler connection cursor errorclass errorvalue uu This error handler ignores but logs 01000 warnings issued by the database VW Y YY Append to messages list if cursor is not None cursor messages append errorclass errorvalue elif connection is not None connection messages append errorclass errorvalue Ignore 01000 database warning 1f issubclass errorclass connection Warning and errorvalue 0 01000 return Raise all other database errors and warnings raise errorclass errorvalue Installation of
21. G nix com ODBC Database Interface for Python Version 3 2 Copyright O 1997 2000 by IKDS Marc Andr Lemburg Langenfeld Copyright O 2000 2013 by eGenix com GmbH Langenfeld All rights reserved No part of this work may be reproduced or used in a any form or by any means without written permission of the publisher All product names and logos are trademarks of their respective owners The product names mxBeeBase mxCGIPython mxCounter mxCrypto mxDateTime mxHTMLTools mxIP mxLicenseManager mxLog mxNumber mxODBC mxODBC Connect mxODBC Zope DA mxObjectStore mxProxy mxQueue mxStack mxTextTools mxTidy mxTools mxUID mxURL mxXMLToolIs eGenix Application Server PyRun PythonHTML eGenix and eGenix com and corresponding logos are trademarks or registered trademarks of eGenix com GmbH Langenfeld Printed in Germany Contents Contents 1 0 Introduction cccccccccccccccccccccccccccccccccccccccccccccccccocccoocce l 1 1 Technical OvervieWe oooconononoconoconononono nono no nonnnonnnnonononononononos 1 lez PSUR Scns eo A E EE T A E Z 1 3 REQUIEM rn otat iia co aodooecionos 3 WINOWS strip EE N 3 Di A OA ne II T 4 do gt AAA PP ee ee ee ee ee 4 2 Installation A 2 1 Download the Software messi 6 2 1 1 Automatic download estao 6 21 2 Manta Download ona 6 Operating System Platform cccccceesssssseeceeeeeesssseeeeeeeeeeeseeaeeees 7 A seissanto
22. InterfaceError failed to retrieve error information line 6778 re 1 Linker Paths Unfortunately the provided db2profile db2cshrs shell scripts are buggy in some versions of DB2 so simply sourcing them won t necessarily work You will have to carefully create your own to work around these issues A typical problem is that the scripts set LIBPATH Or LD LIBRARY PATH without paying attention to possibly existing settings which then causes the following linker related traceback when trying to load mxODBC 4 Accessing Popular Databases 4 5 4 5 1 Traceback most recent call last ImportError from module mxODBC so No such file or directory Database Setup for ODBC Access Unlike many other databases DB2 needs to be explicitly told that you want to connect to the database using ODBC This is done by binding the IBM CLI driver against the database in order to setup ODBC related views and stored procedures Please consult the IBM DB2 documentation for details on how this is done Static vs forward only Cursors DB2 supports static ODBC cursors and this results in mxODBC 3 2 to default to using static cursors on all connections While static cursors allow scrolling through the result set and also provides ways of accessing the correct rowcount value it does come with a significant performance penalty We have seen slow downs in fetching rows of around 2x times for average queries so we recommend configuring conne
23. Microsoft Here s quick version Lar xvfz sglacli 11 0 1790 0 tar g2 cd sqlncli 11 0 1790 0 mkdir p fopt mierosoft sqlneli bin mkdir p opt microsoft sglneli lib finstall sh install foree accept 11icense bin dir opt microsoft sgqlncli bin lib dir opt microsoft sgincli lib You can ignore any warnings Note that using the driver directly from the untarred archive is not possible since the installation location appears to be hardwired in the driver e Depending on your Linux distribution you may have to add symlinks to your OpenSSL libraries to match the ones used on RedHat cd 1ib64 lm 82 Libesl 30 LD Lineal 30 L0 if 3f Lliboryito sa ls 0 0 Litberyto so 10 ldconfig e Add the driver to the etc odbcinst ini or odbcinst ini ODBC Drivers MSNativeClient Installed MSNativeClient Driver opt microsoft sqlncli lib64 libsqlncli 11 0 s0 1790 0 Description MS SQL Server Native Client 11 Threading 1 e Add a data source to the etc odbc ini or odbc ini mssqlserver2008 Driver opt microsoft sqlncli lib64 libsqlncli 11 0 s0 1790 0 Description MS SQL Server 2008 running on Picasso MS Native Client Server tcp picasso SQLSERVER2008 1436 Database testdb The syntax for the Server entry is described in the MSDN article SQL Server Native Client ODBC Connection String Format EasySoft ODBC Driver for SQL Server Homepage http www easysoft com OpenLink O
24. ODBC driver can then communicate with the database using low level and high performance interfaces such as shared memory pipes etc Using the mxODBC Connect product you no longer need to search and install ODBC drivers for all your client platforms Instead you just need one ODBC driver installation on the server which is then shared by all clients The mxODBC Connect also provides better performance since it doesn t require as many network roundtrips to the server as a low level ODBC driver on the client side needs in order to provide the database connectivity Please see our website http www egenix com for more information on mxODBC Connect Installing Unix ODBC Drivers Please consult the documentation of your database for ODBC driver installation instructions These often have to be installed by running a shell script or using the system packaging manager There are no standards for the driver directory location Some drivers install in opt others in usr local yet others can be unzipped anywhere in the system provided the linker is setup to find the driver files mxODBC Python ODBC Database Interface 3 3 4 Setting up an ODBC Data Source 3 3 5 Data sources are setup using the ODBC manager GUI tools on Unix or by editing the respective ODBC configuration files The GUI tools can typically be found in the System part of the menu For more details description please see the ODBC manager manuals e unixODBC Use
25. ODBC environment option This method interfaces directly to the ODBC function SOLGetEnvAttr option must be an integer Suitable option values are available through the SOL singleton object The method returns the data as 32 bit integer It is up to the caller to decode the integer using the SQL defines This function is only available for ODBC 3 x compatible managers and ODBC drivers setenvattr option value This function lets you set ODBC environment attributes which are encoded as 32 bit integers This method interfaces directly to the ODBC function SQLSetEnvAttr option must be an integer Suitable option values are available through the SOL singleton object 11 mxODBC Functions This function is only available for ODBC 3 x compatible managers and ODBC drivers Note The function allows setting environment attributes which mxODBC itself uses to define the way it interfaces to the database Changing these attributes can result in unwanted behavior or even segmentation faults USE AT YOUR OWN RISK statistics Returns a tuple connections cursors stating the number currently open connections and cursors for this subpackage Note that broken connections or cursors are not correctly counted 11 2 mx ODBC Functions 145 In addition to subpackage specific helpers mxODBC also provides a few additional functions available through the top level mx oDBc package These are Formal tesultset cursor Neade
26. ODBC manager but instead have to be repeated in each application using a DSN less setup Even you upgrade an ODBC driver to a newer version you may have to change all DSN less connection setups due to changes in the ODBC driver name We recommend to only use DSN less setups if absolutely necessary or in cases where access to the ODBC configuration files is otherwise not possible DNS less Connection String A DNS less connection provides all configuration information you d normally configure in the ODBC manager for a data source Instead of a DSN name you provide a textual representation of the driver name enclosed in curly brackets e g Driver MySQL ODBC 3 51 Driver Server mysql example net Database mydb The name given in curly brackets must match the driver name as listed in the ODBC manager under Name on the Driver tab The ODBC manager will then map the name to the registered driver A DSN mydsn entry in the connection string is no longer needed For a list of common DSN less connection strings have a look at the ConnectionStrings com website In order to connect to a database using a DSN less connection string you simply pass the string to the mx ODBC Windows DriverConnect API mxODBC Python ODBC Database Interface 3 3 3 3 1 24 Accessing Databases from Unix mxODBC is often used to access databases across a network A very typical use case is that of connecting to MS SQL Server Oracle or DB2 from
27. SQL type information completely This makes it easier to work with drivers such as the SQL Server Native Client which have a few client side limitations that do not appear to be present on the server side Changed the license module name to mxodbc license py so that it can be installed as top level module anywhere on the sys path Note that installing it in mx ODBC will no longer work mxODBC cursors and connection objects now provide a new warningformat attribute which allows easily turning SQL warnings into Python warnings or completely ignoring them Added native support for BIGINT both signed and unsigned which avoids strings conversions if supported by the platform Added support for non standard SQLWCHAR types in order to better support drivers and manager on Unix platforms mxODBC now allows choosing between the Unicode and ANSI ODBC driver APIs of supporting ODBC drivers at connection time All catalog methods now support Unicode parameters as well as strings parameters Added support for adjusting the way catalog methods interpret their parameters as identifiers or as search patterns 19 History amp Changes 173 Catalog methods now check for arguments required by the ODBC API standard rather than letting the ODBC manager or driver raise an error Added new cursor getcolattribute method to allow access to result set column meta data beyond what is already available via cursor description See http msdn micr
28. The type of the return values depends on the setting of cursor datetimeformat and whether the ODBC driver manager does return the value with proper type information Default is to return DateTime instances SQL T LME DateTimeDelta instance or datetime time instance or tocks or hour minute second or String The type of the return values depends on the setting of cursor datetimeformat and whether the ODBC driver manager does return the value with proper type information Default is to return DateTimeDelta instances SQL TIMESTAMP DateTime instance or datetime datetime instance or ticks or year month day hour minute second or String The type of the return values depends on the setting of cursor datetimeformat and whether the ODBC driver manager does return the value with proper type information Default is to return DateTime instances SOL NULL value None The Python None singleton is used to represent the special SQL NULL value in Python Unsupported Type String mxODBC will try to fetch data from columns using unsupported SQL data types as strings This is likely to always work but may cause unwanted conversions and or truncations or loss of precision 130 8 Data Types supported by mxODBC 3 6 131 Output bindings can only be applied using the above mapping by mxODBC if the database correctly identifies the type of the output variables The SQL type
29. UNICODE STRINGFORMAT This format should be used for databases and applications that support native Unicode data communication String columns are converted to Python Unicode objects assuming the connection s encoding setting see the encoding attribute of connection objects and then passed as Unicode to the ODBC driver On output string data is always fetched as Unicode data from the ODBC driver and returned using Python Unicode objects Note that even though mxODBC may report that Unicode support is enabled default in Python 2 0 and later HAVE UNICODE SUPPORT is set to 1 the ODEC driver may still reject Unicode data In this case an InternalError of type S1003 is raised whenever trying to read data from the database in this stringformat mode You can use the included mx ODBC Misc test pyc script to find out whether the database backend support Unicode or not Binary and other plain data columns will still use 8 bit strings for interfacing since storing this data in Unicode objects would cause trouble mxODBC will eventually use buffer memoryview or some form of binary objects to store binary data in some future version e g the new bytes type which was introduced with Python 3 0 This value is inherited by all cursors created from the connection at creation time Note that changing the value of this attribute will not change the string format for existing cursors using this connection timestampresolution Use this att
30. Windows ODBC Data Source Administrator on Windows This can be found in the in the Control Panel as Administrative Tools and is called Data Sources ODBC See the Windows ODBC documentation for details Go to the Tracing tab and select a trace output file under Log File Path and then click on to enable ODBC tracing output After that is done start you application or script using mxODBC and run the code that is causing problems with the driver in question After you ve run the application or script open the ODBC administrator again and click on the same button now called Stop Tracing Finally pick up the ODBC trace file from the location you ve chosen and email it to support egenix com 18 Support 18 1 2 18 1 3 ODBC Driver Manager To enable ODBC level tracing open the etc odbc ini or odbc ini file and add this section to it ODBC Trace 1 TraceFile tmp odbc log If you already have such entries in the ODBC section make sure that the settings are correct and that Trace is set to 1 After that is done start you application or script using mxODBC and run the code that is causing problems with the driver in question After you ve run the application or script open the odbc ini file again and set Trace to 0 This will disable ODBC call level tracing Finally pick up the ODBC trace file from the location you ve chosen tmp odbc log in the example and email it to support egenix com unixODBC D
31. a Unix machine eGenix com has collected some information in the next section 4 Accessing Popular Databases which may help you in finding the right solution for this kind of setup We recommend that you always use an ODBC manager on Unix to access these driver setups e g unixODBC iODBC or the DataDirect ODBC manager Once you ve installed the ODBC drivers on the machine you are running your Python application on you will need to setup an ODBC Data Source This can be done using the ODBC manager GUIs which try to mimic the Windows ODBC Manager or using a text editor by editing either the system wide ODBC configuration files usually etc odbc ini and etc odbcinst ini Mac OS X uses Library ODBC odbc ini and Library ODBC odbcinst ini or the user home directory versions usually odbc ini and odbcinst ini To avoid problems with system permissions eGenix com recommends setting up data sources as System Data Sources using the GUI tools or in the system configuration file etc odbc ini using a text editor as these are usually accessible by all accounts on a Unix server Using the mxODBC connection constructor mx ODBC Manager DriverConnect you can then setup a connection to the database Looking for Unix ODBC Drivers Many database vendors also provide ODBC for various Unix platforms If you are looking for Linux drivers the situation has cleared up a lot in recent years On other platforms such as Mac OS X AIX Sola
32. a previous version of mxODBC you should uninstall the egenix mxodbc package first Please see 2 3 4 Uninstall for instructions License Files In order to use mxODBC you will need license files from eGenix com If you want to test the product before buying it you can request evaluation licenses via the eGenix com web site at http www egenix com When buying licenses from the eGenix com online shop http shop egenix com you will receive the license files immediately after purchase mxODBC Python ODBC Database Interface 2 3 3 12 In both cases the license files are sent to the email address you specified during the purchase process or from which you wrote the evaluation license request in form of a ZIP license archive attached to the license email usually named licenses zip The license archive licenses zip contains one subdirectory per license you bought The directories are named after the license key for each license A typical license archive will have these contents 2 100 8789 0322 0926 2568 0429 mx0dbec license py 2100 8789 0322 0926 2568 061429 mx00db0 license txt 2100 8089 0312 0920 2668 6529 mxodbc license py 2 100 gt 8089 0312 0926 26689 6929 mxodbec license txt in the above example the license archive contains the files for two product licenses In order to install the license files please unzip the license archive to a temporary directory In order for mxODBC to pick up the correct lic
33. available for backward compatibility Fixed bug in DataSources work around for ODBC which caused the DSN names to be truncated to two characters Changed the SQL types used for passing input data to the ODBC driver using executeXXX methods in Python type binding mode Instead of defaulting to SQL CHAR and SQL _ BINARY these now use the SQL types SQL VARCHAR SQL_VARBINARY Added better support for Python type bindings strings are now analyzed for binary content and then bound in binary mode if needed Added new connection attributes dbms name dbms_ version driver_name driver_version Added new cursor methods next and __iter__ which enable cursors to be used as iterators in Python 2 2 Changed quite a few SQLSTATE to exception class mappings and added new mappings for ODBC 3 x If you need to force usage of other mappings please assign these mappings to the modules scope dictionary errorclass Added user definable error handlers as defined in the DB API 2 0 extensions 19 History amp Changes 177 Changed the Windows source files from using the cpp extension to the c extension This should avoid confusion with non VC compilers since mxODBC does not include any C code It also works nice with distutils Added more SQL_ symbols The list now includes all integer symbols from ODBC 3 51 and many database specific extensions including IBM DB2 extensions and MS SQL Server extensions Added new experime
34. based on the methods enter and exit The context managers can be used together with the Python with statement to wrap sections of a program into a block the context that is entered and exited in a controlled way With context Manager as context context do something When entering the block the context manager s enter method is called and the returned object assigned to context When exiting the block the context exit is called either with the exception that caused the block to be left or without exception in case the block was left normally Using connection objects as context object Connection objects implement this API and use it to automatically commit or roll back the current transaction from mx ODBC Manager import DriverConnect connection DriverConnect With connection Cursor connecticn curscdr cursor execute INSERT INTO table VALUES 1 2 Other tasks cursor close This code will automatically commit the INSERT to the database backend in cae the with block is left without exception If the other tasks trigger an unhandled transaction the connection is rolled back when leaving the block For code which doesn t have to do more complex error handling using the with statement block can greatly simplify the resulting code It also gives the transaction section a visible resemblance in the code 6 mxODBC Connection Objects 6 6 6 6 1 6 6 2 73 Cursors also su
35. database This can result in better performance with some ODBC driver setups but also implies that Python type binding mode is used to bind the parameters sql1cma may be a Unicode object in case the ODBC driver and or database support this Return values are not defined fetchall Fetch all remaining rows of a query result returning them as a sequence of sequences e g a list of tuples An Error or subclass exception is raised if the previous call to execute did not produce any result set or no call was issued yet 87 mxODBC Python ODBC Database Interface 88 fetchmany size cursor arraysize Fetch the next set of rows of a query result returning a sequence of sequences e g a list of tuples An empty sequence is returned when no more rows are available The number of rows to fetch per call is specified by the parameter If it is not given the cursor s arraysize determines the number of rows to be fetched The method will try to fetch as many rows as indicated by the size parameter If this is not possible due to the specified number of rows not being available fewer rows may be returned An Error or subclass exception is raised if the previous call to execute did not produce any result set or no call was issued yet fetchone Fetch the next row of a query result set returning a single sequence or None when no more data is available An Error or subclass exception is raised if
36. deal with passing Unicode to and fetching it from an ODBC driver The stringformat attribute of connection and cursor objects allows defining how to convert string data into Python objects and vice versa Unicode conversions to and from 8 bit strings in Python usually assume the Python default encoding which is ASCII unless you modify the Python installation Since the database may be using a different encoding mxODBC allows defining the encoding to be used on a per connection basis The encoding attribute of connection objects is writeable for this purpose Its default value is None meaning that Python s default encoding usually ASCII is to be used You can change the encoding by simply assigning a valid encoding name to the attribute Make sure that Python supports the encoding you can test this using the unicode built in The default conversion mechanism used in mxODBC is EIGHTBIT STRINGFORMAT Unicode gets converted to 8 bit strings before passing the data to the driver output is always an 8 bit string the default encoding Python s default encoding To store Unicode in a database one possibility is to use the UNICODE STRINGFORMAT and set the encoding attribute to eg utf 8 mxODBC will then convert the Unicode input data to UTF 8 store this in the database and convert it back to Unicode during fetch operations Note however that UTF 8 encoded data usually takes up more room in the database than the Unicode equivalent so m
37. for Unix Windows DB2 servers Tested with IBM DB2 9 7 ODBC driver IBM DB2 ships with ODBC drivers for DB2 on Windows Linux and other Unix systems These can also be used to connect to DB2 database over a network Please see this page for more information http publib boulder ibm com infocenter db2luw v9 index sp topic com ibm db 2 udb apdv cli doc doc c0023378 htm Example Configuration for Unix e Setup the network details of your DB2 database in the db2cli ini file ibmdb2 DBAlias SAMPLE Hostname db2 example net e Using the same section name add a new section to your odbc ini file ibmdb2 Driver fusr local odbe drivers db2 clidriver lib 1libdb2 0 You will have to change the driver entry to the location where you copied the ODBC driver and add the lib directory of the driver to your LO LIBRARY PAIR e You can then connect to your database via the connection string DSN ibmdb2 UID username PWD password IBM ODBC Driver for Series AS 400 DB2 servers IBM has a Linux ODBC driver which makes this setup possible See their web page on the iSeries ODBC driver for Linux for details http www 03 ibm com systems i software access linux guide index htm OpenLink ODBC Driver for DB2 Homepage http www openlinksw com DataDirect ODBC Driver for DB2 Homepage http www datadirect com mxODBC Python ODBC Database Interface 4 4 2 General Notes 44 ODBC API Extensions and the IBM C
38. for the above configuration files the ODBC managers honor a few environment variables which can be used to direct them to specific alternate files ODBCINI This environment is used by the ODBC manager to find the ODBC data source configuration file if set VOBCINSTINI This environment is used by the ODBC manager to find the ODBC driver configuration file if set 3 Access Databases using mxODBC Note that some driver manager do not support this environment variable unixODBC and ODBC support the variable the DataDirect ODBC manager doesnt 3 3 6 Available Data Source Types DSNs 29 There are three kinds of data sources that you can install on Windows machines 1 User Data Sources User DSN 2 System Data Sources System DSN 3 File Data Sources File DSN User Data Sources User DSN User data sources are only visible to the user creating them Other users normally do not have access to these data source definitions The user DSNs can be defined via the ODBC manager GUI administration tools or by editing the user ODBC configuration file odbc ini See 3 3 5 ODBC Configuration Files for details When running an application that is meant to run as service or daemon you have to make sure that you create the user data source under the user name of the service or daemon If you intend a data source to be available for all users or to avoid permissions problems creating a system data source is a better
39. included as file LICENSE in the package s main directory Please note that using this software in a commercial environment is not free of charge You may use the software during an evaluation period as specified in the license but subsequent use requires the ownership of a Proof of Authorization which you can buy online from eGenix com Please see the eGenix com mx Extensions Page for details about the license ordering process By downloading copying installing or otherwise using the software you agree to be bound by the terms and conditions of the following eGenix com Commercial License Agreement mxODBC Python ODBC Database Interface 182 EGENIX COM COMMERCIAL LICENSE AGREEMENT Version 1 3 0 Introduction This License Agreement is between eGenix com Software Skills and Services GmbH eGenix com having an office at Pastor Loeh Str 48 D 40764 Langenfeld Germany and the Individual or Organization Licensee accessing and otherwise using this software in source or binary form and its associated documentation the Software Terms and Definitions The Software covered under this License Agreement includes without limitation all object code source code help files publications documentation and other programs products or tools that are included in the official Software Distribution available from eGenix com The Proof of Authorization for the Software is a written an
40. is and thus make these columns types useable as storage facility for arbitrary binary data Note that for mxDateTime input objects seconds rounding is applied just like for SQL TIMESTAMP SQL types For DateTimeDelta input objects seconds are truncated to whole seconds SOL TLNYLNT SQL SMALLINT SQL INTEGER SQL BLIT Integer or any other object which can be converted to a Python integer Conversion from the Python integer a C long to the SQL type is left to the ODBC driver manager so expect the usual truncations SQL BIGINT Long integer or any other object which can be converted to a Python long integer Conversion to and from the Python long integer is done directly if possible or via the string representation if the C data types are not sufficient to hold the numeric data If mxODBC has to use the string representation for interfacing you may receive errors indicating truncation or errors because the database sent string data that cannot be converted to a Python long integer Not all SQL databases implement this type or impose size limits SOL DECIMAL SQL NUMERIC Python decimal Decimal or Float or any other object which can be converted to a Python float Conversion from the Python float a C double to the SQL type is left to the ODBC driver manager so expect the usual truncations Python decimals are passed to that database as strings so no truncation or loss of precisi
41. manager Driver Notes Because of deficiencies in the PostgreSQL ODBC drivers mxODBC operates in Python type binding mode The ODBC driver still has problems with a few important data conversion e g it doesn t properly quote binary data which makes it difficult to send receive binary data Native Unicode data is not supported by the driver You can use the auto transcoding feature of mxODBC with UTF 8 as encoding to work around this The driver only supports forward scrolling with relative increments of 1 Other values result in a driver error As a result only cursor scrol1l 1 can be used Example Configuration for Unix Add a PostgreSQL driver section to the odbcinst ini file the location of the driver file may be different on your system ODBC Drivers PostgreSQL Installed PostgreSQL Description PostgreSQL ODBC Driver Driver usr local postgresgl lib psqlodbcw so setup Edit the odbc ini file based and add a postgresql section the location of the driver file may be different on your system be sure to use the Unicode variant which ends with w so It is also necessary to point LD LIBRARY PATH to the directory where the driver itself is located postgresql Driver usr local postgresgl lib psqlodbcw so Database mydb ServerName postgresql example net Port 5432 Debug 0 Optimizer 0 CommLog 0 ReadOnly 0 SSLmode require ByteaAsLongVarBinary 1 TextAsLongVar
42. mxODBC Notes General Recommendations e Please always use the DriverConnect API to connect to the data source if you need to pass in extra configuration information such as names of log files etc mxODBC Python ODBC Database Interface 152 When interfacing to MySQL using the MySQL ODBC driver we have observed problems with using Unicode statements passed to cursor execute when using iODBC 3 52 5 These problems appear to be related to iODBC As work around you can use unixODBC which works fine with Unicode statements You may experience problems when trying to connect to MySQL via MyODBC hooked to iODBC in case you are using the binary RPMs available from www mysq com For some reason the MyODBC driver does not reference the MySQL shared libs it needs to connect to the MySQL server and there s no way to tell iODBC to load two shared libs Here s a hack which will allow you to create an import lib which solves the problem on Linux rm E usr local lib libmyodbc so ld shared whole archive usr local lib libmyodbece 2 50 34 50 usr lib libmysglclient so 10 o usr local lib libmyodbc so ldconfig 64 bit Platforms You may run into problems with iODBC since it uses 64 bit SQL Unicode types Most ODBC drivers follow the Windows standard of using 32 bit Unicode types Support for Unicode with iODBC is therefore limited You may also run into problems with ODBC drivers compiled against unixODBC While iODBC
43. mxODBC test script no longer expects the database to return rows in the same order as they were inserted into the tables Changed cursor statistics to default to accuracy SQL QUICK since the parameter was deprecated in ODBC3 and SQL ENSURE value doesn t comply to the Open Group standards mxODBC no longer supports being built without Unicode support Changes from 3 0 3 to 3 0 4 Fixed a problem with the Mac OS X builds not working on Intel Macs mxODBC Python ODBC Database Interface 174 Added platform detection code to the prebuilt archives so that mismatches between the downloaded version and the installation platform are not reported to the user instead of causing a compilation errors Changes from 3 0 2 to 3 0 3 Fixed a bug in print_resultset due to a missing import in one of the modules Added native iterator support to mxODBC cursor objects Added a note to the documentation on hidden module dependencies when wrapping mxODBC into applications using py2exe Fixed issues with prebuilt Mac OS X builds not installing on some Mac OS X versions Changes from 3 0 1 to 3 0 2 mxODBC now has better support for using TEXT and VARCHAR columns with binary data esp for database drivers which require the Python type binding mode such as the FreeTDS ODBC driver Fixed a problem with the prebuilt packages not installing on Mac OS X Corrected version number of mx ODBC to show 3 0 2 instead of 2 1 0 Added work around for
44. normally use the mx ODBC Windows subpackage to access the Windows ODBC manager on Unix this would typically be the mx ODBC iODBC mx ODBC unixODBC or the mx ODBC DataDirect package depending on which of these Unix ODBC managers you have installed Each of these subpackages behaves as if it were a separate Python database interface so you actually get more than just one interface with mxODBC The advantage over other Python database interfaces is that all subpackages share the same logic and programming interfaces so you don t have to change your application logic when moving from one subpackage to another This enables programs to run more or less unchanged on Windows and Unix for example As you may know there is a standard for Python database interfaces the Python Database API Specification or Python DB API for short Marc Andr Lemburg the author of the mxODBC package is the editor of this specification so great care is taken to make mxODBC as compatible to the DB API as possible Since some details cannot easily be mapped to the ODBC API there are however a few deviations from the standard Section 5 1 mxODBC and the Python Database API Specification explains these in more detail mxODBC and the Python Database API Specification The mxODBC package tries to adhere to the Python DB API Version 2 0 in most details Many features of the old Python DB API 1 0 are still supported to maintain backwards compatibility and simplify por
45. object holding a time value from the given ticks value number of seconds since the epoch see the documentation of the standard Python time module for details TimestampFromTicks ticks This function constructs an mxDateTime DateTime object holding a time stamp value from the given ticks value number of seconds since the epoch see the documentation of the standard Python time module for details Usage of Unix ticks number of seconds since the Epoch for date time database interfacing can cause troubles because of the limited date range they cover Binary string This function constructs a buffer object pointing to the long string value On Python versions without buffer objects prior to 1 5 2 the string is taken as is STRING This type object is used to describe columns in a database that are string based SOL CHAR SOL BINARY BINARY This type object is used to describe long binary columns in a database SOL LONGVARCHAR SOL LONGVARBINARY e g LONG RAW BLOB TEXT NUMBER This type object is used to describe numeric columns in a database SOL DECIMAL SOL NUMERIC SOL DOUBLE SOL FLOAT SQL REAL SQL DOUBLE SOL INTEGER SOL TINYINT SQL SMALLINT SQL BIT SOL BIGINT DATE TIME This type object is used to describe date time columns in a database SOL DATE SOL TIME SQL TIMESTAMP ROWID This type object is used to describe the Row ID column in a database mxODBC does not support this sp
46. of 22P06 to Warning to make the PostgreSQL driver work with BYTEA and binary data e Added test cases for NTEXT and NCHAR to the test suite These two column data types are available in SQL Server and provide native Unicode storage e Added work around for bug in iODBC on 64 bit platforms it sends OxFFFFFFFF instead of 1 for NULL data columns e Added support for passing Unicode commands to executeXXX e Added optional support for the new Decimal type introduced in Python 2 4 recognize Decimal types on input e Added optional support for the datetime types introduced in Python 2 3 using the Python interface for Python 2 3 and the new C interface in Python 2 4 recognize datetime types on input e mxODBC now no longer request the rowcount per default after each executeXXX call some databases are very slow when it comes to finding out the true number of rows in the result set e Increased the default value of DEFAULT LONG SIZE to e g 32000 this can make a big difference since it avoids network roundtrips in networked setup Changes from 2 0 6 to 2 0 7 e Added Python 2 4 support e Added UCS2 and UCS4 builds of the package Changes from 2 0 5 to 2 0 6 e Added DB API attribute threadsafety 178 19 History amp Changes 179 e Added Python 2 3 support Changes from 2 0 4 to 2 0 5 e Fixed a bug in the native Unicode handling code for long object columns mxODBC now also supports reading and writing Unicode
47. of little value to Python applications DECIMAL DIGITS SMALLINT The scale of the column NULL is returned for data types where scale is not applicable NUM_PREC_ RADIX SMALLINT Either 10 or 2 or NULL If DATA_TYPE is an approximate numeric data type this column contains the value 2 then the COLUMN SIZE column contains the number of bits allowed in the column If DATA_TYPE is an exact numeric data type this column contains the value 10 and the COLUMN SIZE contains the number of decimal digits allowed for the column For numeric data types the database can return a NUM_PREC_RADIX of either 10 or 2 mxODBC Python ODBC Database Interface 108 Column Name Column Datatype Comment NULLABLE SMALLINT not NULL SQL NO_NULLS if the column does not accept NULL values REMARKS VARCHAR 254 May contain descriptive information about the column or NULL It is possible that no usable information is returned in this column due to optimizations COLUMN_ DEF VARCHAR 3 The column s default value If the default value is a numeric literal then this column contains the character representation of the numeric literal with no enclosing single quotes If the default value is a character string then this column is that string enclosed in single quotes If the default value a pseudo literal such as for DATE TIME and TIMESTAMP columns then this column contains the key
48. on a per cursor basis It takes the same values as the connection datetimeformat instance variable and defaults to the creating connection object s settings for connmectien Galeri merormar decimal Farmat Attribute to set the output format for decimal numeric columns on a per cursor basis It takes the same values as the connection decimalformat instance variable and defaults to the creating connection object s settings for connection decimalformat description This read only attribute is a sequence of 7 item sequences for operations that produce a result set which may be empty Each of these sequences contains information describing one result column name type code display size internal 5128 precision scale NULL Ok mxODBC Python ODBC Database Interface 116 This attribute will be None for operations that do not return rows or if the cursor has not had an operation invoked via the execute method yet mxODBC always returns None for display size and internal size This information can be obtained via connection gettypeinfo if needed The type code can be interpreted by comparing it to the type objects specified in the section 8 Type Objects and Constructors below mxODBC returns the SQL type integers in this field These are described in the section 8 Supported Data Types and are available through the sot singleton defined at module level MEessages This is a Python list object to which the stan
49. or services of Licensee or any third party The controlling language of this License Agreement is English If Licensee has received a translation into another language it has been provided for Licensee s convenience only Agreement By downloading copying installing or otherwise using the Software Licensee agrees to be bound by the terms and conditions of this License Agreement For question regarding this License Agreement please write to eGenix com Software Skills and Services GmbH Pastor Loeh Str 48 D 40764 Langenfeld Germany 20 Copyright License 187 EGENIX COM PROOF OF AUTHORIZATION 1 CPU License Example This is an example of a Proof of Authorization for a 1 CPU License These proofs are either wet signed by the eGenix com staff or digitally PGP signed using an official eGenix com PGP key License Grant eGenix com Software Skills and Services GmbH eGenix com having an office at Pastor Loeh Str 48 D 40764 Langenfeld Germany hereby grants the Individual or Organization Licensee Licensee lt name of the licensee gt a non exclusive world wide license to use the software listed below in source or binary form and its associated documentation the Software under the terms and conditions of this License Agreement and to the extent authorized by this Proof of Authorization Covered Software Software Name lt product name gt Software Version lt product version gt incl
50. other Python DB API compliant interface you should only use those interfaces which are mentioned in the Python DB API specification documents mxODBC and the ODBC Specification Since ODBC is a widely supported standard for accessing databases it should in general be possible to use the package with any ODBC version 2 0 3 52 compliant ODBC database driver manager mxODBC prefers ODBC 3 x over 2 x in case the driver manager supports both versions of the standard Full access to most ODBC features The ODBC API is very rich in terms of accessing information about what is stored in the database mxODBC makes most of these APIs available as additional connection and cursor methods and these can be put to good use for database and schema introspection Since many of the parameters and names of the ODBC function names were mapped directly to Python method names by dropping the SQL prefix and converting them to lower case we kindly refer you to the Microsoft ODBC Documentation and your ODBC driver documentation for low level details on the various APIs mxODBC Python ODBC Database Interface 5 3 5 3 1 5 3 2 60 You also can access the MS ODBC online reference from the Microsoft MDAC web site Please note that not all ODBC drivers and databases support the complete set of available introspection parameters When using them please make sure that the databases supported by your application do implement the parameters used in yo
51. provided by the dictionary sqltype which is provided by all subpackages Note You may run into problems when using the tuple versions for date time timestamp arguments This is because some databases notably MySQL want these arguments to be passed as strings mxODBC does the conversion internally but tuples turn out as 1998 4 6 which it will refuse to accept The solution use DateTime Delta instances instead These convert themselves to ISO dates times which most databases including MySQL do understand To check the ODBC driver manager capabilities and support for the above column types run the included mx ODBC Misc test pyc test script 9 DB API Type Objects and Constructors 135 DB API Type Objects and Constructors Since many database have problems recognizing some column s or parameter s type beforehand e g for LONGs and date time values the Python DB API provides a set of standard constructors to create objects that can hold special values When passed to the cursor methods the module can then detect the proper type of the input parameter and bind it accordingly In mxODBC these constructors are not needed it uses the objects defined in mxDateTime for date time values and is able to pass strings buffer and memoryview objects to LONG and normal CHAR columns without problems You only need them to write code that is portable across database interfaces A Cursor Object s description attribute returns information abo
52. scrolling is not needed by the application since fetch operations on In mxODBC 3 3 this will change to forward only cursors 66 5 mxODBC Overview 5 0 static cursors can result in a significant slow down compared to forward only cursors Adjusting the default cursor type can be done on a per connection basis connection mx ODBC Windows DriverConnect connection curtsortype mx ODBC Windows 5QL CURSOR FORWARD ONLY All cursors created on connection will then default to forward only cursor type Performance Hint In tests we have seen slow downs from 2 3x for average queries up to 300x for simple ones when using static cursors compared to forward only ones Oracle mxODBC uses forward only cursors as default since using other types can cause segfaults in the ODBC driver PostgreSQL mxODBC defaults to forward only cursors since the driver becomes unusable with other settings IBM DB2 DB2 supports static cursors so mxODBC 3 2 default to static cursors for this database backend There is a performance penalty of about 2x in using static cursors If you don t need scrolling support for the cursors we therefore recommend adjusting the default to forward only cursors connection mx ODBC Windows DriverConnect connection cursortype mx ODBC Windows SQL CURSOR FORWARD ONLY All cursors created on connection will then default to forward only cursor type Note that with forwar
53. style and also used as native database binding style by MS SQL Server and IBM DB2 Parameters in SQL statements used on cursor execute methods are marked with the question mark letter and the variables are bound to these parameter locations using a positional mapping Parameter values for a SQL statement must be specified as sequence normally a list or a tuple Example SELECT FROM MyTable WHERE A AND B used with a parameter tuple 1 2 would result in the database executing the query SELECT FROM MyTable WHERE A 1 AND B 2 7 mxODBC Cursor Objects named The named parameter binding style is used by the native database interfaces of e g Oracle Parameters in SQL statements used on cursor execute methods are marked with a colon followed by a name e g a or 1 The variables are bound to these parameter locations using a name based mapping Parameter values for a SQL statement must be specified as mapping normally a dictionary and are bound to the locations based on the names used in the SQL statement Example SELECT FROM MyTable WHERE A a AND B b used with a parameter dictionary a 1 b 2 would result in the database executing the query SELECT FROM MyTable WHERE A 1 AND B 2 rowcount This read only attribute specifies the number of rows that the last execute produced for DQL statements like select or affected for SQL DML statements like update or insert The attrib
54. the cursor datetimeformat Such changes do not affect the connection or any other cursor objects created on the connection Using cursors on a closed connection will result in a ProgrammingError to be raised Using multiple Cursor Objects on a single Connection Depending on the capabilities of the database and the used ODBC driver you can have multiple cursors open on a single connection and execute queries and commands on each at will This makes it possible to e g prepare and then cache often used commands 7 mxODBC Cursor Objects 7 2 7 3 7 3 1 7 4 85 Subpackage Support Cursor objects are supported by all subpackages included in mxODBC The extent to which the functionality and number of methods is supported may differ from subpackage to subpackage so you have to verify the functionality of the used methods esp the catalog methods for each subpackage and database that you intend to use Cursor objects as context managers Please see section 6 5 1 Introduction to Context Managers for an introduction to context managers and the Python with statement Using cursor objects as context objects Cursor objects implement this API and use it to automatically close the cursor and freeing resources in the ODBC driver when leaving a with block Instead of writing cursor connection cursor Leys cursor execute INSERT INTO table VALUES 1 2 si other tasks finally cursor close you can w
55. the error handler connection errorhandler myerrorhandler If you need to catch errors or warnings at connection time you can use the optional keyword argument errorhandler to have the error handler installed early enough to be able to deal with such errors or warnings connection mx ODBC Windows DriverConnect DSN test errorhandler myerrorhandler mxODBC Python ODBC Database Interface 11 11 1 144 mxODBC Functions mxODBC includes a few helper functions and generic APIs which aid in everyday ODBC database programming or allow introspection at the ODBC manager level The next sections describe these functions in detail Subpackage Functions For some subpackages mxODBC also defines a few helpers which you can use to query additional information from the ODBC driver or manager These are available through the subpackage e g as mx ODBC Windows DataSources DataSources This helper function is only available for ODBC managers and some ODBC drivers which have internal ODBC manager support e g IBM s DB2 ODBC driver and allows you to query the available data sources It returns a dictionary mapping data source names to descriptions Notes Older versions of unixODBC had a bug in some versions which makes the manager only return information about data sources on the first call to this function Older versions of ODBC truncated the descriptions to two Characters getenvattr option Returns the given
56. the file is located in Library ODBC odbcinst ini This INI file provides one INI section per installed ODBC driver In addition to the data source sections there are also a number of higher level sections ODBC This section is used to configure driver related ODBC manager settings such as ODEC call tracing The settings in this section apply to all data sources mxODBC Python ODBC Database Interface 28 iODBC needs this section in the odbc ini file unixODBC in the odbcinst ini file More recent DataDirect ODBC manager versions accept the section in both files older version need it in the odbc ini file ODBC Drivers This section contains one entry per configured and installed ODBC driver mapping the driver name to the string Installed Example ODBC Trace O TraceFile tmp odbc log ODBC Drivers OracleInstantClient Installed OracleInstantClient Description Oracle 11g ODBC Driver Driver usr local oracle instantclient 11 2 libsgora so 11 1 setup FileUsage CPTimeout CPReuse ll Il odbcinst ini User ODBC Driver Configuration This INI file provides ODBC driver information on a per user basis It uses the same structure as the system wide etc odbcinst ini file The drivers defined in this file are only visible to the user account for which it is defined Environment Variables ODBCINI and ODBCINSTINI In order to override the default search path used by the ODBC manager
57. the result set after opening it are visible on the next fetch operation Please note that using cursor types other than SQL CURSOR FORWARD ONLY may have a significant effect on the performance of fetch operations Default Cursor Type mxODBC 3 2 tries to configure the cursors in a way so that scrollable cursors can be supported by the database If it finds that a database supports static cursors it configures the cursor to use the cursor type SOL CURSOR STATIC You can check the default cursor type by inspecting the cursortype attribute on a newly created connection object Connection mx ODBC Windows DriverConnect if Connection cursortype me ODBC Windows SOL CURSOR STATIC print Connection defaults to static cursors Forward Compatibility Notice Please note that mxODBC 3 3 will no longer try to setup static cursor per default Instead mxODBC will use the ODBC default which is SQL CURSOR FORWARD ONLY Database Specific Cursor Type Notes MS SQL Server MS SQL Server supports static cursors so mxODBC 3 2 default to static cursors for this database backend MS SQL Server supports backwards scrolling and other more advanced scrolling modes when using static cursors With forward only cursors these scrolling capabilities are no longer available The attribute rownumber also gives wrong results with forward cursors We still recommend setting the cursortype to SQL CURSOR FORWARD ONLY in case result set
58. the same sqicmd is used but different parameters are bound to it e g in loops iterating over input data items Use executemany if you want to apply the sq1cma to a sequence of parameters in one call e g to insert multiple rows in a single call sqlcmd may be a Unicode object in case the ODBC driver and or database support this direct specifies whether to use direct unprepared execution or not see executedirect for details It defaults to 1 meaning that direct execution is used if no parameters are given non direct otherwise Return values are not defined executedirect sqlcmd parameters This method works just like execute except that no prepare step is issued and the sqicmd is not cached This can result in better performance with some ODBC driver setups but also implies that Python type binding mode is used to bind the parameters All SQL command parsing is then pushed from the client side to the server side sql1cma may be a Unicode object in case the ODBC driver and or database support this Return values are not defined executemany sqlcmd batch direct 0 Prepare a database operation query or command and then execute it against all parameter sequences found in the sequence batch The same comments as for execute also apply accordingly to this method If the optional integer direct is given and true mxODBC will not cache the sqlcmd but submit it for one time execution to the
59. together with a unixODBC 2 3 or later ODBC manager The Netezza driver will also work with the DataDirect ODBC manager that ships with the Netezza driver If you use this setup please interface to the DataDirect ODBC manager using the mx ODBC DataDirect subpackage Also note that when using the DataDirect ODBC Manager we have seen segfaults related to the odbc ini file being too big You can work around this by either keeping the file short or by setting up a separate netezza odbc ini file and pointing the driver manager to it using the ODBCINI environment variable Netezza and Unicode Unicode data exchange doesn t work well when using the Netezza driver with the DataDirect manager The unixODBC manager interface does not have these issues and works fine with Unicode if the Netezza driver is configured for UTF 16 data using the UnicodeTranslationOption utf16 driver configuration option Example Configuration for Unix e Edit your odbcinst ini file and add the Netezza driver the location of the driver and setup file may be different on your system ODBC Drivers NetezzaSQL Installed NetezzaSQL Driver Jusr local nz 1i1664 libnzodbc so Setup usr local nz 1ib64 libnzodbc so APILevel 1 ConnectFunctions YYN mxODBC Python ODBC Database Interface 4 11 56 Description Netezza ODBC driver DriverODBCVer 03 00 DebugLogging false LogPath tmp For unixODBC use the following setting Unicod
60. types via string conversion e Full Python Support mxODBC works with Python 2 4 2 7 on 32 bit and 64 bit platforms e Highly Portable Codebase in addition to the already supported platforms for mxODBC eGenix com provides custom porting services for more exotic platforms e Easy installation using Windows installers egg file package or our Python distutils compatible prebuilt Python packages e Easy configuration use ODBC manager GUI tools for easy configuration of ODBC data sources then access these data sources by name from Python or use a connection less way to connect to databases by specifying the driver name and database details in the application 1 3 Requirements mxODBC needs these environment on Windows Unix or Mac OS X for successful installation Windows e All Windows platforms starting with Windows 2000 are supported mxODBC Python ODBC Database Interface Unix Python 2 4 or later needs to be installed and working The Windows version of the mxODBC uses the Windows ODBC manager as ODBC manager so you have to configure your ODBC data sources using its GUI interface which is available through the system settings folder Alternatively you can choose to use a DSN less setup which defines all connection details in the connection string You should setup at least one configured and running ODBC data source for testing purposes SuSE and RedHat Linux distributions for x86 and x86_64 AMD64 EM64T proc
61. will not change the decimal format for existing cursors using this connection driver name String identifying the ODBC driver driver version String identifying the ODBC driver version encoding Read write attribute which defines the encoding to use for converting Unicode to 8 bit strings and vice versa If set to None default Python s default encoding will be used otherwise it has to be a string providing a valid encoding name e g latin 1 or utf 8 6 mxODBC Connection Objects errorhandler Read write attribute which defines the error handler function to use If set to None the default handling is used i e errors and warnings all raise an exception and get appended to the messages list An error handler must be a callable object taking the arguments connection cursor errorclass errorvalue where connection is a reference to the connection cursor a reference to the cursor or None in case the error does not apply to a cursor errorclass is an error class which to instantiate using errorvalue as construction argument See the Error Handlers section 10 for details license String with the license information of the installed mxODBC license MBSSdqes This is a Python list object to which mxODBC appends tuples exception class exception value for all messages which the interfaces receives from the underlying ODBC driver or manager for this connection The list is cleared automatically by all c
62. 0 Thread Safety amp Thread Friendliness ee eeeeeeeeeeeeees 61 CONNECTIONS ANG CULSOMS sic aun toute esa icon aecisiaronAcauauiade 61 Unlocking the Python Global Interpreter Lock GIL ooooo oo 61 Threadine SU pOr ada 61 Transaction SUPDO Fleitas 61 AUC OMMI oa a A 61 Manual COMMI Cessa oi Se Ss tna a E a Ste assay Ria aoa ae 62 Transaction Startana Enri ds 62 Data Sources without Transaction Suppott ccceeeeeesseeeeeeeeees 62 mxODBC Python ODBC Database Interface 5 5 3 5 6 5 6 1 5 6 2 5 7 5 7 1 5172 DSa 5 8 5 8 1 6 1 6 2 6 3 Adjusting the Connection Commit Mode ssssssesssssssssreesssssssssreesss 63 SOred Procedure Sandoval 63 Input Output and Output Parameters coooooocccccccncnonoocnnnnncnnnnnanancnanancnnns 63 Using result sets to pass back output data eee eeeeeeeeeeeeeeees 64 Oracle Ref Cursors make this asy cccccceeesssssneceeeeeeeeeeeseeeees 64 SQL Output Statements in Stored Procedures occccccnnnnoccnncnnnnnnnanns 65 ODBC CUISOR VY DGS us iia lada 65 Adjusting Inspecting the ODBC Cursor Type scccceeeeeessneeeeeeees 65 SQL CURSOR FORWARD ONLY ccccscsssssessssecessesesseeesseseeeeeeee 65 SQL CURSOR STATE 65 SOL CURSOR KEYSET DRIVEN crisi 66 SOLCURSOR DYNAMU Cut asun 66 Perault Cursor DEl 66 Database Specific Cursor Type Notes ocooooooccccccccncnonooccnncnccnnnnanancnnnancnnns 66 MOSOR E
63. 10 FailoverRetryCount 10 FetchBufferSize 64000 ForceWCHAR F Lobs T Longs I mxODBC Python ODBC Database Interface 4 3 2 42 MaxLargeData 0 MetadataldDefault F QueryTimeout T ResultSets T SQLGetData extensions F SQLGetData extensions T Translation DLL Translation Option 0 DisableRULEHint T UeeriD StatementCache F CacheBufferSize 20 UseOCIDescribeAny F e Using these settings you can then connect to Oracle using a simple connection string such as DSN oraclellgr2 UID username PWD password EasySoft ODBC Driver for Oracle Homepage http www easysoft com OpenLink ODBC Driver for Oracle Homepage http www openlinksw com DataDirect ODBC Driver for Oracle Homepage http www datadirect com Actual Technologies Mac OS X ODBC Driver for Oracle Homepage http www actualtech com When using the driver on Mac OS X 10 6 Snow Leopard be sure to use version 3 0 9 or higher since earlier versions had a problem with fetching data General Notes Oracle tnsnames ora file When connecting to Oracle database you typically have to provide a tnsnames ora file which has the network connection information of your Oracle database servers If you want to use a different file location be sure to set the environment variable TNS ADMIN to the path of the tnsnames ora file 4 Accessing Popular Databases 4 4 IBM DB2 4 4 1 Available ODBC Drivers 43 IBM ODBC Driver
64. 6 executedirect sqlcmd parameters cccccnnonoccconcnonnnonccnnnnnnnnnn 87 executemany sqicmd batch direct 0 0 87 A 87 fetchmany size Cursor arraySiZe coccooooccccnnccnnnnonoccnnnnnnnnns 88 Etchone Utada 88 Un E E D Sedaris bacadiat Tae 88 getcolattribute position info_id cccccccnnnnccconnncnnnnnnccacnanannnnos 88 PECUNIAE eaer pi da 90 PCLCULSOFODHOM OPUON esnean diios 90 NEXU cas sate sucies N as vdobesdauaieueessassseuniays aaasnseiee 91 A LG einai te ielareansbistaiats tetebectusshaatacaaaiaseae kysyase hale nuantmy tioas 91 prepare salen aia ia 92 scroll value MOde relative ooocooooccnoononoccnnoccnnoronanccnnocononos 92 SElCONVE ter CONVE rs iawn iio 92 SELCUFSOF MAINE MAING anar AEE 92 Setcursoroption Option value 2 2 eeeeeeeseeeeeeeeeeeeessseeeeeeeeees 93 SSEUMPULSIZES SIZES aia 94 setoutputsize sizel column sasun 94 OOE a er rns rr ee ere errr 94 se CEE A cenacaveomnatacuchetuauenane a one darn 94 exit__ exc_type exc_value exe tb ineeie 94 Catalog Methods ata iia 95 Commomniitenace spice dd 95 A ano cue a acraaie S E utes 95 Search Pattern Parameters aio 95 Case sensitivity of Search Patterns ooooooocccnnccnononccnnnnnnnnnnanaannnnos 95 Switching between Search Patterns and Identifier Matching 96 UNICOS na 96 Available Catalog Methods resina iici n 96 columns qualifier None owner None table None CONO sa dl 96 columnprivileges qualifier Non
65. 7 mxODBC Cursor Objects Option Comment Possible values SOL ASYNC ENABLE OFF default SOL ASYNC ENABLE ON SQL ASYNC ENABLE DEFAULT SQL ATTR MAX LENGTH Returns the length limit for fetching column data Possible values Any positive integer or SQL MAX LENGTH DEFAULT no limit SQL ATTR MAX ROWS Returns the maximum number of rows a fetchall command would return from the result set Possible values Any positive integer or SQL MAX ROWS DEFAULT no limit SOL ATTR NOSCAN Check whether the ODBC driver will scan the SQL commands for ODBC escape sequences or not Possible values SQL NOSCAN_OFF default SQL NOSCAN_ ON SQL NOSCAN DEFAULT SQL ROW NUMBER Returns the row number of the current row in the result set or 0 if it cannot be determined The method returns the data as 32 bit integer It is up to the caller to decode the integer using the Sot defines next Works like fetchone to make cursors compatible to the iterator interface new in Python 2 2 Raises a StopIteration at the end of a result set nextset This method will make the cursor skip to the next available set discarding any remaining rows from the current set 91 mxODBC Python ODBC Database Interface If there are no more sets the method returns None Otherwise it returns a true value and subsequent calls to the fetch methods will return rows from the next result set An Err
66. A TAR 43 IBM ODBC Driver for Unix Windows DB2 ServerS cccooocccnccnno 43 Example Configuration for UNIX sssssessssssssssseesssssssssreesssssssssees 43 IBM ODBC Driver for iSeries AS 400 DB2 ServerS cccooocccnncnnoo 43 OpenLink ODBC Driver for DB2 cccccnnnnnncccnccccnnononccnnnncnonnnanannnnos 43 DataDirect ODBC Driver for DB2 oocccccnnccnnnnnocnnnonicocnnonanonnnnanonos 43 Genera Notes oaas a a T A S 44 ODBC API Extensions and the IBM CLl ooccconcccnnnnnccnnnnnoccnnnnnnccnnnns 44 Configuring Database ACCesS ei 44 Environment Variables on UNIX cccconcccnncnnccnnnnnncnnnonaconnnnnacononanonos 44 Linker Pastas dc 44 Database Setup for ODBC ACCESS cccocoooocconcccconononoonnoncccnnnnnnnaccnnncnnnn 45 Static vs forward only CUTSOTS yes 45 PP e dors 45 Available ODBC Drivers ni ivi 45 Sybase ASE ODBE Oliver rra ea e 45 NULL issues with Sybase ODBC driver coooooooocccnccccnnononccncnnnnnnns 46 BIGINT columns can cause data CorruptiON cccccccnnonccnncnnnnns 46 POFIVETYIN Elda 46 Example Configuration for UNiX ooooccccncccnnnonooocnnnnnnnncnnnacncnncncnnns 46 EasySoft ODBC Driver for SybaS oooooooococncccnncoooooccnncncnnnnnnnancnancnnon 47 OpenLink ODBC Driver for Sybase cccocoooocccnccccnnnooooccconcconnnanannnnos 47 mxODBC Python ODBC Database Interface 4 6 4 6 1 4 7 4 7 1 4 7 2 4 8 4 8 1 4 8 2 4 9 4 9 1 4 10 4 10 1 DataDirect ODBC Driver for SybaS
67. ALLINT Contains SQL TRUE if a column of this data type is automatically set to a unique value when a row is inserted otherwise contains SQL FALSE LOCAL_TYPE_NAME VARCHAR 1 28 This column contains any localized native language name for the data type that is different from the regular name of the data type If there is no localized name this column is NULL This column is intended for display only The character set of the string is locale dependent and is typically the default character set of the database MINIMUM_ SCALE INTEGER The minimum scale of the SQL data type If a data type has a fixed scale the MINIMUM_ SCALE and MAXIMUM SCALE columns both contain the same value NULL is returned where scale is not applicable MAXIMUM SCALE INTEGER The maximum scale of the SQL data type NULL is returned where scale is not applicable If the maximum scale is not defined separately in the database but is defined instead to be the same as the maximum length of the column then this column contains the same value as the COLUMN SIZE column mxODBC Python ODBC Database Interface 104 Column Name Column Datatype Comment SQL DATA TYPE SMALLINT not NULL SQL data type This column is the same as the DATA _TYPE column SQL DATETIME SUB SMALLINT The subtype code for datetime data types SQL CODE DATE SQL CODE TIME SQL CODE_ TIMESTAMP For all other data type
68. ARAM_INPUT_OUTPUT this parameter is an input output parameter SQL PARAM_OUTPUT this parameter is an output parameter 7 mxODBC Cursor Objects 107 Column Name Column Datatype Comment SQL RETURN_VALUE the procedure column is the return value of the procedure SQL RESULT_COL this parameter is actually a column in the result set DATA TYPE SMALLINT not NULL SQL data type of column TYPE_NAME VARCHAR 128 not NULL Character string representing the name of the data type corresponding to DATA_TYPE COLUMN SIZE INTEGER If the DATA_TYPE column value denotes a character or binary string then this column contains the maximum length in characters for the column For date time timestamp data types this is the total number of characters required to display the value when converted to character For numeric data types this is either the total number of digits or the total number of bits allowed in the column depending on the value in the NUM_PREC_RADIX column in the result set BUFFER_LENGTH INTEGER The maximum number of bytes for the associated C buffer to store data from this column if SQL C_DEFAULT were specified on the SOLBindCol SOLGetData and SOLBindParameter ODBC calls used internally by mxODEC This length does not include any null terminator For exact numeric data types the length accounts for the decimal and the sign Note This column is
69. ARS feature of SQL Server Native Client which enables working with multiple active result sets on the same connection from mx ODBC Manager import DriverConnect SOL options SQL COPT SS MARS ENABLED SQL MARS ENABLED YES db DriverConnect DSN mssqlserver2008 UID sa PWD dbsOR X9 rxD connection options options 6 mxODBC Connection Objects 6 4 6 4 1 71 The DriverConnect API is only available if the ODBC driver or ODBC driver manager supports this It is available on all supported ODBC driver manager subpackages such as the one for Windows and ODBC unixODBC DataDirect on Unix platforms See the subpackages section for details ODBC asa user password clear auto commit l errorhandler None Is just an alias for Connect needed for Python DB API 1 0 compliance Default Transaction Settings ODBC usually defaults to auto commit meaning that all actions on the connection are directly applied to the database Since this can be dangerous mxODBC defaults to turning auto commit off at connection initiation time provided the database supports transactions All connection constructors implicitly start a new transaction when connecting to a database in transactional mode When connecting to a database with transaction support you should explicitly do a rollback or commit prior to closing the connection mxODBC does an automatic rollback of the transaction when the connection is closed if the drive
70. BINARY String These can contain embedded 0 bytes and SQL VARBINARY other special characters SOL LONGVARBINARY BLOB or LONG BYTE Handling of these column types is in SQL database dependent Please refer to the database s documentation for details SOL TINYINT Integer or Bits are converted to Python integers O SQL SMALLINT Long Integer and 1 resp SOL INTEGER ees Unsigned short integers are fetched as Python integers unsigned integers as Python long integers SQL BIGINT Long Integer mxODEC tries to fetch the long integer data directly and falls back to using string interfacing if the platform does not provide the necessary C types for this SQL DECIMAL Float or In FLOAT DECIMALFORMAT mode SQL NUMERIC decimal Decimal default mxODBC will fetch the numeric data as Python float Since Python stores floats as double precision C float rounding errors may occur during the mxODBC Python ODBC Database Interface SQL Type Python Type Comments conversion In DECIMAL _DECIMALFORMAT mode mxODBC will fetch the numeric data as string and create a Python decimal Decimal instance from it which is then returned This avoids any rounding errors SOL REAL SOL ELOAT SOL DOUBLE Float Python stores floats as double precision C float so rounding errors may occur during the conversion SQL DATE DateTime instance or datetime date instance or ticks or year month day or String
71. C This length does not include any null terminator For exact numeric data types the length accounts for the decimal and the sign Note This column is of little value to Python applications DECIMAL DIGITS SMALLINT The scale of the column NULL is returned for data types where scale is not applicable PSEUDO COLUMN SMALLINT Indicates whether or not the column is a pseudo column Possible values SQL PC_NOT PSEUDO SQL PC_ UNKNOWN SQL PC_PSEUDO 7 mxODBC Cursor Objects statistics qualifier None owner None table None unique SQL INDEX ALL accuracy SQL QUICK Query the data source for information on statistics and available indexes for a given table The table parameter is mandatory Possible input values for unique SOL INDEX UNIQUE Return only unique indexes SOL INDEX ALL Return all indexes Possible input values for accuracy SOL ENSURE The data returned for CARDINALITY and PAGES must be current and accurate This mode is not widely supported and its use is discouraged SQL QUICK The data for CARDINALITY and PAGES is returned if available but must not be current This method is mainly useful for identifying the indexes of a table in a database schema The catalog method generates a result set having the following schema Column Name Column Datatype Comment TABLE_CAT VARCHAR 128 Always NULL TABLE_SCHEMA VARCHAR 128 The name of the schema c
72. C 2 x See the ODBC Documentation for details 5 mxODBC Overview 5 4 5 4 1 5 4 2 5 4 3 3 9 5 5 1 61 Thread Safety amp Thread Friendliness mxODBC itself is written in a thread safe way There are no module globals being used and thus no locking is necessary Connections and Cursors In general when using a separate database connection for each thread you shouldn t run into threading problems If you do it is more likely that the ODBC driver is not 100 thread safe and thus not 100 ODBC compatible Note that having threads share cursors is not a good idea there are many very strange transaction related problems you can then run into Unlocking the Python Global Interpreter Lock GIL Many of the underlying ODBC SQL function calls are wrapped by macros unlocking the global Python interpreter lock before the call and regaining that lock directly afterwards The most prominent of those are the connection APIs and the execute and fetch APIs Unlocking the interpreter lock during long SQL function calls gives your application more responsiveness This is especially important for GUI based applications since no other Python thread can run when the global lock is acquired by one thread Threading Support mxODBC will only support threading if you have built Python itself with thread support enabled Python for Windows and most recent Python versions for Unix have this enabled per default Try python c import thre
73. CPU makes use of more than two 2 processors Licensee must obtain additional CPU licenses to cover the total number of installed processors The number of cores per processor does not count towards this license limitation Virtual machines always count as one 1 CPU If a Developer CPU is used by more than one developer Licensee must obtain additional Developer CPU licenses to cover the total number of developers using the CPU 20 Copyright License 183 Commercial Environment refers to any application environment which is aimed at directly or indirectly generating profit This includes without limitation for profit organizations private educational institutions work as independent contractor consultant and other profit generating relationships with organizations or individuals Governments and related agencies or organizations are also regarded as being Commercial Environments Non Commercial Environments are all those application environments which do not directly or indirectly generate profit Public educational institutions and officially acknowledged private non profit organizations are regarded as being Non Commercial Environments in the aforementioned sense Educational Environments are all those application environments which directly aim at educating children pupils or students This includes without limitation class room installations and student server installations which are intended to be used by s
74. DBC Driver for SQL Server Homepage http www openlinksw com DataDirect ODBC Driver for SQL Server Homepage http www datadirect com mxODBC Python ODBC Database Interface Actual Technologies Mac OS X ODBC Driver for SQL Server Homepage http www actualtech com When using the driver on Mac OS X 10 6 Snow Leopard be sure to use version 3 0 9 or higher since earlier versions had a problem with fetching data FreeTDS Unix ODBC Driver for SQL Server Homepage http www freetds org Tested with FreeTDS 0 91 ODBC driver compiled against unixODBC 2 3 1 The FreeTDS ODBC driver implements the client side of the TDS wire protocol used by Sybase ASA and Microsoft SQL Server installations It allows you to directly connect to a SQL Server database from a Unix machine Driver Limitations e The FreeTDS ODBC driver version 0 91 introduces Unicode support for the first time in its version history The previous stable version 0 82 did not have Unicode support We ve had most success using the NATIVE UNICODE_STRINGFORMAT mode e Most other operations work as expected but please note that the driver is still under heavy development in some areas You should test it thoroughly before using it on a production system e The FreeTDS website mentions that the driver has some restrictions Please see the FreeTDS user guide for details e Be sure to use the same ODBC manager with FreeTDS as the one you have compiled it with If you
75. Direct ODBC driver manager e Native Unicode is supported by the driver manager combination setup with the CharacterSet UTF16 setting in the odbc ini section for Teradata e Trying to use the Teradata ODBC driver with unixODBC or iODBC usually results in an immediate segfault e If you use the Teradata ODBC driver in combination with the DataDirect ODBC manager be sure to keep the odbc ini file short With longer odbc ini files the combination will segfault e The Teradata driver only supports relative forward scrolling in the result set Backwards scrolling is not supported e Teradata has the tendency to return non ordered result sets in random order This is due to the way the database works internally If you need to rely on a reproducible result set order please add an ORDER By clause to the SELECT statements as necessary mxODBC Python ODBC Database Interface 54 Example Configuration for Unix Edit your odbcinst ini file and add the Teradata driver the location of the driver and setup file may be different on your system ODBC Drivers Teradata Installed Teradata Driver opt teradata client 13 10 odbc 64 lib tdata so APILevel CORE ConnectFunctions YYY DriverODBCVer 3 51 SQLLevel 1 Edit your odbc ini file and add a Teradata section the location of the driver may be different on your system It is also necessary to point LD LIBRARY PATH to the directory where the driver itself is l
76. E WARNINGFORMA isis psss di 147 FLOAT DECIMALFORMAT DECIMAL _DECIMALFORMAT 148 HAVE UNICODE SUPPORT ccccssscsssecessecerseceesecerseceesesaveeee 148 A pea oe ena es 148 12 2 mx ODBC Globals and Constants csceececesceceeees 148 Error Warning InterfaceError DatabaseError DataError OperationalError IntegrityError InternalError ProgrammingError NOMS UD DORE drops oia cs 148 13 mx ODBC Subpackage sssccscssscrevseees 149 13 1 SUDPACKase NOTES iii 149 mxODBC Python ODBC Database Interface 13 1 1 13 1 2 13 2 13 3 13 3 1 133052 13 3 3 13 4 13 4 1 13 5 13 5 1 13 6 13 6 1 13 7 14 14 1 14 2 Windows Platform Notes ccccceccsceccececcccecsceccccceceececeecscescscesceces 149 Unx Plathorna c NOLS a do a et 149 mx ODBC Manager Generic ODBC Driver Manager 149 Windows Plato Masini 150 Uni Plato MS nd 150 mx ODBC Windows Windows ODBC Driver Manager 150 Connecting toa Data as Criada 150 supported Data PES osa 151 File Data SOURCES ii la ad dde dd 151 mx ODBC IODEC ODBC Driver Manager 151 NS O A 151 General RecommendatiONS oocooccocnocnncnncnnonnnonoconcnncnnccoccnccnonnnos 151 6A DIE PlatO MS ira an 152 mx ODBC unixODBC unixODBC Driver Manager 152 Notes o a a e sa ae sa a atten cena an ea is 153 General RECOMMENCAtIONS ccecceccecceccescesccsccsccscceccscceceeses 153 G4 DICPlaU Or sc
77. ING aos 78 driver Verid io 78 CAU and 78 Erro rnanole a 79 MENS iii 79 MESES 79 PAUTA Er 79 amar deta 79 Tamed sinr a 79 SAO IO 80 EIGHTBIT_STRINGFORMAT default oooooonnnnnnnnnnnnnnoooooo000mmm0 80 MIXED STRINCEONMA TN 80 UNIGODE STRINGFONRMA Li 80 NATIVE UNICODE STRINGFORMAT ccccccssessecseseeseceeseceeeeeeees 81 mestampres Olsen prcd rn 81 Wal MIMGlOMM als nar acia adobo 82 ERROR WARNINGFORMAT default cccccceeeeeeeeeeeeeseeeeees 82 WARN WARNINGFORMAT susana avon svacntansiens 82 IGNORE _WARNINGFORMA Tooccoooccconcccconcccnonccononocononcnononcccnoninos 82 Additional ALUM ULES Sia 82 mxODBC Cursor Objects cccccsssssssseeeee OF Relationship between Cursors and Connections 84 Dependency on the Connection Object occcccnnnnocccnnnccnnnnncccccnnnncnnns 84 Using multiple Cursor Objects on a single Connection ooooooccccccco 84 Subpackage SUPPO Maarten 85 Cursor objects as Context MAaNagelS eseeeeeeeeeeeeeeeeeeees 85 Using cursor objects as Context objects ooccccccnnoocccnncconnnanancannnannnnns 85 Cursor Type ODE 85 Cursor Object Constructor cta 86 connection cursor name None cursor_options 86 Cursor OD ect Memo ibi 86 Contents 7 6 1 Callproc procnamel parameters o occccnnnnonocccnnonnnnnnncannnnnnnnns 86 lOs ositos NAAT 86 execute sqicmd parameters direct 1 oooccnncccnoncnnonnnnnnnos 8
78. LI The ODBC API is the native IBM DB2 call level interface and provides the best performance when interfacing to DB2 IBM has also extended ODBC with various custom extensions they make available as CLI interface If you need support for those extensions please contact support egenix com Configuring Database Access If you want to use the DriverConnect API with IBM DB2 you ll have to configure the IBM ODBC driver s data source INI file which is named db2cli ini and usually found in the same directory as the above script files The file is needed in addition to the odbc ini file and the entries must match If you place the db2cli ini file into a different directory make sure that you setup the environment variable DB2CLIINIPATH to point to the full path of the file Environment Variables on Unix If you don t use a db2cli ini file you can configure the access details using environment variables In order to connect to the IBM DB2 database the DB2INSTANCE environment variable must be set to the name of the DB2 instance you would like to connect to There may be more environment variables needed please check the scripts that come with DB2 called db2profile for bash or db2cshrc for C shell which set the environment variables Without having these set mxODBC will fail to load and give you a traceback Traceback most recent call last Crom mxODBC import ImportError initialization of module mxODBC failed mxODBC
79. Misc proc py LesL pyo DataDirect dbi py dbtypes py Manager Windows dbi py dbtypes py 10DBC dbi py dbtypes py unixODBC abi py dbtypes py LazyModule py ODBC py Entries enclosed in brackets are packages i e they are directories that include a _ init__ py file Ones with slashes are just simple subdirectories that are not accessible via import 163 mxODBC Python ODBC Database Interface 18 18 1 18 1 1 164 Support eGenix com is provides commercial support for this package including adapting it to special needs for use in customer projects If you are interested in receiving information about this service please contact support egenix com for details This section describes methods which are useful to track down interoperability problems with ODBC drivers eGenix support may ask you to apply some of the methods when working with you to resolve driver related problems ODBC Call Level Tracing In support some cases eGenix may ask you to create an ODBC trace of a session demonstrating a problem you may have with a particular ODBC driver This section explains how to enable ODBC call level tracing The ODBC trace log is a text file that ODBC managers and some drivers can generate in order to help with debugging the interaction between the driver the driver manager and the application The method of how to enable tracing depends on the used ODBC driver manager Windows ODBC Manager Open the
80. ODBC Cursor Type Both connections and cursors expose a read write cursortype attribute for this purpose The attribute uses the ODBC defined values for the cursor types The following values are defined in the ODBC standard SQL CURSOR FORWARD ONLY The cursor only scrolls forward This is the default setting in case mxODBC finds that the database does not support scrollable cursors SQL CURSOR_STATIC The result set is made static by creating a static copy of the result set after opening the cursor As a result any changes to the result set after opening the cursor will not be visible to the client mxODBC uses these cursors as default for backends which support scrollable cursors gt The sou global refers to the mxODBC subpackage global of the same name e g for mx ODBC Windows this is accessible as mx ODBC Windows SOL Please note that in mxODBC 3 3 this will always be the default value Starting with mxODBC 3 3 the default will always be soL cURSOR_ FORWARD ONLY 65 mxODBC Python ODBC Database Interface Did od 5 7 3 SQL CURSOR_KEYSET DRIVEN Keysets are sets of columns in the result set that provide unique keys to the rows in the result set Keyset driven cursors fix the memberships and order of the rows in the result set using these keysets Unlike static cursors they don t create a copy of the result set SQL CURSOR DYNAMIC Dynamic cursors are the opposite of static cursors All changes to
81. ODBC unixODBC packages for the Mac OS X PPC and 386 builds Fixed a problem where the mx ODBC DataDirect package could load an iODBC shared lib This will now result in an ImportError Added note about Sybase ASE 15 ODBC driver and using NULL with SQL_CHAR columns Fix a rare case of truncation of Unicode data when working with ODBC drivers manager that use sizeof SQLWCHAR 1 standard is 2 or 4 Misc mxODBC now uses PyObject_ MALLOC for memory allocation which should make memory allocation a little faster in a few places Added egenix mx base dependency to the mxODBC egg archives Note that relying on this to automatically install egenix mx base is not a good idea since easy_install will download and install the source archive so a compiler is needed and the compilation can easily fail Changes from 3 1 1 to 3 1 2 Fixed a compatibility problem with Python 2 7 s distutils that was introduced in Python 2 7 3 Improved compatibility of the mxODBC native Unicode string format handling with Unix ODBC drivers when running UCS4 builds of Python This allows using the NVARCHAR and NCHAR types of SQL Server with the new MS SQL Server Native Client for Linux with UCS4 Python builds UCS2 Python builds don t exhibit this issue The new driver has proven to be much more feature complete than the FreeTDS ODBC driver so it s definitely worth 19 History amp Changes 171 a try Note that the MS driver currently has an issue
82. QL NO NULLS Query the data source for information on special columns of a given table The table parameter is mandatory Special columns in this sense are columns which can be used to uniquely identify a row in the table e g primary keys or which are automatically updated by the database e g auto increment columns Possible input values for coltype SQL BEST ROWID Return the optimal column or set of columns for uniquely identifying a row in the table the rowid SQL ROWVER Return columns that are automatically updated by the database when the row is updated Possible input values for scope SQL SCOPE_CURROW The rowid column s are only guaranteed to be valid as long as the rows remain unchanged SQOL SCOPE TRANSACTION The rowid is guaranteed to be valid for the duration of the current transaction SOL SCOPE SESSION The rowid is guaranteed to be valid for the duration of the connection Possible input values for nullable SQL NO NULLS Exclude special columns that nullable Using this option can result in an empty result set if the table driver or database don t support such requirements SOL NULLABLE Return special columns even if they can have NULL values The method is useful to determine columns that can be used as to determine query columns that allow retrieving rows which have been inserted in a table without primary key or in a table with a primary key which is defined as auto increment c
83. SN less COnnecliONns anal 30 Pros and Cons of using DSN less Connections ccmmconocccnncncnnnnnnns 30 DNS less Connection Stig 31 Accessing Popular Databases ssssssseeee 32 INAS OL cea 32 Available ODBC DIES ada iiod 32 MS SQL Server Native Client for SQL Server 2005 2008 and later 32 Finding the latest version of the SQL Server Native Client 32 Optimizing SQL Server Native Client Performance 0 33 Configuring the SQL Server Native Client Network Protoco l 33 Multiple active result sets MARS on a single connection 33 MS SQL Server ODBC Driver for SQL Server 2000 cooocccccncccnnnoo 34 Configuring the SQL Server ODBC Driver Client Network PIO CO a 34 MS SQL Server Native Client for LINUX cooocccnonccnnonoccnnnocnnanccnnnnoss 34 Driver rado Sp dao 34 Example Configuration for UNiX coccccnnnnnnccnnnncnnnnnanacnnonaninnnaannss 35 EasySoft ODBC Driver for SQL Server cccoooooooocccccccnnnonoocccnncncnnnnannss 35 OpenLink ODBC Driver for SQL Server oooooooccccccnccnonoccnnncncnonananannnos 35 DataDirect ODBC Driver for SQL Server cccccceseesceeesceeeeseeees 35 Actual Technologies Mac OS X ODBC Driver for SQL Server 36 FreeTDS Unix ODBC Driver for SQL Server c ccccccceeesceeeeseeeees 36 Diver Lita Sarandi ita 36 Example Configuration for UNiX coccccnnnnnocccnnnncnnnononcccnncncnnnannnos 37 General Notes anta rd 37 ODBC API Extensi
84. SOL ASYNC ENABLE OFF default SQL ASYNC ENABLE ON SQL ASYNC ENABLE DEFAULT SQL ATIR MAX LENGTH Maximum length of any fetched column Default is no limit Possible values Any positive integer or SOL MAX LENGTH DEFAULT no limit 20L ATTR MAX ROWS Limit the maximum number of rows to fetch in a result set Default is no limit Possible values Any positive integer or SOL MAX ROWS DEFAULT no limit mxODBC Python ODBC Database Interface Option Comment SQL AT TR METADATA ID Tell the ODBC driver to interpret the catalog method parameters as case insensitive identifiers Default is to interpret them as case sensitive SQL search patterns Possible values SOL TRUE case insensitive identifers SOL FALSE case sensitive search patterns default SOL ATTR NOSCAN Tell the ODBC driver not to scan the SQL commands and unescape expand any ODBC escape sequences it finds Default is to scan for them Possible values SQL NOSCAN_ OFF default SQL NOSCAN_ON SOL NOSCAN DEFAULT setinputsizes sizes This methods does nothing in mxODBC it is just needed for DB API compliance setoutputsize sizel column This methods does nothing in mxODBC it is just needed for DB API compliance iter 1 Returns the cursor itself This method makes cursor objects usable as iterators new in Python 2 2 s Ler 1 Returns the cursor itself This me
85. T STRINGPORMAT MIXED STRINGFORMAT UNICODE STRINGFORMAT NATIVE UNICODE STRINGFORMAT Integer values which are used by connection stringformat and cursor Strinorormat mxODBC can handle different string conversion methods on a per connection and per cursor basis See the documentation of the two attributes for more information ERROR WARNINGFORMAT WARN WARNINGFORMAT IGNORE WARNINGFORMAT Integer values which are used by connection warningformat and cursor warningformat mxODBC can use different ways of reporting database warnings on a per connection and per cursor basis See the documentation of the two attributes for more information mxODBC Python ODBC Database Interface 12 2 148 FLOAT DECIMALFORMAT DECIMAL DECIMALFORMAT Integer values which are used by connection decimalformat and cursor decimalformat mxODBC can handle different output formats for numeric and decimal database column types on a per connection and per cursor basis See the documentation of the two attributes for more information HAVE UNICODE SUPPORT Integer flag which is either 0 or 1 depending on whether mxODBC was compiled with Unicode support or not Unicode support is always available in mxODBC 3 1 and later so this flag is always set to 1 license String with the license information for the installed mxODBC license mx ODBC Globals and Constants At the top level the mx ODBC package defines these globals and constants Erro
86. Table name of the table containing the result set column If the table name cannot be determined e g for expressions an empty string is returned Returns a string SQL DESC_TYPE NAME Data source dependent type name of the result set column or an empty string if the value cannot be determined Returns a string SQL DESC_ UNSIGNED Checks whether the result set column is unsigned numeric data or not Returns an integer value SQL TRUE column data is unsigned or not numeric SQL FALSE column data is signed If the ODBC driver doesn t support an info_id or cannot determine the requested value it either raises an exception or returns an empty string where applicable getcursorname Returns the current cursor name associated with the cursor object This may either be the name given to the cursor at creation time or a name generated by the ODBC driver for it to use getcursoroption option Returns the given cursor option This method interfaces directly to the ODBC function SOLGetCursorOption option must be an integer Suitable option values are available through the SOL object Possible values are Option Comment SOL ATTR QUERY TIMEOUT Returns the query timeout in seconds used for the cursor Note that not all ODBC drivers support this option SQL TTR ASYNC ENABLE Check whether asynchronous execution of commands is enabled
87. UE Check whether the result set column refers to an auto increment column of the table The check only returns valid values for numeric columns that can be defined as auto increment column in the database Returns an integer value SQL TRUE column is auto increment SQL FALSE column is not an auto increment column or not numeric SUL DESC BASE COLUMN NAME Base column name of the result set column If the base column name cannot be determined e g for expressions an empty string is returned Returns a string SQL DESC BASE TABLE NAME Base table name of the result set column If the base table name cannot be determined e g for expressions an empty string is returned Returns a string SUL DESC DISPLAY SIZE Returns the maximum number of characters needed to display the column data Returns an integer SQL DESC LENGTH Returns the maximum length of the column data in characters Returns an integer SQL DESC OCTET LENGTH Returns the maximum length of the column data in bytes Returns an integer SQL DESC PRECISION Returns the precision of a numeric column For date time columns this returns the precision of the seconds fraction if applicable Returns an integer SOL DESC SCALE Returns the scale of a numeric column Returns an integer mxODBC Python ODBC Database Interface 90 Option Comment SQL DESC_ TABLE NAME
88. VE Ad 66 Oracle eae Satta eta ea 67 Postres licuar aa 67 BM DBZ da 67 mxODBC Subpackages cece eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeens 67 One API for all SUDDACKACES ca 68 mxODBC Connection Objects sseseee 69 Subpackage SUP POL sriivectseecnccevveicteevcaeeratiasataearasvinen 69 Connection Type ODJECE erica 69 Connection Object Constructors cccccccncncnnnnnonnnonininnnnnno 69 Connect dsn user password clear_ auto commit 1 errorhandler None connection_OptiONS cccccncnnnnccnnnnnnon 69 connect dsn user password clear_auto_commit 1 errorhanaler NON ii 70 DriverConnect DSN_ string clear_auto_commit 1 errornanaler NOME a aa 70 ODBC dsn user password clear auto _commit 1 erromandler NoONiaaa add 71 Contents 6 4 6 4 1 6 4 2 6 5 6 5 1 6 5 2 6 6 6 6 1 6 6 2 6 7 6 8 Default Transaction Settings 0 0 0 0 eeeeeeeeeeeeeeeeeeeeeeeeees 71 OVEFMCING the Detalla pri 71 Errors due to missing Transaction Support ccccccnnononacnnononnnnnanacnnnnnnnnos 72 Connection objects as context ManagerS ccccccccncnnnnnnnon 72 Introduction to Context MAanNagerS sccccceeeeesessneeeeeeeeeeessseeeeeeees Ya Using connection objects as context ObjeCt oocccccncononcconcncnnnnnanccnnnnos 72 Unicode ANSI Connections cccsceccscecececcecscecescscececcs 73 Unicode ODBC Titer ACG ase esses an 73 ANS ODBC Itaca A is tea 73 Connection Obje
89. Y DE 115 date tmelo Mala ca 115 decimal matias pi 115 deESCAP UO daa 115 SIMCSSAQES N E A T E E E E E 116 PAramcoU borrada pidan 116 params lena 116 amak der l a 116 O estes van acon sacees ne aneca eae na cat ania necaece eae nae aacae es 117 SLOW COUN Li 117 FOWMUNIDER cai 117 INC LIM a liyitanstinckoncera nee tee arene aes eagmen aw ane eee 117 STUIMES TAME SOIMUOM sario a E UE NERO 118 Wal MMC OMM aU sins R a E 118 8 Data Types supported by mxODBC 119 8 1 mxODBC Parameter Binding ooooocnconononononononcnonconno nono nos 119 8 1 1 Parameter Binding SES acia 120 Contents 8 2 8 2 1 8 2 2 8 3 8 4 8 5 8 6 8 7 8 8 8 9 10 10 1 mxODBC Input Binding MOdeS eseseeeeeeeeeeeeeeeeees 121 Adjusting the Type Binding MOde scccceeeeesessseeeeeeeeeeeeesseeeees 122 Per Statement Binding Mode reirme e 122 SOL Type Mp t BICIS and 122 Python Type Input Binding oooooccncnnncnononoconononononc nono nono nos 126 Output CONVEFSIONS ne S 129 Output Type Converter FUNCTIONS occcooocccccnnoccnnnnonncs 131 POSO Nai idos 131 SU Pers atracan 131 O T E ET E T E Matias 132 Dinda aldeei e T 132 AUTO CONVETSIONS speria raa a EEEE TEE ORE 132 Unicode and String Data Encodings oooccncnnnnnnnnnnnnnnnnnmmoo 133 Additional COMME Satin 134 DB API Type Objects and Constructors 135 Date Wear Mont day tetitas 135 Time hour minute SecOnd occcnoccnnoccnnncnnno
90. aa a E mn N 16 SED Ae arn E ashe dada teas oaisedaot aves 16 A oainas ta Diarten E 2a hearse Cees A 17 Automatic Uninstall oia 17 Manta Unas tall ds 17 Access Databases using mxODBC 0066 18 ODBC Application Stack ooooccccnincnonoconnnnnnnnnnnnnnnnnnnnnnnnos 18 Arenttecture 32D ys DADA 18 Accessing Databases from Windows 19 Contents D2 33252 3 2 3 3 2 4 iZ O 3 2 6 3 3 3 3 1 02 3 3 3 3 3 4 3 3 5 Looking for Windows ODBC Drivers sssssssessssssssseesssssssssreeesssssssrees 19 Installing Windows ODBC Drivers cccccssesssseeeeeeeeeeeeessneeeeeeeees 20 Setting up dn ODBC Dala SOU A 20 ODBC on 64 bit Windows Versions ccccceeeeseeessneeeeeeeeeeeeees 20 ODBC Contistration Hess 20 ODBC INI ODBC Data Source ConfiguratiON cccmooocccccccnnnnnnnns 21 ODDC asnos tota 21 lODBCE Data SOURCES enisrocad ai ii 21 ODBCINST INI ODBC Driver ConfiguratiON cccccnnoccnnccnnnnnnanos 21 ODBC DEVET orree a 21 Windows Registy KEYS io i 21 HKEY LOCAL MACHINE SoftwrelODBCIODBC INI 21 HKEY LOCAL MACHINE Software ODBC ODBCINST INI 21 HKEY CURRENT USER Software ODBC ODBC INI ococcccncc o 21 Available Data Source Types DSNS cconcnonocccccccnnconcocnnnncccnnananancnanancnnns 22 User Datrsources User DSN aan 22 System Data Sources System DSN coooooncccccncnnoccncnnnonoconnnnnnaconnnos 22 File Data Sources Fle DSN lina d
91. ading to find out If you get an exception thread support is not available Transaction Support Auto Commit ODBC uses auto commit on new connections per default This means that all SQL statement executes will directly have an effect on the underlying database even in mxODBC Python ODBC Database Interface Da 62 those cases where you would really back out of a certain modification e g due to an unexpected error in your program mxODBC turns off auto commit whenever it creates a new connection ie it runs the connection in manual commit mode unless the connection constructor flag clear auto commit is set to O or the database does not provide transactions You can adjust the connection s commit mode after creating it using the connection autocommit attribute See 5 5 3 Adjusting the Connection Commit Mode for details Manual Commit Using a connection in manual commit mode means that all your commands are grouped in transactions only the connection will see the changes it has made to the data in the database until an explicit connection commit is issued The commit informs the database to write all changes done during the last transaction into the global data storage making it visible to all other users A connection rollback on the other hand tells the database to discard all modifications processed in the last transaction Transaction Start and End New transactions are started implicitly in the following c
92. afely be removed from the system It will not remove files which were added to the subpackages after installation nor will it remove the license files you manually installed 2 Installation 2 3 2 3 2 11 Installation using egg package archives We assume that you have already have setuptools and easy_install installed in your Python installation The examples in this section refer to a Unix or Mac OS X installation but it is also possible to install egg packages on Windows You can check this by searching for easy install in the directory where you ve installed the Python interpreter binary python c import setuptoocols print setuptools installed If this reports an ImportError you don t have setuptools installed In that case please see the next section Note that you can also use the information from this section to create a zc buildout setup Setuptools In order to be able to install eggs you need to install a Python package called setuptools To get this package installed download the file ez_setup py from the URL http peak telecommunity com dist ez_setup py and run it using the Python interpreter that you will be using with mxODBC python ez Setup py This will install setuptools into your Python site packages directory as well as a script called easy_install in your bin directory The easy install script is later need to install the mxODBC Before You Start Upgrading When upgrading from
93. amed to have all new cursors created on the connection default to the named style The default cursor paramstyle is set to the value connection paramstyle of the connection on which the cursor was created It is also possible to adjust existing cursors to use the named parameter style for all subsequent cursor execute method calls by simply setting cursor paramstyle to named This has no affect on other cursors created on the same connection Example cursor paramstyle qmark cursor execute SELECT FROM MyTable WHERE A AND B Ly ay print cursor fete alld cursor paramstyle named cursor execute SELECT FROM MyTable WHERE A a AND B b caza Lo Bro 241 8 Data Types supported by mxODBC 3 2 121 print cursor tetenalld More information about the connection and cursor attribute paramstyle is available in section 6 8 Connection Object Attributesand 7 7 Cursor Object Attributes mxODBC Input Binding Modes When passing parameters to the execute methods of a cursor mxODBC has to apply type conversions to the parameters in order to send them to the database in an appropriate form This process is called binding a variable mxODBC implements two different input variable binding modes depending on what the ODBC driver can deliver Binding Mode Value of connection bindmethod Comments SQL type binding BIND USING SQLTYPE The database is asked for the appropriate data type and m
94. and other database features which are useful to know when writing applications for a particular database backend mxODBC Parameter Binding When defining SQL statements that use parameters mxODBC provides a way to bind Python values to those parameters called parameter binding Instead of using the literal parameter values in the SQL statement passed to the cursor execute methods you can use a parameter binding character or character sequence to define the parameter locations in the SQL statement and then pass the Python parameter values to the cursor execute methods as additional parameter The ODBC driver or the database backend will then take the values and use them to run the SQL statement Example Use SELECT FROM MyTable WHERE A AND B and 1 2 parameter binding instead of SELECT FROM MyTable WHERE A 1 AND B 2 embedding parameters literally This has both a performance and a security advantage Performance is much better if the database backend can easily identify whether it has already created an access plan for a SQL statement by simply looking at the parameterized version of the statement than first having to convert a SQL mxODBC Python ODBC Database Interface 8 1 1 120 statement with embedded literal parameters to a normalized form and then find that it already has an access plan If you plan to run the same statement over and over again or use cursor executemany then the ODBC driver o
95. append errorclass errorvalue Ignore warnings 10 mxODBC Exceptions and Error Handling if record messages only or ignore warnings and issubelass errorclass mx 0ODBC Brrof Warning EStTura Raise the exception raise errorclass errorvalue Installation of the error handler on the connection connection errorhandler myerrorhandler In case the connection or one of the cursors created from it cause an error mxODBC will call the myerrorhandler function to let it decide what to do about the error situation Possible error resolutions are to raise an exception log the error in some way ignore it or to apply a work around Typical use cases for error handlers are situations where warnings need to be masked or an application requires an on demand reconnect If you need to catch errors or warnings at connection time you can use the optional keyword argument errorhandler to have the error handler installed early enough to be able to deal with such errors or warnings connection mx ODBC Windows DriverConnect DSN test errorhandler myerrorhandler 10 5 Warning Classes 141 The Python DB API 2 0 does not define a warning class hierarchy At the time the DB API 2 0 was defined the Python warning was not yet in existence It is expected that a future revision will add such a hierarchy Until then mxODBC uses it s own warning hierarchy which currently just has one warning class DatabaseWarning Warning i
96. ases e creation of a new connection e onreturn from a commit and e after having issued a rollback Unless you perform an explicit connection commit prior to deleting or closing the connection mxODBC will try to issue an implicit rollback on that connection before actually closing it Errors are only reported in case you use the connection close method Implicit closing of the connection through Python s garbage collection will ignore any errors occurring during rollback Data Sources without Transaction Support Data sources that do not support transactions such as flat file databases e g Excel or CSV files on Windows cause calls to rollback to fail with an NotSupportedError mxODBC will not turn off auto commit behavior for these sources The setting of the connection constructor flag clear_auto commit has no effect in this case 5 mxODBC Overview 5 5 3 5 6 5 6 1 63 Some databases for which mxODBC provides special subpackages such as MySQL don t have transaction support since the database does not provide transaction support For these subpackages the rollback connection method is not available at all i e calling it produces an AttributeError and the clear auto commit flag on connection constructors defaults to 0 Adjusting the Connection Commit Mode You can adjust the connection s commit mode after creating it using the connection autocommit attribute Setting the attribute to True will caus
97. ata in your client applications even if the database does not natively support Unicode mxODBC will automatically provide the necessary conversions on the fly mxODBC supports both the Unicode or the ANSI ODBC APIs You can chose the optimal approach for your driver e Support for Multiple Result Sets call stored procedures and access all returned result sets using an easy to API Easily free up resources in case result sets are no longer needed e Useful DB API Extensions o connection autocommit to easily turn on off the ODBC autocommit feature o cursor and connection objects usable as context managers 1 Introduction O Adjustable paramstyle mxODBC supports both the ODBC question mark positional parameter binding style as well as the named parameter styles used by e g Oracle cursor scroll to scroll the cursor in result sets without actually fetching data ODBC cursor connection option methods to adjust ODBC cursors connections to your application s needs and optimize performance by e g declaring a connection read only e Configurable Data Type Mappings O Supports Python type binding and Database type binding for efficient data exchange Supports mxDateTime and Python s time and datetime modules for date time value exchange Supports standard Python floats integers longs and Python s decimal module for loss less numeric value exchange Automatically handles and supports unknown data types and user data
98. atabase Interface The method is useful for determining and extracting table access permissions from the database The catalog method generates a result set having the following schema Column Name Column Datatype Comment TABLE_CAT VARCHAR 1 28 Always NULL TABLE_SCHEMA VARCHAR 1 28 The name of the schema containing TABLE NAME TABLE_NAME VARCHAR 1 28 not NULL The name of the table or view or alias or synonym GRANTOR VARCHAR 1 28 Authorization ID of the user who granted the privilege GRANTEE VARCHAR 128 Authorization ID of the user to whom the privilege is granted PRIVILEGE VARCHAR 1 28 The table privilege This may be one of the following strings ALTER CONTROL INDEX DELETE INSERT REFERENCES SELECT UPDATE IS_GRANTABLE VARCHAR 3 Indicates whether the grantee is permitted to grant the privilege to other users This can be YES NO or NULL 7 7 Cursor Object Attributes arraysize This read write attribute specifies the number of rows to fetch at a time with fetchmany It defaults to 1 meaning to fetch a single row at a time mxODEC observes this value with respect to the fetchmany method but currently interacts with the database a single row at a time closed This read only attribute is true if the cursor or the underlying connection was closed by calling the close method Any ac
99. atabases using mxODBC 27 ODBC This section is used to configure driver related ODBC manager settings such as ODBC call tracing The settings in this section apply to all data sources ODBC needs this section in the odbc ini file unixODBC in the odbcinst ini file More recent DataDirect ODBC manager versions accept the section in both files older version need it in the odbc ini file ODBC Data Sources This section contains one entry per configured data source mapping the data source name to a description Example ODBC Trace 0 TraceFile tmp odbc log ODBC Data Sources sybaseasel2 Sybase ASE 12 on sybaseasel2 example net sybaseasel2 Driver opt sybase DataAccess ODBC lib libsybdrvodb so Description Adaptive Server Enterprise Server sybaseasel2 egenix internal Port 5000 Database mydb TextSize 10000000 UseCursor 1 FileUsage 1 Trace 0 TraceFile tmp sybase log odbc ini User ODBC Data Source Configuration This INI file provides data source information on a per user basis It uses the same structure as the system wide etc odbc ini file The data sources defined in this file are only visible to the user account for which it is defined etc odbcinst ini System ODBC Driver Configuration Depending on your ODBC manager installation or OS the file may also reside in a different directory Please consult your ODBC manager documentation for details On Mac OS X
100. ay be given as list of option value tuples These are then passed to the cursor s cursor setconnectoption API see the Cursor Object section 7 and allow configuring the cursor upfront to a specific need getconnectoption option Get information about the connection option must be an integer Suitable option values are available through the SQL object see the Constants section 10 5 for details The method returns the data as 32 bit integer It is up to the user to decode the integer value using the SQL defines available through the soL constant This API gives you a very wide range of information about the underlying database and its capabilities See the ODBC SQLGetConnectAttr API Documentation for more information lt QOTLATO LATO id Get general information about the database the ODBC driver and the ODBC driver manager The info id must be an integer Suitable values are available through the sor object see the Constants section 10 5 for details 6 mxODBC Connection Objects 75 The method returns a tuple integer string giving an integer decoding in native integer byte order of the first bytes of the API s result as well as the raw buffer data as string It is up to the caller to decode the data e g using the struct module This API gives you a very wide range of information about the underlying database and its capabilities See the ODBC SQLGetInfo API Documentation for more information nativesql
101. ay be given to set the error handler for the Connection object prior to actually connecting to the database This is useful to mask e g certain warnings which can occur at connection time The errorhandler can be changed after the connection has been established by assigning to the errorhandler attribute of the Connection object The default error handler raises exceptions for all database warnings and errors mxODBC Python ODBC Database Interface 70 If you connect to the database through an ODBC manager you should use the DriverConnect API since this allows passing more configuration information to the manager and thus provides more flexibility over this interface See the following section 6 4 Default Transaction Settings for details on Clear auto commit connection options may be given as list of option value tuples to set pre connect ODBC connection options The option and value arguments must use the same format as the parameters for the setconnectoption method This list can be used to e g enable the MARS feature of SOL Server Native Client which enables working with multiple active result sets on the same connection from mx ODBC Manager import DriverConnect SOL options SQL COPT SS MARS ENABLED SQL MARS ENABLED YES db DriverConnect DSN mssqlserver2008 UID sa PWD dbsOR X9 rxD connection pptions opElons CONNECT dan weer pasavwora y Clear auto commit l errorhandler None Is just a
102. ay experience data truncations which then cause the decoding process to fail Another possibility is to use the MIXED STRINGFORMAT which allows mxODBC to interface to the database using the best suitable data type For e g MS SQL Server this usually means passing all string data as Unicode data to and from the database In MIXED STRINGFORMAT mode mxODBC will return string data in the default format of the database driver leaving the conversion to the Python program Note mxODBC only supports Unicode objects at the data storage interface level meaning that it can insert and fetch Unicode data from a database provided that the database can handle Unicode and that the used mxODBC subpackage was mxODBC Python ODBC Database Interface 3 9 134 configured with Unicode support It also supports SQL commands given as Unicode data However it does not handle Unicode at the schema interface level that is e g cursor description will not return Unicode objects for the column names This may be added to a future version of mxODBC but is currently not supported by the package Additional Comments The above SQL types are provided by each subpackage in form of SQL type code integers through attributes of the singleton object SOL e g SOL CHAR is the type integer for a CHAR column You can decode the type code value in the cursor description tuple by comparing it to one of those constants A reverse mapping of integer codes to code names is
103. cess Databases using mxODBC ODBC INI ODBC Data Source Configuration This INI file provides data source information using one INI section per data source In addition to the data source sections there are also a number of higher level sections ODBC This section is used to configure driver related ODBC manager settings such as ODEC call tracing The settings in this section apply to all data sources ODBC Data Sources This section contains one entry per configured data source mapping the data source name to a description ODBCINST INI ODBC Driver Configuration This INI file provides one INI section per installed ODBC driver In addition to the data source sections there are also a number of higher level sections ODBC Drivers This section contains one entry per configured and installed ODBC driver mapping the driver name to the string Installed Windows Registry Keys The following registry keys provide the ODBC configuration information in much the same way the formerly used INI files did HKEY LOCAL MACHINE Software ODBC ODBC INI One entry per INI section of the ODBC INI file used for system wide settings and system DSNs See 3 2 5 Available Data Source Types DSNs for details on the different DSN types HKEY LOCAL MACHINE Software ODBC ODBCINST INI One entry per INI section of the ODBCINST INI file used for managing the installed ODBC drivers HKEY CURRENT _USER Software ODBC ODBC INI On
104. cexcsesiaren cevasardectxoosiel ace ee 153 A a perenre rem re ert mre reer E corte y 153 mx ODBC DataDirect DataDirect ODBC Manager 154 NOES Sane a a 155 General RECOMMENCAtIONS cceccsccecceccescesccsccsccscceccecceceeses 155 BADIA RON SiN AN 155 ODBC Driver Subpackages tina 155 Hints Links to other Resources 00 6 157 Running mxODBC from a CGI script coccononococuuuaccnnnnnnnnnnos 157 Running mxODBC with mod_wsgi occccnnnnnnoocuoconcnnnnnnnnnnon 157 mod wsgi and Python 2 7220 E 157 Manifest work around iii a a 158 Contents 14 3 14 4 15 16 17 18 18 1 18 1 1 18 1 2 18 1 3 18 1 4 18 1 5 18 2 19 Freezing MXODBC USING PyZeXe cccooocccconocccnonoccnnoninccnonnnss 158 More Sources of InformatiOn sccccecececececececcecececs 158 Empleo 00 Testing the Database Connection 162 mxODBC Package Structure ommm 163 DUD DOME ai 169 ODBC Call Level Traduca 164 Windows ODBC Manager aa 164 IODBE Driver Mandager sa 165 UNIXODBE Driver Manage aa nie a E in 165 DataDirect ODBC Driver Manage sissscisranii i a a 165 MacOSX ODBC Driver Manae asorin a caret soo haeiease 166 mxODBC Call Level Tracing ooocccccncccnnnnnnnnnnnnnnnnnnnnnnnnoo 166 History amp Changes rccccccssssssssscsscccscees 167 Changes rom 9 20 1 10 22 0 aaa aa 167 Feature Enhancements Cain 167 Driver Compatible aaa 167 A o E Manda ec
105. char 1 This currently doesn t appear to work UseServerSidePrepare 1 Using these settings you can then connect to PostgreSQL using a simple connection string such as DSN postgresql UID username PWD password 4 Accessing Popular Databases 4 7 4 7 1 49 EasySoft ODBC Driver for PostgreSQL Homepage http www easysoft com OpenLink ODBC Driver for PostgreSQL Homepage http www openlinksw com DataDirect ODBC Driver for PostgreSQL Homepage http www datadirect com Actual Technologies Mac OS X ODBC Driver for PostgreSQL Homepage http www actualtech com When using the driver on Mac OS X 10 6 Snow Leopard be sure to use version 3 0 9 or higher since earlier versions had a problem with fetching data MySQL Available ODBC Drivers MySQL ODBC Driver Homepage http dev mysql com downloads connector odbc Be sure to use the mxODBC ODBC manager subpackage against which the MySQL driver was compiled This will usually be mx ODBC unixODBC or mx ODBC iODBC The MySQL ODBC driver documentation recommends using unixODBC with the driver i e the mx ODBC unixODBC subpackage Note that the MySQL 5 1 ODBC driver can also connect to a MySQL 5 0 database server It is usually best to use the latest available version even if your database servers hasn t been upgraded yet Driver Notes e There is one particularity with the ODBC driver for MySQL all input parameters are being processed as strin
106. ckage and find the module instead of the mx ODBC Error exception class Exception Classes These exceptions are defined in the modules scope and also available as attributes of the connection objects to easy writing applications using different mxODBC sub packages Error Baseclass for all other exceptions related to database or interface errors You can use this class to catch all errors related to database or interface failures error is just an alias to Error needed for DB API 1 0 compatibility mxODBC Python ODBC Database Interface Error is a subclass of exceptions StandardError Warning Exception raised for important warnings like data truncations while inserting etc Warning is a subclass of exceptions StandardError This may change in a future release to some other baseclass indicating warnings InterfaceError Exception raised for errors that are related to the interface rather than the database itself DatabaseError Exception raised for errors that are related to the database DataBrror Exception raised for errors that are due to problems with the processed data like division by zero numeric out of range etc OperationalError Exception raised for errors that are related to the database s operation and not necessarily under the control of the programmer e g an unexpected disconnect occurs the data source name is not found a transaction could not be processed a memory allocation error occurred duri
107. cononcnnncconaronunccnnonons 135 Timestamp year month day hour minute second 135 Datekrom ICKS HICKS idol 135 Mis o eraren 136 Timestamp FFOM TICKS CIEKS nia iia 136 A halen ease metas tusatt viata eran neh as 136 STRING 136 DINA cat 136 NUMBER a Mo unveaayaet boa uherncneuce Ma uidials 136 DATE TIME ieee sacra icy eats anata Gace id 136 ROV ID asada ses E a na 136 mxODBC Exceptions and Error Handling 137 Exception Clas SCS aida saaeeeraaet 137 mxODBC Python ODBC Database Interface 10 2 10 3 10 4 10 4 1 10 5 10 6 10 6 1 10 6 2 11 11 1 11 2 WAI iaa 138 MENACE e enana AAE 138 Databases aa 138 DIETO aask 138 Operational ETTOL suiras E renner rnrn arr er 138 VLC SRIRVEITOR ia as 138 ernal EOE sora ee A ees 138 Proerd ninine Erotico oa 138 NotSUpPPOrtedENO untada 138 SOL EMO MAD DING Saanaata 139 SION CASS sects or tiscien ace ach E E TE TTA 139 Exception Valla OM 139 A earnest E ON 139 SCLC OG gn i rah EE cease anes ebwagi Nis anee henge 139 Messagete bora adi 139 E a AEDE E AAE a road 139 Enor Handler stas 140 So es 140 Warning Classes 141 Database Wan 141 Database Warnes oie 142 Default Error Handle 142 ERROR_WARNINGFORMAT default ccccccccssssssssseeeeeeeees 142 WARN WARNINGFORMA T rabo 142 IGNORE _WARNINGFORMA Tooocooocconoccnnocnnnoconoccnnoccnonoconoccnnonnns 142 Custom Warning Error Handler ccceesessssncceeeeeeeessseeeeeeeeeeeeees 143
108. constants e g SQL CHAR for string data but could also have database specific values mxODBC only understands the ones defined in the above table so this gives you a chance to map user defined types to ones that Python can process mxODBC Python ODBC Database Interface 3 7 132 sqllen is only used for string data and defines the maximum length of strings that can be read in that column mxODBC allocates a memory buffer of this size for the data transfer Returning 0 as sq11en will result in mxODBC dynamically growing the data transfer buffer when fetching the column data This is sometimes handy in case you want to fetch data that can vary in size binddata is optional and only needed for some special sqitypes It will be used in future versions to e g allow binding output columns to files which some ODBC drivers support the column data is transferred directly to a file instead of copied into memory Cursor objects will use the connection s converter attribute as default converter It defaults to None meaning that no converter function is in effect None can also be used to disable the converter function on a cursor Don t use a converter function on the cursor cursor setconverter None You can switch converter functions even in between fetches mxODBC will then reallocate and rebind the column buffers for you Example always return INTEGER values as FLOATS def converter position sqltype sqllen if sql
109. crashing MySQL ODBC 3 51 20 driver Added work around for Informix ODBC driver complaining about timestamp formats mxODBC now includes the license verification module dependencies so you no longer have to add them manually when using e g py2exe Added a note to the documentation on hidden module dependencies when wrapping mxODBC into applications using py2exe Added work around for SQL Server 2005 to be able to retrieve gt 1MB Unicode data when running mxODBC in UNICODE_STRINGFORMAT string format mode Enhanced the stringformat documentation to more clearly state how the conversion processes work mxODBC stringformat set to UNICODE_STRINGFORMAT did not convert Unicode to 8 bit strings when run in Python type binding mode Added Python datetime support on Python 2 3 Added Python 2 6 support on Windows using VC9 mxSetup prebuilt archives no longer need to use build skip to skip the build process The build command is now smart enough to detect check and automatically use a build pickle and the prebuilt format 19 History amp Changes 175 Fixed a problem in mxSetup that caused the uninstall command not to work with prebuilt packages Thanks to Wouter van Atteveldt for pointing out the problem Changes from 3 0 0 to 3 0 1 Fixed a bug in the stringformat setting that could cause the stringformat setting not to affect the SQL type used in binding parameters Fixed a bug in the way binding sets the length info
110. ct Methods ie 74 KO Ea E tases eee E EOE see 74 COMA O A E A EEA 74 cursor name None Cursor_OptiONS ccccccconnnccccnnncnnnnnnnns 74 pertconnectoption oplO Misal 74 Seno IO 1G ss a 74 MMALIVESG COMUMANG riada ida 75 o eae sautencen cde aang deemed eee icncareetoucer 75 setconnectoption option value oocccccnonoccccnnnnnnnnanccccnnnnnnns 75 E COE rara deco 76 y JEXIL exc type EXC Value EXC 0D ria cio 76 Connection Object Attributes lt 2iiccsiattcasacicatictaaniecaceies races 76 A A A AN 76 A Sess ates Cain aun Pats 76 Close II Era eR RETR te ey carte EL ET ae 76 BGG G s A ane Oo EE Be EE ET 76 CUES ORV DO Jorre ude vonneca teed ein T sanhscunmetnedresenadns 76 SQL CURSOR FORWARD ONLY cccssccsssessssecersececseceesecesevcaeee 77 SOLCURSON STATE ea anatomic 77 SOL CURSOR KEVSEN DRIVEN wcuscscccsssdsecenstosiantsiereaensnsenensietas 77 SOLCURSOR DYNAMIC sses a eon tetas bolawaeses 77 ACUM Ora aa E E AO I7 DATETIME DATETIMEFORMAT delal saire aa IT PYDATETIME DATETIMEFORMA Tooooconccconoccncocnnnonnnonccnoncnncnnnnoss ZI TIMEVALUE DATETDIMEFORMA Tercan n o vicoids ER TOPLE DATETIMEFORMA asar ra Te STRING DATETIMEFORMA Donostia lll 78 AMAS NAM cs 78 A II Andes 78 mxODBC Python ODBC Database Interface 6 8 1 7 1 7 1 1 712 EZ 7 3 7 3 1 7 4 aS 7 6 dECIMAlO MAL 78 FLOAT DECIMALFORMAT default cccccccccceeceeeessseseseeees 78 DECIMAL DECIMALFOR MAT 78 Arver T
111. ctions that do not need scroll support to use forward only cursors per default connection mx ODBC Windows DriverConnect connection cufsortype mx ODBC Windows 5S0b CURSOR FORWARD ONLY All cursors created on connection will then default to forward only cursor type Please refer to section 5 7 ODBC Cursor Types for more details on cursor types Sybase ASE Available ODBC Drivers Sybase ASE ODBC driver Homepage http www sybase com Tested with Sybase ASE 15 5 ODBC driver Sybase ASE 15 5 ships with ODBC drivers for both 32 bit and 64 bit platforms The drivers are part of the ASE server packages 3 Please note that in mxODBC 3 3 this will always be the default value 45 mxODBC Python ODBC Database Interface 46 The ASE 15 5 ODBC driver can also be used to connect to a Sybase ASE 12 x server database In fact this setup is recommended since the 15 5 version of the driver fixes a couple of issues that are present in the 12 x ODBC driver NULL issues with Sybase ODBC driver We have had reports of the Sybase ODBC driver producing errors when trying to set a character column to NULL by passing None to mxODBC for that column The problem appears to have been fixed in the Sybase ODBC driver versions of Sybase ASE 15 5 ESD 3 for the Windows and Linux 32 bit versions The 64 bit versions still have this issue even with ESD 3 instead of inserting NULLs random data is put into the database A user repor
112. ctory where the driver itself is located 4 Accessing Popular Databases 4 6 4 6 1 47 sybasease Driver opt sybase DataAccess ODBC 1ib libsybdrvodb so Description Adaptive Server Enterprise Server sybasease example net Port 5000 Database mydb TextSize 10000000 UseCursor 1 FileUsage l Trace Off TraceFile tmp sybase log e Using these settings you can then connect to Sybase ASE using a simple connection string such as DSN sybasease UID username PWD password EasySoft ODBC Driver for Sybase Homepage http www easysoft com OpenLink ODBC Driver for Sybase Homepage http www openlinksw com DataDirect ODBC Driver for Sybase Homepage http www datadirect com Actual Technologies Mac OS X ODBC Driver for Sybase Homepage http www actualtech com When using the driver on Mac OS X 10 6 Snow Leopard be sure to use version 3 0 9 or higher since earlier versions had a problem with fetching data PostgreSQL Available ODBC Drivers PostgreSQL ODBC Driver Homepage http psqlodbc projects postgresgql org Tested with psqlodbc 08 02 0200 The PostgreSQL driver is usually compiled against unixODBC on Unix platforms Please use the mx ODBC unixODBC subpackage to connect to PostgreSQL with it mxODBC Python ODBC Database Interface 48 On Mac OS X you may need to use the mx ODBC iODBC subpackage instead since the Mac OS X ODBC manager is derived from the iODBC
113. d cursors the rowcount attribute does not always give correct results with DB2 mxODBC Subpackages The mxODBC package is organized in subpackages with one package per support ODBC driver manager and in custom builds additional subpackages for specific drivers databases See section 13 mx ODBC Subpackages for details on available subpackages In mxODBC 3 3 this will change to forward only cursors 67 mxODBC Python ODBC Database Interface 5 8 1 68 One API for all Subpackages To make applications portable between ODBC database backends each of these subpackages use the same names and API signatures in fact the same mxODBC implementation is used for each of the subpackages customized to meet the respective ODBC driver manager s specific requirements As an example say if you are using the mx ODBC Windows subpackage then the constructor to call would be mx ODBC Windows DriverConnect When porting the application to Unix you d use e g the mx ODBC iODBC subpackage and the constructor then becomes mx ODBC iODBC DriverConnect In your application you d just have to change the top level import from from mx ODBC import Windows as Database to from mx ODBC import iODBC as Database The subpackage globals such as exception names helper functions connection constructors etc remain the same so no additional changes are necessary Of course you will usually have to rely on different ODBC drivers when switc
114. d is only implemented for input parameters in mxODBC for reasons explained in 5 6 Stored Procedures Future versions of mxODBC may also support in out and output parameters Glose 1 Close the cursor now rather than automatically at garbage collection time The cursor will be unusable from this point forward an Error or subclass exception will be raised if any operation is attempted with the cursor execute sqlcmd parameters direct 1 Prepare and execute a database operation query or command Parameters must be provided as sequence and will be bound to variables found in the sqicmd string on a positional basis Variables in the sqicmd string are specified using the ODBC variable placeholder e g SELECT name id FROM table WHERE amount gt 12 Note that in mxODBC 3 0 and earlier the execute methods used to work like executemany when passing a list of tuples as parameter a feature inherited from Python DB API 1 0 Starting with mxODBC 3 1 this behavior was removed to avoid confusion 86 7 mxODBC Cursor Objects AND amount lt and get bound in the order they appear in the SQL statement sqlcmd from left to right A reference to the sqicmd string will be retained by the cursor and made available to Python as cursor commana If the same sqlcmd object is passed in again the cursor will optimize its behavior by reusing the previously prepared statement This is most effective for algorithms where
115. d of Python Windows users always need the UCS2 version Mac OS X should also try the UCS2 version first Unix users will most likely need the UCS4 version To find out which variant your Python version was compiled with run the following command python c print UCS s len u x encode unicode internal This will either print out UCS2 or UCS4 Step 2 Next install the egenix mxodbc prebuilt package in your Python installation mxODBC Python ODBC Database Interface 16 Note that you may need to have admin or root privileges in order to successfully complete the following step unless you are using a virtualenv based setup 1 First unzip the downloaded prebuilt package archive to a temporary directory 2 Then run the following command using the Python installation you intend to use in the package directory egenix mxodbc 3 1 python setup py install Note that you can use the standard distutils install command options e g to install the package to a different prefix using prefix or a home directory using home For more information on the available options please have a look at the distutils install command documentation After installation you can remove the temporary directory without causing harm Please keep the prebuilt package archive around in case you want to uninstall the package again Step 3 Now that you have installed the product code you need to install the proper lic
116. d signed notice from eGenix com providing evidence of the extent of authorizations the Licensee has acquired to use the Software and of Licensee s eligibility for future upgrade program prices if announced and potential special or promotional opportunities As such the Proof of Authorization becomes part of this License Agreement Installation of the Software Installation refers to the process of unpacking or copying the files included in the Software Distribution to an Installation Target Installation Target refers to the target of an installation operation Targets are defined among other parameters in terms of the following definitions 1 CPU refers to a central processing unit which is able to store and or execute the Software a server personal computer virtual machine or other computer like device using at most two 2 processors 2 Site refers to a single site of a company 3 Corporate refers to an unlimited number of sites of the company 4 Developer CPU refers to a single CPU used by at most one 1 developer Additional terms may be defined as part of the Proof of Authorization When installing the Software on a server CPU for use by other CPUs in a network Licensee must obtain a License for the server CPU and for all client CPUs attached to the network which will make use of the Software by copying the Software in binary or source form from the server into their CPU memory If a
117. dard mxODBC error handler appends tuples exception class exception value for all messages which the interfaces receives from the underlying ODBC driver or manager for this cursor See section 10 Error Handlers for details The list is cleared by all cursor methods calls prior to executing the call except for the fetch calls to avoid excessive memory usage and can also be cleared explicitly by executing del cursor messages An application can use the information in this list to verify correct operation of the method calls This is particularly useful if the ODBC driver or database splits the error information across multiple error messages In such a case only one of the messages will be used to raise the exception by mxODBC usually the top most but this message may not provide enough information to track down the problem paramesunt This read only attribute specifies the number of parameters in the current prepared command The attribute is 1 in case this information is not available paramstyle Sets the default parameter binding style of the cursor The value is initially set to the value of connection paramstyle of the creating connection The value takes affect on the next call to a cursor execute method The attribute can be set or queried and takes the following string values following the paramstyle module global as defined in the DB API qmark default This is the default ODBC parameter binding
118. e mxODBC Python ODBC Database Interface 154 e The default used to be lock level 3 the ODBC driver does not allow multiple threads to use it and everything is serialized This could result in the application using mxODBC and unixODBC to hang during long running queries Fixing this was easy but not well documented in unixODBC Setting the thread lock level to O driver is fully thread safe allowed the application to run other queries in parallel e g PostgreSQL Description PostgreSQL driver for Linux amp Win32 Driver usr local lib libodbcpsgl so Setup usr local 1lib libodbcpsqlS so Threading 0 e Starting with unixODBC 2 3 1 the default thread lock level now is 0 so the above is no longer necessary e These are the available thread lock levels from unixODBC s _handle c Level 0 Only the DM internal structures are protected the driver is assumed to take care of it s self Level 1 The driver is protected down to the statement level each statement will be protected and the same for the connect level for connect functions note that descriptors are considered equal to statements when it comes to thread protection Level 2 The driver is protected at the connection level only one thread can be in a particular driver at one time Level 3 The driver is protected at the env level only one thing at a time By default the driver open connections with a lock level of 3 this can be changed by adding
119. e owner None table None colma None sais 99 foreignkeys primary_qualifier None primary_owner None pimary_table None foreign_qualifier None foreign _owner None foreign_table None eccceeeees 100 paman ADE tore E 100 a A A A discuss 100 2etypelnto sqlivPO siga 101 primarykeys qualifier None owner None table None 104 procedures qualifier None owner None procedure None 105 procedurecolumns qualifier None owner None procedure None column NON6 ooooccccccnnnnononnnnncncnnnanannncnnos 106 mxODBC Python ODBC Database Interface specialcolumns qualifier None owner None table None coltype SQL BEST ROWID scope SQL SCOPE_SESSION nullable SOL NO NULL cnica ci n 109 SOL BEST RO WD cerniere naran atdids 109 SOL ROWN R stella eto eel da eat bs aad 109 SOL SCOPE CURRO sia 109 SOL SCOPE TRANSACTION uta sii 109 SOLESCOPE SESSION sii 109 SOLNO NUDE eraser a doll li 109 SOL NUELABLE iaa dehaimertnraeen 109 Statistics qualifier None owner None table None unique SQL INDEX_ALL accuracy SQL QUICK oo 111 SOL INDEX UNIQUE 0 riscos 111 SOLIN DEX AL iis erick vs E a E E A 111 SOLENSURE sa ES 111 OEO 6 aro deca lecitina ad 111 tables qualifier None owner None table None type None 113 tableprivileges qualifier None owner None table None 113 lel Cursor OD Ec ATHDULES acia 114 MSI 114 OS O LA 114 COI COUN Ei saab o bos 115 COMMA A 115 CONDECION ii 115 SCUPSONL
120. e Fixed the documentation w r to debugging builds The default configuration does contain the debugging code See the debugging section for details on how to build a debugging version e Changed handling of warnings during database connect warnings will no longer be reported as exceptions This should allow connects to e g MS SQL Server to work without having to recompile mxODBC on Windows mxODBC Python ODBC Database Interface 180 Fixed a bug in the handling of direct execution executedirect Input parameters passed to executedirect will be bound using Python bindings Reverted a change introduced in 2 0 0 which prevered the ODBC 3 5 data types for date time values over the old ones The MS ODBC manager has massive problems with these which cause all queries involving date time columns to fail mxODBC 2 0 1 will no again use the old type codes which work fine with all ODBC drivers managers Added experimental SAP DB support as new subpackage mx ODBC SAPDB Added more tests to the test script 20 Copyright License 20 181 Copyright amp License 1997 2000 Copyright by IKDS Marc Andr Lemburg All Rights Reserved mailto mal lemburg com 2000 2013 Copyright by eGenix com Software GmbH Langenfeld Germany All Rights Reserved mailto info egenix com This software is covered by the eGenix com Commercial License Agreement which is included in the following section The text of the license is also
121. e can now be much enhanced and increased to levels beyond that of mxODBC 3 1 and previous releases by adjusting the default cursor type to forward only cursors connection mx ODBCO Windows DriverConnect la connection cursortype mx ODBC Windows SQL CURSOR FORWARD ONLY Cursors created on this connection will then default to forward only cursors instead of the mxODBC 3 2 default for SQL Server of using static cursors cursor Connection cursor The performance increase compared to mxODBC 3 2 1 is enormous from 2 3x faster executes fetches for average queries up to 300x faster for simple cases In mxODBC 3 3 we will switch to using forward only cursors per default for all database backends e IBM DB2 can benefit from the same performance enhancements using forward only cursors The effect is a lot smaller but still noticeable up to 2x faster executes fetches with forward only cursors compared to mxODBC 3 2 1 e Added documentation to explain the different cursor types compatibility with different database backends and effects on performance mxODBC Python ODBC Database Interface 168 Fixes e Fixed a problem with using mxODBC cursors as context managers these worked fine in Python 2 6 but had stopped working in Python 2 7 due to changes in the Python internals Changes from 3 2 0 to 3 2 1 Feature Enhancements e The next SQLAlchemy release will be fully compatible with mxODBC 3 2 1 Many thanks g
122. e driver does not support scrollable cursors meaning that cursor scroll will only work using the built in mxODBC emulation for forward scrolling Example Configuration for Unix To be able to use the Oracle Instant Client you have to create a tnsnames ora file providing the network configuration details of the target database ORACLE11GR2 DESCRIPTION ADDRESS PROTOCOL TCP HOST oraclellgr2 example net PORT 1521 CONNECT DATA SERVER DEDICATED SERVICE NAME praclellgrz example net Add an Oracle driver section to the odbcinst ini file the location of the driver file may be different on your system ODBC Drivers OracleInstantClient Installed OracleInstantClient Description Oracle 11g ODBC Driver Driver opt oracle instantclient 11 2 libsqora so 11 1 setup FileUsage CPTimeout CPReuse I Edit the odbc ini file based on the above tnsnames ora settings Note that the location of the driver file depends on your installation It is also necessary to point LD LIBRARY PATH to the directory where the driver itself is located oraclellgr2 Driver opt oracle instantclient 11 2 libsgqora so 11 1 ServerName oraclellgr2 DSN driver options Application Attributes T Attributes W BatchAutocommitMode IfAllSuccessful BindASFLOAT E CloseCursor F DisableDPM F DisableMTS T EXECSchemaOpt EXECSyntax T Failover T FailoverDelay
123. e entry per INI section of the ODBC INI file used for user specific settings and user DSNs See 3 2 5 Available Data Source Types DSNs for details on the different DSN types 21 mxODBC Python ODBC Database Interface 3 2 5 Available Data Source Types DSNs 22 There are three kinds of data sources that you can install on Windows machines 1 User Data Sources User DSN 2 System Data Sources System DSN 3 File Data Sources File DSN User Data Sources User DSN User data sources are only visible to the user creating them Other users normally do not have access to these data source definitions When running an application that is meant to run as service you have to make sure that you create the user data source under the user name of the service If you intend a data source to be available for all users or to avoid permissions problems creating a system data source is a better option When connecting to a user DSN you have to specify the DSN name as part of the connection string of mx ODBC Windows DriverConnect using the form DSN mydsn If you use the mx ODBC Windows Connect API to connect pass the DSN name as first parameter System Data Sources System DSN System data sources are available to all users of the system This is the recommended setup if you run services that need to access the data sources from more than just one account When connecting to a system DSN you have to specify the DSN
124. e the connection to operate in auto commit mode again Setting it to False will have the connection use manual commit The attribute also allows querying the current commit mode in the same way Alternatively you Can use a connection setconnectoption SQL AUTOCOMMIT SQL AUTOCOMMIT ON call to turn on auto commit and connecti n setconnectopteion SOL AUTOCOMMIT sULsAUTOCOMMIY OFF to turn it off again Similarly connection getconnectoption SQL AUTOCOMMIT will return the current option value as tuple Stored Procedures There are two ways to call a stored procedure in mxODBC directly using the callproc cursor method or indirectly using the following standard ODBC syntax for calling stored procedures The ODBC syntax for calling a stored procedure is as follows call procedure name parameter parameter Using the above syntax you can call stored procedures through one of the execute Calls e g cursor execute call myprocedure 1 2 will call the stored procedure myprocedure with the input parameters 1 2 After calling callproc or execute you can then access output from the stored procedure as one or more result sets using the standard fetch cursor methods If the stored procedure has generate multiple result sets skipping to the next result set is possible by calling the nextset cursor method Input Output and Output Parameters mxODBC does not support input output or outpu
125. eTranslationOption utfl6 For DataDirect use this setting UnicodeTranslationOption utf8 CharacterTranslationOption all PreFetch 256 Socket 8192 e Edit your odbc ini file and add a Netezza section the location of the driver may be different on your system It is also necessary to point LD LIBRARY PATH to the directory where the driver itself is located netezza Driver usr local nz 1ib64 libnzodbc so Description NetezzaSQL ODBC Servername netezza example net Port 5480 Database mydb username Password ReadOnly false ShowSystemTables false LegacySQlTables false LoginTimeout 0 QueryTimeout 0 DateFormat 1 NumericAsChar false SQLBitOneZero true SEFTPORLE false securityLevel preferredUnSecured caCertFile Needed by the DataDirect ODBC manager values 1 UTF 16 2 UTF 8 DriverUnicodeType 1 e Using these settings you can then connect to Netezza using a simple connection string such as DSN netezza UID username PWD password DataDirect ODBC Driver for Netezza Homepage http www datadirect com Other Databases If you want to run mxODBC in a Unix environment and your database doesn t provide an Unix ODBC driver you can try the drivers sold by these ODBC driver specialists 4 Accessing Popular Databases 4 11 1 EasySoft ODBC Driver Packages Homepage http www easysoft com EasySoft also maintains the open source ODBC manager unixODBC
126. ecial column type and thus no type code is equal to this type object SQL NULL values are represented by the Python None singleton on input and output 136 10 mxODBC Exceptions and Error Handling 10 10 1 137 mxODBC Exceptions and Error Handling The mxODBC package and all its subpackages use the DB API 2 0 exceptions layout All exceptions are defined in the submodule mx ODBC Error but also imported into the top level package module mx ODBC as well as all sub packages Note that all sub packages use the same exception classes so writing cross database applications is simplified this way The exception values are either e a single string or o a tuple having the format sqlstate sqltype errortext lineno SQL state sqistate and type sqltype are defined by the ODBC standard and may be extended by the specific ODBC driver handling the connection Please see the ODBC driver manual for details Lineno refers to the line number in the mxODBC c file to ease debugging the package Note on the mx ODBC Error Module If you want to import the exception classes from the mx ODBC Error submodule you have to use the from import form from mx ODBC Error import ProgrammingError The reason is that the Error base class is imported into the top level mx ODBC package when loading it shadowing the module of the same name With the above form Python will lookup mx ODBC Error in the module dictionary instead of the mx ODBC pa
127. ed C buffer to store data from this column if SQL_C_DEFAULT were specified on the SOLBindCol SQLGetData and SOLBindParameter calls This length does not include any null terminator For exact numeric data types the length accounts for the decimal and the sign DECIMAL DIGITS SMALLINT The scale of the column NULL is returned for data types where scale is not applicable NUM_PREC_RADIX SMALLINT Either 10 or 2 or NULL If DATA_TYPE is an approximate numeric data type this column contains the value 2 then the COLUMN SIZE column contains the number of bits allowed in the column If DATA_TYPE is an exact numeric data type this column contains the value 10 and the COLUMN SIZE contains the number of mxODBC Python ODBC Database Interface 98 Column Name Column Datatype Comment decimal digits allowed for the column For numeric data types the database can return a NUM_PREC_RADIX of either 10 or 2 NULLABLE SMALLINT not NULL SQL NO_NULLS if the column does not accept NULL values REMARKS VARCHAR 254 May contain descriptive information about the column or NULL It is possible that no usable information is returned in this column due to optimizations COLUMN DEF VARCHAR 254 The column s default value If the default value is a numeric literal then this column contains the character representation of the numeric literal with no enclosing s
128. ee 14 1 Running mxODBC from a CGI script for more details on getting ODBC drivers to work in such an environment mod_wsgi and Python 2 7 On Windows there is also another issue to consider when running the combination Apache mod_wsgi and Python 2 7 Due to changes in Python 2 7 manifests for the Visual C runtime environment needed by Windows to find the right DLL to load are no longer added to Python extensions since this caused problems with loading them into Python processes see Python Issue 4120 Unfortunately neither mod_wsgi nor Apache appear to include the required manifests either This causes an import error when trying to load mxODBC into a mod _wsgi run process since Windows cannot resolve the DLL references in mxODBC without the manifest mxODBC Python ODBC Database Interface 14 3 14 4 158 Since this affects not only mxODBC but other Python C extensions as well you may want to use a work around until either Apache or the mod_wsgi team solves the problem Manifest work around Adding the VC manifests to the Apache process is explained in this posting You will also have to install the MS VC 2008 CRT SP1 redistributable package on the server running Apache With those changes in place mxODBC should load without problems Freezing mxODBC using py2exe Thomas Heller has written a great tool which is based on distutils The tool allows you to freeze your application into a single standalone Wind
129. eement will automatically terminate upon a material breach of its terms and conditions if not cured within thirty 30 days of written notice by eGenix com Upon termination Licensee shall discontinue use and remove all installed copies of the Software Indemnification Licensee hereby agrees to indemnify eGenix com against and hold harmless eGenix com from any claims lawsuits or other losses that arise out of Licensee s breach of any provision of this License Agreement Third Party Rights Any software or documentation in source or binary form provided along with the Software that is associated with a separate license agreement is licensed to Licensee under the terms of that license agreement This License Agreement does not apply to those portions of the Software Copies of the third party licenses are included in the Software Distribution High Risk Activities The Software is not fault tolerant and is not designed manufactured or intended for use or resale as on line control equipment in hazardous environments requiring fail safe performance such as in the operation of nuclear facilities aircraft navigation or communication systems air traffic control direct life support machines or weapons systems in which the failure of the Software or any software tool process or service that was developed using the Software could lead directly to death personal injury or severe physical or environmental damage High Risk Activities
130. ense files please copy them to a location on your sys path Or PYTHONPATH If you installed Python to e g C Python26 on Windows or usr local bin python on Unix or Mac OS X the typical location for installation of the license files would be C Python26 Lib site packages or usr local lib python2 6 site packages Use the following command to see the sys path that your Python version uses python a import sys print p Jomn sys path Step by step Installation Guide Step 1 Determine whether you are using a UCS2 or UCS4 build of Python Windows users always need the UCS2 version Mac OS X should also try the UCS2 version first Unix users will most likely need the UCS4 version To find out which variant your Python version was compiled with run the following command python c print UCS s len u x encode unicode internal This will either print out UCS2 or UCS4 Step 2 Next install the egenix mxodbc egg package in your Python installation 2 Installation 13 Note that you may need to have admin or root privileges in order to successfully complete the following step unless you are using a virtualenv based setup If you got UCS2 in step 1 run the following command using the easy install script from the Python installation you intend to use easy install i http downloads egenix com python index ucs2 egenix mxodbc If you got UCS4 in step 1 use this command easy install i htt
131. enses in order for the mxODBC to startup correctly Go to the temporary directory where you unzipped the license archive and change to the license subdirectory which contains the license for the installation you are currently working on Copy the two files mxodbc_license py and mxodbc license txt from the license subdirectory to the Python site packages directory Step 4 Test the installation by trying to import mxODBC S python Python 2 6 4 r264 75706 Jan 4 2010 20 40 33 SCC d2 l SUSE Lams on Linux Type help copyright credits or license for more information gt gt gt import mx ODBC Manager gt gt gt If you don t get any ImportError you have successfully installed mxODBC 2 Installation 2 4 3 Uninstall 17 Automatic Uninstall In order to uninstall the mxODBC package run the setup py of the installation package using the uninstall command and the same options you passed to the install command when you installed the package python setup py uninstall Manual Uninstall If you no longer have the older installation package just remove the site packages mx ODBC directory with all its subdirectories mxODBC Python ODBC Database Interface 3 1 3 1 1 18 Access Databases using mxODBC mxODBC provides an easy to use way of accessing the ODBC API of ODBC managers and drivers from Python Together with a suitable ODBC driver installed on the machine where you are running the Pyth
132. er Converts Language Events to Unicode More information about the MS SQL Server ODBC Driver and the various connection parameters and options are available on the MSDN Library site MS SQL Server ODBC Driver Programmer s Guide Access Violations If you are experiencing problems related to access violations like e g ProgrammingError 3 7000 Oy Microsoft ODBC SOL Server Driver Syntax error or access violation 4498 a possible reason could be that you are using a function or stored procedure which is generating output using PRINT or that it uses RAISEERROR to report an error with the parameters or values 4 Accessing Popular Databases 4 2 4 2 1 39 Another possible reason is that the ODBC driver for SQL Server does not support the syntax you are using or that bound parameters are not allowed at that location in the SQL statement As work around you can use Python string formatting to insert the data verbatim directly into the SQL statement Distributed Transaction Managers If you are using a transaction manager e g MS DTC you can sometimes get warnings like the following mxODBC Warning LS O LOCO 1312 Microsoft ODBC SOL Server Driver SOL Server OLE DB provider returned message New transaction cannot enlist in the specified transaction coordinator 4606 This is a problem related to the used transaction manager rather than mxODBC or the database Please consult your DBA for help Note t
133. er None foreign table None Query the database schema for information on foreign keys The method has two modes of operation depending on which parameter is set primary table The method returns a list of foreign key columns in other tables that refer to the primary key column of the given table and the primary key column of the given table itself foreign table The method returns a list of foreign key columns in a table that refer to the primary keys of other tables and the primary key columns of those other tables This is useful to determine the relationships between the tables in a database schema The catalog method generates a result set having the following schema Column Name Column Datatype Comment PKTABLE_ CAT VARCHAR 128 Always NULL PKTABLE SCHEMA VARCHAR 128 The name of the schema containing PKTABLE_NAME PKTABLE_NAME VARCHAR 128 not Name of the table containing the primary key NULL PKCOLUMN_NAME VARCHAR 128 not Primary key column name NULL FKTABLE_ CAT VARCHAR 1 28 Always NULL FKTABLE SCHEMA VARCHAR 128 The name of the schema containing FKTABLE_NAME FKTABLE_NAME VARCHAR 128 not Name of the table containing the foreign key NULL FKCOLUMN_NAME VARCHAR 128 not Foreign key column name NULL ORDINAL_ POSITION SMALLINT not NULL The ordinal position of the column in the key starting at 1 100 7 mxODBC Cursor Objects
134. ermissions eGenix com recommends setting up System Data Sources as these are usually accessible by all accounts on a Windows machine Using the mxODBC connection constructor mx ODBC Windows DriverConnect you can then setup a connection to the database Looking for Windows ODBC Drivers Microsoft supports a whole range of desktop ODBC drivers for various databases and file formats These are available under the name ODBC Desktop Database Drivers search the MS web site for the exact URL wx1350 exe and also included in the more up to date Microsoft Data Access Components MDAC archive mdac_typ exel It includes ODBC drivers for Access dBase Excel Oracle Paradox Text flat file CSV FoxPro MS SQL Server If you need to connect to databases running on other hosts please contact the database vendor or check the SQLSummit list of ODBC drivers mxODBC Python ODBC Database Interface Di 3 2 3 3 2 4 20 Installing Windows ODBC Drivers Please consult the documentation of your database for ODBC driver installation instructions These are usually installed in the same way as any other application on Windows but their respective setup wizards and options are usually different in layout and depend on the target database Setting up an ODBC Data Source Data sources are setup using the Windows ODBC Manager on Windows This can be found in the in the Control Panel as Administrative Tools and is called Data Sou
135. essors FreeBSD and Sun Solaris are supported Unix platforms eGenix com can also provide custom builds for other Unix platforms on request Please write to sales egenix com for details Python 2 4 or later needs to be installed and working On Linux FreeBSD and Solaris the binary package includes support for the iODBC the unixODBC and the DataDirect managers You must have at least one of these installed in order to be able to connect to ODBC data sources Please use the ODBC manager GUI interfaces to configure the data sources Alternatively you can choose to use a DSN less setup which defines all connection details in the connection string mx ODBC Manager prefers iODBC over unixODBC over DataDirect if more than one ODBC driver manager is installed You should setup at least one configured and running ODBC data source for testing purposes Mac OS X Mac OS X 10 4 10 5 Intel and PPC 32 bit and Mac OS X 10 6 Intel 64 bit are supported Python 2 4 or later needs to be installed and working Mac OS X uses a variant of iODBC as system ODBC manager On Mac OS X 10 4 and 10 5 this comes pre installed with the system On Mac OS X 10 6 the ODBC manager is available from Apple as separate download Please use the ODBC manager GUI interfaces to configure the data sources Alternatively you can choose to use a DSN less setup which defines all connection details in the connection string If you want to use the unixODBC manager from MacPorts
136. et after opening the cursor will not be visible to the client mxODBC uses these cursors as default for backends which support scrollable cursors SQL CURSOR_KEYSET DRIVEN Keysets are sets of columns in the result set that provide unique keys to the rows in the result set Keyset driven cursors fix the memberships and order of the rows in the result set using these keysets Unlike static cursors they don t create a copy of the result set SQL CURSOR DYNAMIC Dynamic cursors are the opposite of static cursors All changes to the result set after opening it are visible on the next fetch operation Please refer to section 5 7 ODBC Cursor Types for more details on cursor types Performance Warning Please note that using cursor types other than SOL CURSOR FORWARD ONLY may have a significant effect on the performance of fetch operations datetimeformat Use this instance variable to set the default output format for date time timestamp columns of all cursors created using this connection object Possible values are see the Constants section 10 5 for details DATETIME DATETIMEFORMAT default DateTime and DateTimeDelta instances PYDATETIME DATE TIME FORMAT datetime date datetime time datetime datetime instances Only available using Python 2 4 and later TIMEVALUE DATETIME FORMAT Ticks number of seconds since the epoch and tocks number of seconds since midnight TUPLE DATETIMECOBMAT Python tuples as de
137. exes tables qualifier None owner None table None type None Query the data source for information on tables stored in the database type may be set to a comma separated string of database table types using all uppercase characters The exact list of available types is data source dependent Common types include TABLE VIEW SYSTEM TABLE GLOBAL TEMPORARY LOCAL TEMPORARY ALIAS SYNONYM This method is useful for checking whether a table exists and is accessible by the current user or not It also aids in database schema introspection The catalog method generates a result set having the following schema Column Name Column Datatype Comment TABLE_CAT VARCHAR 1 28 The name of the catalog containing TABLE_SCHEM This column contains a NULL value TABLE_SCHEMA VARCHAR 1 28 The name of the schema containing TABLE NAME TABLE_NAME VARCHAR 1 28 The name of the table or view or alias or synonym TABLE_TYPE VARCHAR 1 28 Identifies the type given by the name in the TABLE_NAME column It can have the string values TABLE VIEW INOPERATIVE VIEW SYSTEM TABLE ALIAS or SYNONYM REMARKS VARCHAR 254 Contains the descriptive information about the table tableprivileges qualifier None owner None table None Query the data source for information on table privileges associated with database tables 113 mxODBC Python ODBC D
138. f this attribute will not change the warning format for existing cursors using this connection Additional Attributes In addition to the above attributes all exception objects used by the connection s subpackage are also exposed on the connection objects as attributes e g connection Error gives the Error exception of the subpackage which was used to create the connection object 6 mxODBC Connection Objects See the Exceptions and Error Handling section 10 for details and names of these error attributes 83 mxODBC Python ODBC Database Interface 7 1 7 1 1 7 1 2 84 mxODBC Cursor Objects These objects represent a database cursor an object which is used to manage the context of a database query operation This includes preparing and parsing the query or command to be executed on the connection executing the query or command one or multiple times and providing a pointer into the result set or sets generated by queries Relationship between Cursors and Connections Dependency on the Connection Object Cursors are created through a database connection As a result cursor objects are only usable as long as the connection object exists and the associated database connection is open and working All operations of a cursor are done through the connection that was used to create it The scope and default settings of a cursor are defined by the connection Once created you can change various settings of the cursor e g
139. fined in the Supported Data Types section 10 Please note that in mxODBC 3 3 this will always be the default value 77 mxODBC Python ODBC Database Interface 78 JIRING DATETIMEPORMAT Python strings The format used depends on the internal settings of the database See your database s manuals for the exact format and ways to change it We strongly suggest always using the DateTime DateTimeDelta instances Note that changing the values of this attribute will not change the date time format for existing cursors using this connection This value is inherited by all cursors created from the connection at creation time Note that changing the value of this attribute will not change the date time format for existing cursors using this connection dbms name String identifying the database manager system dbms version String identifying the database manager system version decimal Format Use this instance variable to set the default output format for decimal and numeric columns of all cursors created using this connection object Possible values are see the Constants section 10 5 for details FLOAT DECIMALFORMAT default Values are returned as Python floats DECIMAL DECIMALFORMAT Values are returned as Python decimal Decimal instances Only available using Python 2 4 and later This value is inherited by all cursors created from the connection at creation time Note that changing the value of this attribute
140. follows the ODBC standard of using 64 bit SQL length types unixODBC has only recently starting with version 2 2 13 switched to these longer types As a result ODBC drivers compiled against older versions of unixODBC will not work reliably with ODBC Commercial ODBC drivers for Unix are often compiled using 64 bit SQL length types and 32 bit Unicode types iODBC uses 64 bit types for both 13 5 mx ODBC unixODBC unixODBC Driver Manager Tested with unixODBC 2 3 1 unixODBC is an alternative Open Source ODBC manager for originally designed for Linux and later extended to other Unixes maintained by EasySoft It compiles against mxODBC without problems Many open source ODBC drivers are compiled against this driver manager per default so it may provide better support for those drivers than iODBC 13 mx ODBC Subpackages 13 5 1 Notes General Recommendations 64 bit Please always use the DriverConnect API to connect to the data source if you need to pass in extra configuration information such as names of log files etc Between unixODBC 2 3 0 and unixODBC 2 3 1 the unixODBC project switched the library name of the ODBC manager library from libodbc so 1 to libodbc so 2 to signal the change in their ABI on 64 bit platforms see below This renaming affects both 32 and 64 bit versions of unixODBC Since eGenix com compiles against unixODBC 2 3 1 mxODBC will look for a libodbc so 2 library file and this may not be availab
141. function Please refer to the ODBC Documentation for more information Note that while the API function also supports setting character fields the method currently does not know how to handle these Note for ADABAS SAP DB MAX DB users Adabas SAP DB and MAX DB can emulate several different SQL dialects They have introduced an option for this to be set These are the values you can use 1 ADABAS 2 DB2 3 ANSI 4 ORACLE 5 SAPR3 The option code is SOL CONNECT_OPT DRVR_ START 2 according to the Adabas documentation Please consult your driver documentation for details mxODBC Python ODBC Database Interface enter 1 Returns the connection itself This method makes connection objects usable as context manager together with the __exit__ method and is called when entering a with block new in Python 2 5 lt BRIT exc Type exe value exc Eb Returns True in case exc_type is set to None no exception set and commits the current transaction Returns False in case exc_type is set to an exception and rolls back the current transaction This method is part of the context manager API and is called when leaving a with block new in Python 2 5 6 8 Connection Object Attributes 76 Autocom E Writeable attribute to query and set the auto commit status of the connection Returns True if the connection is operating in auto commit non transactional mode Returns False is the connection is operating in manual comm
142. ge the default warning reporting behavior of mxODBC in case you don t want to define your own errorhandler The DB API 2 0 mandates that database warnings must raised as mx ODBC Warning exception but mostly because at the time of writing the Python warning module did not yet exist For some applications it may be more useful to report warnings via Python warnings The application could then use the standard Python warning filters to report or filter the warnings in an appropriate way Another alternative is to simply ignore such warnings Some ODBC are rather verbose when it comes to warnings Note that a possibly registered errorhandler will still be called in all these cases however the mxODBC default error handler will use the warningformat to determine how to react to database warnings Possible values are see the Constants section 10 5 for details ERROR WARNINGFORMAT default Report warnings in the usual DB API 2 0 way and raise a Warning exception WARN WARNINGFORMAT Instead of raising a Warning exception issue a mx ODBC DatabaseWarning which is a Python Warning subclass and can be filtered using the standard Python warnings module mechanisms IGNORE_WARNINGFORMAT Silently ignore the database warning The warning will still be added to the message attribute but no further action is taken This value is inherited by all cursors created from the connection at creation time Note that changing the value o
143. given in the above table is also made available though the cursor s description tuple as type code entry position 1 for result set generating SQL commands You can compare this value directly to the appropriate soL object values e g test for SOL CHAR Or SQL VARCHAR Output Type Converter Functions The last section defined the standard mapping mxODBC applies when fetching output data from the database You can modify this mapping on the fly by defining a cursor converter function which takes three arguments and has to return a 2 tuple def converter position sgqltype sqllen modify sgqltype and sqllen as appropriate return sqltype sqllen Now tell the cursor to use this converter cursor setconverter converter or 3 tuple def converter position sgqltype sqllen modify sgqltype and sgllen as appropriate provide binddata as input e g for file names which should be used for file binding return sqltype sqllen binddata Now tell the curser to use this converter cursor setconverter converter The converter function is called for each output column prior to the first fetch operation executed on the cursor The returned values are then interpreted as defined in the table in section 8 3 Output Conversions and SQL Type Input Binding The parameters have the following meanings position identifies the O based position of the column in the result set sqltype is usually one of the SQL data type
144. gs even integers and floats The ODEC driver implements the necessary conversions mxODBC uses the mxODBC Python ODBC Database Interface 50 Python Type binding method to bind the input parameters see the Python Type Input Binding section 8 4 for more details Native Unicode is not supported by the MySQL ODBC driver You can use the auto transcoding feature of mxODBC to work around this by setting the ODBC driver database character set to utf8 and the connection encoding to utf 8 on the mxODEC client side Using a MySQL5 Windows ODBC driver character setting of utf 8 with hyphen can cause the driver to segfaults so care must be taken using the right spelling for the character set setting The MySQL ODBC driver does not always update the rownumber to the correct value especially when using scrol11 When using the ODBC driver RPMs available from www mysql com please be sure to also have the MySQL shared libs RPM and the MySQL development RPM installed Some older MySQL ODBC driver setups eGenix com has tested showed some serious memory leaks on Linux machines Please check your setup for such leaks before going into production There are no known leaks in mxODBC itself Example Configuration for Unix Add a MySQL driver section to the odbcinst ini file the location of the driver file may be different on your system ODBC Drivers MySQL Installed MySQL Description MySQL ODBC Driver Driver
145. hat even though the above exception is raised by the cursor execute method the fact that it is a warning suggests that the executed operation was indeed executed on the cursor Other Common Problems and Solutions A general description of the problems you might experience when accessing the MS SQL Server using ODBC is described in the article Using ODBC with Microsoft SQL Server Even though it s dated September 1997 it provides some insights into the design and workings of the MS SQL ODBC driver MS Access Database Available ODBC Drivers MS Access ODBC Driver Tested with MDAC 2 8 SP1 Access ODBC driver MS Access ships with an ODBC driver for the database which is then installed on the same machine as MS Access or Office The drivers are also available separately as part of the MDAC package MDAC 2 8 SP1 can be downloaded from this page http www microsoft com downloads details aspx familyid 78CAC895 EFC2 4F8E A9E0 3A1AFBD5922E amp displaylang en mxODBC Python ODBC Database Interface 4 3 4 3 1 40 MDBTools ODBC Driver Homepage http mdbtools sourceforge net This package provides a very limited ODBC driver which allows accessing Access database files directly without having to install or run MS Access It is mostly used on Unix platforms to extract data from existing MS Access database files Oracle Available ODBC Drivers Oracle Instant Client ODBC driver Homepage http www oracle com techn
146. having more than one active result set per connection This means that you cannot have two cursors on the same connection which both have active result sets Starting with SQL Server 2005 there is a connection option which can be used to enable the MARS feature of SQL Server Native Client which enables working with multiple active result sets on the same connection from mx ODBC Manager import DriverConnect SQL options SQL COPT SS MARS ENABLED SQL MARS ENABLED YES db DriverConnect DSN mssqlserver2008 UID sa PWD dbsOR X9 rxD connection eptions opti ns This option is available on SQL Server Native Client for Windows and Linux The FreeTDS ODBC driver 0 91 does not support this option mxODBC Python ODBC Database Interface 34 MS SQL Server ODBC Driver for SQL Server 2000 Tested with MS SQL Server ODBC driver from MDAC 2 8 SP1 If you still use SQL Server 2000 please get the latest ODBC driver for SQL Server from the Micrsoft MDAC package MDAC 2 8 SP1 can be downloaded from this page http www microsoft com downloads details aspx familyid 78CAC895 EFC2 4F8E AQEO 3ATAFBD5922E amp displaylang en Configuring the SQL Server ODBC Driver Client Network Protocol When configuring an ODBC data source using the MDAC SQL Server ODBC Driver you can choose the protocol by clicking on the Client Configuration button on the second wizard page Note that the MDAC ODBC drivers do not support shared memory access U
147. he MARS feature in 19 History amp Changes 169 SQL Server Native Client The connection cursor constructor now has a new cursor_options parameters which allows configuring the cursor with a set of cursor options The scroll method supports far more ODBC drivers than before The scroll method no longer needs a working rownumber and rowcount implementation from the ODBC drivers in most cases Updated the SQL lookup object to include more ODBC SQL parameter codes including special ones for SQL Server and IBM DB2 Added DataDirect specific SQL lookup object attributes mx ODBC Manager will now prefer unixODBC over iODBC Previous mxODBC releases used the order ODBC unixODBC DataDirect when looking for a suitable ODBC manager on Unix platforms unixODBC is more widely supported nowadays and provides better Unicode support than iODBC Driver Compatibility Added work around for Oracle Instance Client to prevent use of direct execution cursor executedirect will still work but won t actually use direct execution with the Oracle driver Added work around for Oracle Instant Client to prevent segfaults in the driver when querying the cursor rowcount or cursor rownumber Added check to make sure that Python type binding mode is not used with Oracle Instance Client as this can cause segfaults with the driver and generally doesn t work Added a work around to have the IBM DB2 driver return correct rowcount values
148. he name will result in an empty result set You can use connection getinfo SQL IDENTIFIER CASE to determine how the database stores identifiers See the ODBC Documentation for details Switching between Search Patterns and Identifier Matching Some ODBC drivers support adjusting the catalog method interface to interpret the parameters as case insensitive identifiers instead In mxODBC this can be enabled using Cursor setcursoropti n 50L ATTR METADATA ID SOL TRUE The setting persists on the cursor It can be switched off again using Cursor sSeLcursoropreion SUL ATTR METADATA ID SUL FALSE which then causes the catalog methods to interpret the parameters as case sensitive search patterns again Whether this really helps with the problem described above depends on the application Unicode All catalog methods accept Unicode parameters if the ODBC drivers provide the necessary support for this Available Catalog Methods Please note that the drivers may not implement all catalog methods that mxODBC supports In such a case you will get a NotSupportedError or AttributeError exception when trying to use a method that is not supported by the ODBC driver The following catalog methods are supported by mxODBC Columns qualifier None owner None table None column None Query the database schema for information on table columns column allows restricting the results to a single column of a table Depending
149. he standard fetch and nextset APIs to access the results The key to making this work is by not passing in any variable for the output REF CURSOR when calling the stored procedure Oracle Base has a more detailed article on this e Using Ref Cursors To Return Recordsets Thanks to Etienne Desgagn for pointing out this solution 64 5 mxODBC Overview 5 6 2 SQL Output Statements in Stored Procedures 5 5 7 1 You should not use any output SQL statements such as PRINT in the stored procedures since this will cause at least some ODBC drivers notably the MS SQL Server one to turn the output into an SQL error which causes the execution to fail On the other hand these error messages can be useful to pass along error conditions to the Python program since the error message string will be the output of the PRINT statement ODBC Cursor Types Starting with mxODBC 3 2 mxODBC supports several different ODBC cursor types These types define how the cursors will be used by the application and whether or not the application will see changes to the result set while fetching the result set rows As with other cursor settings the ODBC cursor type default value can be defined on the mxODBC connection object and the setting is then inherited by the mxODBC cursor objects created on that connection Subsequent changes to the cursor type on the cursor do not affect the setting on the connection Adjusting Inspecting the
150. hich you wrote the evaluation license request in form of a ZIP license archive attached to the license email usually named licenses zip The license archive licenses zip contains one subdirectory per license you bought The directories are named after the license key for each license A typical license archive will have these contents 1008 76 9 0322 0926 2560 0429 mxodbe license py 2100 8 789 0922 0920 2508 0d29 maodbe license Ext 2100 8089 0312 0926 240068 6929 mx0dbe license py 2100 8089 0312 0926 2668 6929 mx0db 6 11c ens e txt in the above example the license archive contains the files for two product licenses In order to install the license files please unzip the license archive to a temporary directory In order for mxODBC to pick up the correct license files please copy them to a location on your sys path Or PYTHONPATH If you installed Python to e g C Python26 the typical location for installation of the license files would be C Python26 Lib site packages Use the following command to see the sys path that your Python version uses python c import sys print 1 Jo mtsys pera Step by step Installation Guide Step 1 After you have downloaded the Windows installer of the egenix mxodbc distribution double click on the exe file to start the installer mxODBC Python ODBC Database Interface 2 2 4 10 Note Depending on your Python installation you may need admin privileges on Wi
151. hing from Windows to Unix or the other way around While the mxODBC API names and signatures don t change you will likely have to make some application level changes to accommodate for differences in the ODBC drivers you are using 6 mxODBC Connection Objects 6 1 6 2 6 3 69 mxODBC Connection Objects Connection objects provide the communication link between your Python application and the database They are also the scope of transactions you perform Each connection can be setup to your specific needs multiple connections may be opened at the same time Subpackage Support Connection objects are supported by all subpackages included in mxODBC The extent to which the functionality and number of methods is supported may differ from subpackage to subpackage so you have to verify the functionality of the used methods esp the catalog methods for each subpackage and database that you intend to use Connection Type Object mxODBC uses a dedicated object type for connections Each mxODBC subpackage defines its own object type but all share the same name ConnectionType Connection Object Constructors Connect den u ser password plear auto commit L errorhandler Non e connection optiens This constructor returns a connection object for the given data source It accepts keyword arguments dsn indicates the data source to be used user and password are optional and used for database login errorhandler m
152. horization is not permitted and requires the written prior permission from eGenix com mxODBC Python ODBC Database Interface 184 Modifications Software modifications may only be distributed in form of patches to the original files contained in the Software Distribution The patches must be accompanied by a legend of origin and ownership and a visible message stating that the patches are not original Software delivered by eGenix com nor that eGenix com can be held liable for possible damages related directly or indirectly to the patches if they are applied to the Software Experimental Code or Features The Software may include components containing experimental code or features which may be modified substantially before becoming generally available These experimental components or features may not be at the level of performance or compatibility of generally available eGenix com products eGenix com does not guarantee that any of the experimental components or features contained in the eGenix com will ever be made generally available Expiration and License Control Devices Components of the Software may contain disabling or license control devices that will prevent them from being used after the expiration of a period of time or on Installation Targets for which no license was obtained Licensee will not tamper with these disabling devices or the components Licensee will take precautions to avoid any loss of data that might resu
153. ide on http www python org Andrew Kuchling s introduction to the Python Database API is an especially good reading There are also a few books on using Python DB API compatible interfaces some of them cover mxODEC explicitly On Unix gt gt gt Import mx ODBC 10DBC gt gt gt db gt gt gt C db cursor gt gt gt c execute select count gt gt gt c fetchone 30597 gt gt gt c tables None None None None 8 gt gt gt MX ODBC Print resultset c Column 1 Column 2 Column 3 ro ro rest ro ro q dl ro ro test4 1 ea testolobs de En testblobs2 e de testdate my my testdates I uo testdatetime gt gt gt c close gt gt gt de closet gt gt gt On Windows gt gt gt import mx ODBC Windows SH aba mx ODBC Windows DriverConnect DSN database UlD user PWD passwd gt gt gt 0 db cursor gt gt gt c execute select count gt gt gt c fetchone 305 gt gt gt c tables None None None None 8 Joe Mx ODBC prine tesultset 0 Column 1 Column 2 Column 3 TI UA ttest4a q Pesthblobs En pl testblobs2 mt ey testdate E di testdates ns de testdatetime gt gt gt c close gt gt gt db close ARA As you can see mxODBC has the same interface on Unix and Windows which from test Column 4 TABLE TABLE TABLE TABLE TABLE TABLE TABLE TABLE
154. ingle quotes If the default value is a character string then this column is that string enclosed in single quotes If the default value a pseudo literal such as for DATE TIME and TIMESTAMP columns then this column contains the keyword of the pseudo literal e g CURRENT DATE with no enclosing quotes If NULL was specified as the default value then this column returns NULL If the default value cannot be represented without truncation then this column contains TRUNCATED with no enclosing single quotes If no default value was specified then this column is NULL It is possible that no usable information is returned in this column due to optimizations SQL DATA TYPE SMALLINT not NULL SQL data type This column is the same as the DATA_TYPE column SQL DATETIME SUB SMALLINT The subtype code for datetime data types SQL CODE DATE SQL CODE TIME SQL CODE_TIMESTAMP For all other data types this column returns NULL CHAR_OCTET_LENGTH INTEGER Contains the maximum length in octets for a Character data type column For Single Byte character sets this is the same as COLUMN SIZE For all other data types it is NULL 7 mxODBC Cursor Objects 99 Column Name Column Datatype Comment ORDINAL_POSITION INTEGER not NULL The ordinal position of the column in the table The first column in the table is number 1 IS_NULLABLE VARCHAR 254 Contains the string NO if the column is know
155. instead of the system iODBC manager you first have to install unixODBC from the MacPorts and then tell the Mac OS X linker where to find the ports libraries by adjusting the environment variable DYLD_LIBRARY_PATH prior to starting Python 1 Introduction export DYLD LIBRARY PATH opt local lib e You should setup at least one configured and running ODBC data source for testing purposes mxODBC Python ODBC Database Interface 2 1 2 1 1 ye 2 Installation The mxODBC database package is distributed as add on for the eGenix com mx Base Distribution egenix mx base Please visit the eGenix com web site to download the latest versions of both the eGenix com mx Base Distribution and the eGenix com mxODBC distribution for your platform and Python version IMPORTANT NOTE Before installing the egenix mxodbc package you will have to install the egenix mx base distribution which contains packages needed by mxODBC Even though both distributions use the same installation procedure please refer to the egenix mx base installation instructions on how to install that package Download the Software Automatic download If you want to use egg package archives for the mxODBC installation package tools such as easy_install or zc buildout will download the archives automatically from a special package index on the eGenix com website A separate manual download is normally not needed However you can still download the files man
156. ise transfer the Software or any part thereof or use it for the benefit of any third party iii use the Software outside the Product or for any other purpose not expressly licensed hereunder 3 the Product does not provide functions or capabilities similar to those of the Software itself i e the Product does not introduce commercial competition for the Software as sold by eGenix com 4 Licensee has obtained Developer CPU Licenses for all developers and CPUs used in developing the Product Redistribution Installation Targets any number of CPUs capable of running the Product and the Software Proof This Proof of Authorization was issued by lt name gt lt title gt Langenfeld lt date gt Proof of Authorization Key lt license key gt 20 Copyright License 191
157. ises a NotSupportedError in case a request for backward scrolling is made in such a result set Hopefully this will change as ODBC drivers become more mature setconverter converter This method sets the converter function to use for subsequent fetches Passing None as converter will reset the converter mechanism to its default setting See the Supported Data Types section 8 for details on how user defined converters work Setcursorname name Sets the name to be associated with the cursor object 92 7 mxODBC Cursor Objects 93 There is a length limit for names in SQL at 18 characters An InternalError will be raised if the name is too long or otherwise not useable setcursoroption option value Sets a cursor option to a new value Only a subset of the possible option values defined by ODBC are available since this method could otherwise easily cause mxODBC to segfault it makes changes possible which effect the way mxODBC interfaces to the ODBC driver Only options with numeric values are currently supported Option Comment gt UL AIR QUERY TIMEOUT Sets the query timeout in seconds used for the cursor Queries that take longer raise an exception after the timeout is reached Possible values Any positive integer or SQL QUERI TIMBOUT DEFAULT Note that not all ODBC drivers support this option SOL ATTR ASYNC ENABLE Enable asynchronous execution of commands Possible values
158. istribution or by running the following at the command prompt python c import mx DateTime If you get an import error please visit the eGenix com web site and install the egenix mx base package first e You will need ODBC drivers for all databases you wish to connect to Windows comes with a very complete set of such drivers but if you can t find the driver you are looking for have a look at 14 Hints amp Links to other Resources 2 2 2 Before You Start Upgrading When upgrading from a previous version of mxODBC you can normally install the new version in place of the previous one If you want to be extra careful you can also uninstall the previous version using the standard Windows software setup tool See 2 2 4 Uninstall for details 2 Installation 2 2 3 If you used a different packaging format for installing the previous version please see the relevant installation section of this guide for instructions on how to uninstall that variant License Files In order to use mxODBC you will need license files from eGenix com If you want to test the product before buying it you can request evaluation licenses via the eGenix com web site at http www egenix com When buying licenses from the eGenix com online shop http shop egenix com you will receive the license files immediately after purchase In both cases the license files are sent to the email address you specified during the purchase process or from w
159. it transactional mode Setting the attribute to True or False adjusts the connection s mode accordingly This attribute is a shortcut to using connect Lon setconn ctoption SOL AUTO COMMIT value and can raise the same exceptions e g in case of a closed connection bindmethod Attribute to query and set the input variable binding method used by the connection This can either be BIND USING PYTHONTYPE Of BIND USING SQLTYPE see the Constants section 10 5 for details closed Read only attribute that is true in case the connection is closed Any action on a closed connection will result in a ProgrammingError to be raised This variable can be used to conveniently test for this state converter Read write attribute that sets the converter callback default for all newly created cursors using the connection It is None per default meaning to use the standard conversion mechanism See the Supported Data Types section for details CUPSaOrE ys Read write attribute that sets the default ODBC cursor type for cursors created on this connection Possible values are 6 mxODBC Connection Objects SQL CURSOR FORWARD ONLY The cursor only scrolls forward This is the default setting in case mxODBC finds that the database does not support scrollable cursors SQL CURSOR_ STATIC The result set is made static by creating a static copy of the result set after opening the cursor As a result any changes to the result s
160. k up the ODBC trace file from the location you ve chosen and email it to support egenix com mxODBC Call Level Tracing To simplify debugging the mxODBC package can generate debugging output in several important places The feature is only enabled if the mxODBC package was compiled with debug support and output is only generated if Python is run in debugging mode use the Python interpreter flag d python d 6cripc py The resulting log file is named mxODBC log It will be created in the current working directory messages are always appended to the file so no trace is lost until you explicitly erase the log file If the log file can not be opened the module will use stderr for reporting To obtain a debugging version of mxODBC please contact support egenix com for help 19 History amp Changes 19 History amp Changes 167 For more recent changes please visit the product page on the eGenix com website Changes from 3 2 1 to 3 2 2 Feature Enhancements e Backported the new cursortype attribute from the upcoming mxODBC de The new attribute allows easily adjusting and inspecting the ODBC cursor type to be used for an mxODEC cursor object The reason for this unusual backport and inclusion in a patch level release is that we found a serious performance issue with MS SQL Server when using it with mxODBC 3 2 see below This needed to be addressed immediately Driver Compatibility e MS SQL Server performanc
161. le if your system comes with unixODBC 2 3 0 If you have unixODBC 2 3 0 installed you can safely create a symlink from the libodbc so 1 library to the new name libodbc so 2 to overcome this problem Please see the unixODBC website for instructions Platforms On 64 bit platforms you may run into problems with unixODBC since it uses 32 bit SQL length types for versions prior to 2 2 13 Some ODBC drivers on Unix instead use 64 bit SQL length values and will therefore not return correct results when used with unixODBC The binary version eGenix com ships was compiled against unixODBC 2 3 1 or later and expects 64 bit SQL length types If you need a version for unixODBC 2 2 12 or earlier please either use our older mxODBC 3 0 release or write to support egenix com for help Commercial ODBC drivers for Unix are often compiled using 64 bit SQL length types and 32 bit Unicode types unixODBC uses the same types starting with version 2 3 You may run into problems with ODBC drivers compiled against iODBC While unixODBC follows the ODBC standard of using 32 bit Unicode types ODBC defaults to using the Unix 64 bit standard As a result ODBC drivers compiled against iODBC will not work reliably with Unicode data when used with unixODBC Threading 153 In unixODBC versions 2 3 0 and below the ODBC manager used a little known odbc ini setting called Threading which determined the default thread level protection of the ODBC data sourc
162. ls of the ODBC specification from the user but does provide access to many of the introspection APIs defined in that standard If you dont need introspection for your applications you can easily make use of mxODBC without any further knowledge of the underlying ODBC interface Technical Overview The mxODBC package provides a Python Database API 2 0 compliant interface to databases that are accessible via the ODBC application programming interface API Since ODBC is the de facto standard for connecting to databases this allows connecting Python to most available databases on the market today Accessing the databases can be done through an ODBC manager e g the ODBC manager that comes with Windows ODBC or unixODBC which are free ODBC managers available for Unix or the DataDirect ODBC manager which is a proprietary ODBC manager for Unix The package supports parallel database interfacing meaning that you can access multiple different databases from within one process e g one database through the iODBC manager and another through unixODBC mxODBC is customizable to many different needs via configuration attributes e g you can use the Python datetime module or the eGenix xom mxDateTime package for handling date time value eliminating the problems you often face when handling dates before 1 1 1970 and after 2038 It also supports the Python decimal module long integer interfacing Unicode large binary and text data as well as st
163. lt when the components can no longer be used NO WARRANTY eGenix com is making the Software available to Licensee on an AS IS basis SUBJECT TO ANY STATUTORY WARRANTIES WHICH CAN NOT BE EXCLUDED EGENIX COM MAKES NO REPRESENTATIONS OR WARRANTIES EXPRESS OR IMPLIED BY WAY OF EXAMPLE BUT NOT LIMITATION EGENIX COM MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS LIMITATION OF LIABILITY TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW IN NO EVENT SHALL EGENIX COM BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR 1 ANY INCIDENTAL SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS INCLUDING WITHOUT LIMITATION DAMAGES FOR LOSS OF BUSINESS PROFITS BUSINESS INTERRUPTION LOSS OF BUSINESS INFORMATION OR OTHER PECUNIARY LOSS AS A RESULT OF USING MODIFYING OR DISTRIBUTING THE SOFTWARE OR ANY DERIVATIVE 20 Copyright License 10 11 12 13 185 THEREOF EVEN IF ADVISED OF THE POSSIBILITY THEREOF OR II ANY AMOUNTS IN EXCESS OF THE AGGREGATE AMOUNTS PAID TO EGENIX COM UNDER THIS LICENSE AGREEMENT DURING THE TWELVE 12 MONTH PERIOD PRECEEDING THE DATE THE CAUSE OF ACTION AROSE SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES SO THE ABOVE EXCLUSION OR LIMITATION MAY NOT APPLY TO LICENSEE Termination This License Agr
164. lution for timestamp input columns on a per cursor basis It works in the same ways as the connection timestampresolution instance variable and defaults to the creating connection object s settings for connection timestampresolution warningformat Attribute to set the database warning reporting method used by the mxODBC default error handler It takes the same values as the connection warningformat instance variable and defaults to the creating connection object s settings for connection warningformat 118 8 Data Types supported by mxODBC 3 1 119 Data Types supported by mxODBC mxODBC tries to maintain as much of the available information across the Python ODBC bridge as possible In order to implement this mxODBC converts between the ODBC and the Python world by using native data types in both worlds You should note however that some ODBC drivers return data using different types than the ones accepted for input e g a database might accept a time value convert it internally to a timestamp and then return it in a subsequent SELECT as timestamp value mxODBC cannot know that the value only contains valid time information and no date information and thus converts the output data into an mxDateTime DateTime instance instead of an mx DateTime DateTimeDelta instance which would normally be returned for time values The included mx ODBC Misc test pyc can help to check for this behavior It tests many common column types
165. ly take a look at their ODBC site Note that they now call their ODBC SDK Microsoft Data Access Components SDK MDAC It does not only focus on ODBC but also on OLE DB and ADO Note If you are not happy about the size of the SDK download over 31MB you can also grab the older 3 0 SDK which might still be available from a FTP server Look for odbc3sdk exe using e g FTP Search Microsoft also supports a whole range of desktop ODBC drivers for various databases and file formats These are available under the name ODBC Desktop Database Drivers search the MS web site for the exact URL wx1350 exe and also included in the more up to date Microsoft Data Access Components MDAC archive mdac_typ exel Microsoft ODBC Portal This portal page has a few interesting links into the Microsoft ODBC site If you re looking for the latest SQL Server or Oracle ODBC drivers this is the place to look first ODBC Documentation The ODBC documentation is included in the free MS MDAC SDK which you can download from their ODBC site SQLSummit List of ODBC drivers A collection of available ODBC driver packages This should be the first place to look in case you are searching for OBDC connectivity to your database mxODBC Python ODBC Database Interface 15 Examples Here is a very simple example of how to use mxODBC More elaborate examples of using Python Database API compatible database interfaces can be found in the Database Topic Gu
166. method set to BIND USING SQLTYPE The SQL type is what the database ODBC driver expects from mxODBC The interface then tries to convert the Python input objects to the Python type given in the table before passing it on to the ODBC driver SQL Type Python Type Comments SQL CHAR String or The conversion truncates the string SQL VARCHAR Unicode or at the SQL field length The handling SQL LONGVARCHAR TEXT stringified object of special characters depends on the BLOB or LONG in SQL codepage the database uses Some database drivers managers can t handle binary data in these column types so you better check the database s capabilities with the included mx ODBC Misc test pyc first before using them The handling of Unicode depends on the setting of the stringformat 122 8 Data Types supported by mxODBC 123 SQL Type Python Type Comments attribute In NATIVE UNICODE _ STRINGFORMAT mode Unicode is passed to the ODBC driver as native Unicode Strings are converted to Unicode using the connection s character encoding setting In all other modes Unicode is converted to an 8 bit string before passing it to the ODBC driver using the connection s character encoding setting Strings are passed as is Note that for DateTime input objects seconds rounding is applied just like for SQL TIMESTAMP SQL types For DateTimeDelta input objects seconds are truncated to whole seconds
167. mix e g unixODBC and ODBC you can easily run into Unicode data corruption issues The two ODBC managers use different default data types for Unicode data so a FreeTDS ODBC driver compiled against unixODBC 2 bytes Unicode data type will not return correct Unicode data when used with the ODBC ODBC manager 4 bytes Unicode data type e There are other ODBC drivers available from commercial vendors which implement the full ODBC3 API including a free one from Microsoft for Linux Alternatively you can use our mxODBC Connect product to use the SQL Server Native Client on Windows from all supported Python platforms and without the need for a client side ODBC driver e The FreeTDS driver does not support the MARS feature Only one active result set is allowed per connection This driver also support the MARS feature See Multiple active result sets MARS on a single connection for details 36 4 Accessing Popular Databases Example Configuration for Unix Here is a sample setup for FreeTDS on Linux talking to MS SQL Server 2008 on Windows e Add this section to usr local freetds etc freetds conf the freetds conf configuration file may be in a different location on your machine MS SQL Server 2000 running on server MONET MONET host monet example net port 1433 tds version 8 0 e Add this section to etc odbc ini the odbc ini configuration file may be in a different location on your machine It is also necessa
168. mmediately after purchase In both cases the license files are sent to the email address you specified during the purchase process or from which you wrote the evaluation license request in form of a ZIP license archive attached to the license email usually named licenses zip The license archive licenses zip contains one subdirectory per license you bought The directories are named after the license key for each license A typical license archive will have these contents Z100 8789 U322 0920 2508 6429 meodbe license py 2100 8789 0322 0926 2568 6429 mx0db60 license trt 2100 8089 0312 09268 206068 0529 mx0dbe license pY 2 100 8089 0912 0920 2008 629 mek000e liceno Ext in the above example the license archive contains the files for two product licenses In order to install the license files please unzip the license archive to a temporary directory In order for mxODBC to pick up the correct license files please copy them to a location on your sys path Or PYTHONPATH If you installed Python to e g C Python26 on Windows or usr local bin python on Unix or Mac OS X the typical location for installation of the license files would be C Python26 Lib site packages or usr local lib python2 6 site packages Use the following command to see the sys path that your Python version uses python o import sys print jomnfeys patan Step by step Installation Guide Step 1 Determine whether you are using a UCS2 or UCS4 buil
169. momtsuts a eats 168 Changes rom 2 010 Dil sicienstilivuictingsees oud dees lonn hae 168 Feature Enhancement auna 168 Driver Compatibili adi 168 Changes iron 3 2 10 3 Di a 168 Foal UrES Sa covedeas panvaccasucteay ease toe menctucocueteayosevecsucous 168 Driver Compatibles iia 169 PIO ars 170 mxODBC Python ODBC Database Interface Changes roma AOS h 2a nearness 170 Changes TONS LOTOS Tel eie 171 Chances trom 30 Ao 3 Dai 171 AA a aa 173 Changes TOMI O2 105 0 aran desea adecee 174 Changes romo A aa 174 Changes tromo OOTO 0 ariadna a 175 Changes trom 20 7 16 310 Orenius 175 Changes tro 2 0610 207a enisi aa 178 Changes tron 2 0 5 10 2 06 arseen dai 178 Changes from 0A TO 20 5 nr 179 Changes trom 2 0 3 02 Dil 179 Changes rom 20 210 20 nic 179 Changes from 2 0110 202 n an seeaneeones 179 Chanegestrom 2 000 20 dial 179 20 Copyright amp License oonococooooooooooooococococoooooooos 181 1 Introduction 1 1 Introduction mxODBC has proven to be the most stable and versatile ODBC interface available for Python It has been in active use for years and is actively maintained by eGenix com to meet the requirements of modern database applications which our customers have built on top of mxODEC This manual will give you an in depth overview of mxODBC s capabilities and features It is written as technical manual so background in Python and database programming is needed mxODBC tries to hide many of the complicated detai
170. mxODBC will then default to auto commit mode Rollback will not work in that mode SAP MaxDB SAPDB Available ODBC Drivers MaxDB ODBC driver Homepage http www sdn sap com irj sdn maxdb Tested with MaxDB 7 7 ODBC driver MaxDB ships with ODBC drivers for all supported platforms The ODBC driver is included in the distribution tar archive of the database as SDBODBC TGZ You can use the drivers with both unixODBC and iODBC Note that the MaxDB 7 7 ODBC driver can also connect to a MaxDB 7 6 database server It is usually best to use the latest available version even if your database servers hasn t been upgraded yet mxODBC Python ODBC Database Interface Example Configuration for Unix e Edit your odbcinst ini file and add the MaxDB driver the location of the driver and setup file may be different on your system ODBC Drivers MaxDB Installed MaxDB Driver usr 7local maxdb 1ib Libsdbodbcw so Description MaxDB ODBC Driver e Edit your odbc ini file and add a MaxDB section the location of the driver may be different on your system be sure to use the Unicode variant which ends with w so It is also necessary to point LD LIBRARY PATH to the directory where the driver itself is located maxadb DRIVER usr local maxdb lib libsdbodbcw so ServerDB MYDB ServerNode maxdb example net SQLMode IsolationLevel Trace 0 TraceFileName tmp maxdb log e Using these settings you can then co
171. n ODBC Database Interface 106 Column Name Column Datatype Comment is a procedure that is it does not have a return value SQL PT FUNCTION The returned object is a function that is it has a return value procedurecolumns qualifier None column None owner None procedure None Query the data source for information on parameter details of procedures stored in a data source procedure can be used to limit the results to a set of procedures or a single procedure column allows restricting the results to a single procedure parameter The method can be used to e g determine whether a parameter is an input output or input output parameter The catalog method generates a result set having the following schema the term column used here refers to the procedure s call parameters Column Name Column Datatype Comment PROCEDURE_CAT VARCHAR 128 Always NULL PROCEDURE _ VARCHAR 128 The name of the schema containing SCHEMA PROCEDURE_NAME PROCEDURE _ VARCHAR 128 The name of the table or view or alias or NAME synonym COLUMN_NAME VARCHAR 128 Name of the column of the specified table view alias or synonym COLUMN TYPE SMALLINT not NULL Identifies the type information associated with this column Possible values SQL PARAM_TYPE_UNKNOWN the parameter type is unknown SQL PARAM_INPUT this parameter is an input parameter SQL P
172. n alias for Connect needed for Python DB API 2 0 compliance DraverConnec te DSN String clear auto commit 1 srrorhanaler None This constructor returns a connection object for the given data source which is managed by an ODBC Driver Manager e g the Windows ODBC Manager or iODBC It allows passing more information to the database than the standard Connect constructor errorhandler may be given to set the error handler for the Connection object prior to actually connecting to the database This is useful to mask e g certain warnings which can occur at connection time The errorhandler can be changed after the connection has been established by assigning to the errorhandler attribute of the Connection object The default error handler raises exceptions for all database warnings and errors Please refer to the documentation of your ODBC manager and the database for the exact syntax of the DSN_ string It typically has this formatting DSN datasource name UID userid PWD password case can be important and more entries may be needed to successfully connect to the data source See the following section 6 4 Default Transaction Settings for details on Clear aut commit connection options may be given as list of option value tuples to set pre connect ODBC connection options The option and value arguments must use the same format as the parameters for the setconnectoption method This list can be used to e g enable the M
173. n to be not nullable and YES otherwise columnprivileges qualifier None owner None table None column None Query the database schema for information on column privileges for the given table This is useful to determine the authorizations granted to a table or column column allows restricting the results to a single column of a table Note that the table parameter is mandatory The catalog method generates a result set having the following schema Column Name Column Datatype Comment TABLE CAT VARCHAR 1 28 Always NULL TABLE SCHEMA VARCHAR 1 28 The name of the schema containing TABLE_NAME TABLE NAME VARCHAR 128 not The name of the table or view or alias or NULL synonym COLUMN NAME VARCHAR 128 not Name of the column of the specified table view NULL alias or synonym GRANTOR VARCHAR 128 Authorization ID of the user who granted the privilege GRANTEE VARCHAR 1 28 Authorization ID of the user to whom the privilege is granted PRIVILEGE VARCHAR 128 The table privilege This may be one of the following strings INSERT REFERENCES SELECT UPDATE IS GRANTABLE VARCHAR 3 Indicates whether the grantee is permitted to grant the privilege to other users This can be YES NO or NULL mxODBC Python ODBC Database Interface Toreignkeys primary quali tier None primary Owner None Pllery table Non e foreign quelitier Nene foreign own
174. nal position of the column within the index whose name is given in the INDEX_ NAME column A NULL value is returned for this column if the TYPE column has the value of SQL TABLE_ STAT COLUMN_ NAME VARCHAR 1 28 Name of the column in the index A NULL value is returned for this column if the TYPE column has the value of SQL TABLE_ STAT ASC_OR_DESC CHAR 1 Sort sequence for the column A for ascending D for descending NULL value is returned if the value in the TYPE column is SQL TABLE_ STAT CARDINALITY INTEGER If the TYPE column contains the value SQL TABLE_STAT this column contains the number of rows in the table If the TYPE column value is not SQL TABLE_ STAT this column contains the number of unique values in the index A NULL value is returned if the information cannot be determined PAGES INTEGER If the TYPE column contains the value SQL TABLE_STAT this column contains the number of pages used to store the table If the TYPE column value is not 7 mxODBC Cursor Objects Column Name Column Datatype Comment SQL TABLE_STAT this column contains the number of pages used to store the indexes A NULL value is returned if the information cannot be determined FILTER_ CONDITION VARCHAR 128 If the index is a filtered index this is the filter condition NULL is returned if TYPE is SQL TABLE_STAT or the database does not support filtered ind
175. name as part of the connection string of mx ODBC Windows DriverConnect using the form DSN mydsn If you use the mx ODBC Windows Connect API to connect pass the DSN name as first parameter File Data Sources File DSN File data sources are special in the sense that they store the data source connection information and options in a dedicated file rather than in the registry This can be useful if you want to manage data sources across many servers and keep the data source files on a central file server You create such DSN files using the ODBC manager In order to connect to such a data source you have to use the mx ODBC Windows DriverConnect API and provide a FILEDSN c myfile dsn entry instead of the usual DSN mydsn as part for the connection string 3 Access Databases using mxODBC See the ODEC File Data Source documentation for more details 3 2 6 DSN less Connections 23 If you don t want to bother setting up a data source in the ODBC manager you can also use a DSN less connection setup Pros and Cons of using DSN less Connections These setups include all required driver and connection information in the connection string itself All connection information is thus under the control of the application without any system ODBC manager being aware of the connection setup This has both up and downsides The most important downside is that changes to the server system can no longer be administered through the
176. nd values which sometimes cannot be represented with full accuracy SOL LONGVARCHAR SOL VARBLNARBY SOL LONGVARBINARY char None Any nullable column The Python None singleton is converted to the special SQL NULL value Any other type SOL VARCHAR Conversion is done by calling str variable and then passing the resulting string value to the ODBC driver manager Same notes as for strings apply See the ODBC Documentation and your ODBC driver s documentation for more information on how these C data types are mapped to SQL column types 8 Data Types supported by mxODBC 8 5 Output Conversions The following data types are used per default for output variable SQL Type Python Type Comments SOL CHAR String The handling of special characters SQL VARCHAR depends on the codepage the database SQL LONGVARCHAR Eee TEXT BLOB or LONG in SQL In NATIVE UNICODE STRINGPORMAT and UNICODE STRINGFORMAT mode the string data is converted to a Python Unicode object based on the connection s encoding setting SOL WCHAR String or Whether a Python string or Unicode SQL WVARCHAR Unicode object is returned depends on the setting SQL WLONGVARCHAR of the stringformat attribute of the TEXT BLOB or LONG cursor fetching the data in SQL In EIGHTBIT STRINGFORMAT mode the Unicode data is converted to a Python string object based on the connection s encoding setting SOL
177. ndows XP Vista and 7 to successfully complete the installation Step 2 The installer will then ask you to accept the license choose the Python version and then to start the install process If the listbox showing the installed Python versions is empty it is likely that you have chosen the wrong Windows installer for your Python version Please go back to the eGenix com web site and download the correct version for the installed Python version Step 3 In case you are upgrading to a new mxODBC version the installer will ask you whether you want to overwrite existing files Answer yes to this question It is safe to allow the installer overwrite files The installer will then install all the needed files Note that it does not setup any links on the desktop or in the start menu Step 4 Test the installation by trying to import mxODBC S python Python 2 6 4 r264 75706 Jan 4 2010 20 40 33 GCO 4 2 1 SUSE Linux on Linux Type help copyright credits or license for more information gt gt gt import mx ODBC Manager APF If you don t get any ImportError you have successfully installed mxODBC Uninstall The Windows installer will automatically register the installed software with the standard Windows software setup tool To uninstall the distribution run the Windows Software Setup tool and select the Python x x eGenix mxODBC x x entry for deinstallation This will uninstall all files that can s
178. ng processing etc IntegrityError Exception raised when the relational integrity of the database is affected e g a foreign key check fails InternalError Exception raised when the database encounters an internal error e g the cursor is not valid anymore the transaction is out of sync etc ProgrammingError Exception raised for programming errors e g table not found or already exists syntax error in the SQL statement wrong number of parameters specified performing operations on closed connections etc NotSupportedError Exception raised in case a method or database API was used which is not supported by the database e g requesting a rollback on a connection that does not support transaction or has transactions turned off This is the exception inheritance layout StandardError Warning Error IntertaceError Databasebrror DataBrror 138 10 mxODBC Exceptions and Error Handling _ OperationalError _ INTEGTILYUCTOL _ AiMbernalBetor _ ProgrammlingError __ NotsupportedError 10 2 SQL Error Mappings 10 3 139 If you are interested in the exact mapping of SQL error codes to exception classes have a look at the errorclass dictionary which is defined at subpackage scope 8 mx ODBC Windows errorclass errorclass The errorclass dictionary maps SQLSTATE strings to error classes and is used by mxODBC to determine which Python exception class to use for reporting the database error wi
179. ng the ANSI API on the ODBC driver ANSI parameters are passed through as is to the ODBC driver For ODBC drivers that do not support the ODBC Unicode interface connecting using an ANSI connection string and subsequently using ANSI parameters for all execution and catalog methods may result in better performance or improved compatibility Example Use the ANSI ODBC API of the driver by using an 8 bit connection mxODBC Python ODBC Database Interface string db mx ODBC Windows DriverConnect DSN mydb UID uid PWD pwd 6 7 Connection Object Methods 74 close Close the connection now rather than automatically at garbage collection time The connection will be unusable from this point on an Error or subclass exception will be raised if any operation is attempted with the connection The same applies to all cursor objects trying to use the connection commit Commit any pending changes and implicitly start a new transaction For connections which do not provide transaction support or operate in auto commit mode this method does nothing Cursor mame N ne cursor eprtiene 1 Constructs a new Cursor Object with the given name using the connection and initializes any provided cursor options If no name is given the ODBC driver or database backend will determine a unique name on its own You can query this name with cursor getcursorname see the Cursor Object section 7 The cursor options m
180. nly has to pass the SQL statement and the list of parameters to the database rather than build and send hundreds of statements across the wire to the database Security is better since the ODBC driver or database backend based building of the final SQL statement prevents the popular SQL injection attack on applications With this attack method an attacker tries to trick an application into inserting a specially prepared SQL statement string sequence into an application defined SQL statement template Say the application uses SELECT FROM MyTable WHERE A s An attacker could then try to send the parameter value 1 DROP TABLE MyTable to the application which would then result in the SQL statement SELECT FROM MyTable WHERE A 1 DROP TABLE MyTable to be executed in case the application doesn t very carefully check parse and quote the parameter value for A Parameter Binding Styles mxODBC uses the ODBC parameter style as binding parameter marker style per default This style is called qmark because it uses positional question mark markers to locate the parameters e g SELECT FROM MyTable WHERE A Starting with mxODBC 3 2 mxODBC also provides a way to adjust the parameter style on a per connection and per cursor basis In addition of the qmark parameter style mxODBC also supports the Oracle style named parameter style The default style is still the qmark style but you can set the connection paramstyle to n
181. nnect to MaxDB using a simple connection string such as DSN maxdb ULD username PWD password 4 8 2 General Database Notes 52 Warnings when deleting update more than one row at a time MaxDB issues a mx ODBC Error Warning 01001 0 rT SAP AG LIBSDBOD SO Cursor operation conflict 8416 warning whenever you try to delete or update more than one row with a single database statement You can easily work around this by setting the cursor warningformat to IGNORE WARNINGFORMAT restoring it afterwards to the default ERROR _WARNINGFORMAT if you just want to ignore this particular warning case 4 Accessing Popular Databases 4 9 Teradata 4 9 1 Available ODBC Drivers 53 Teradata ODBC Driver Homepage http www teradata com downloadcenter Tested with Teradata 13 1 ODBC driver and DataDirect 6 0 ODBC manager The Teradata ODBC driver was developed by DataDirect and requires the DataDirect ODBC manager so you will need to use the mx ODBC DataDirect package on Unix to work with the driver Driver Notes e The mx ODBC DataDirect package is currently only available for Linux 32 bit and 64 bit systems If you need the package on other platforms please write to support egenix com for assistance e The DataDirect ODBC driver manager is included in the same directory as the Teradata ODBC driver itself If you setup LD LIBRARY PATH to the directory where the driver is located mxODBC will automatically use the right Data
182. nnnnncnnnnnnccncnncninnnannnss 54 DataDirect ODBC Driver for Teradata coooooooccccnnccnnnnonoccnnnnnnnnnnnnnos 54 NCTE ZZ dto 55 Avallable ODBC Drivers 1 as 55 Contents 4 11 4 11 1 4 11 2 4 11 3 4 11 4 4 11 5 5 1 Skal 5 2 5 2 1 5 3 5 3 1 D2 5 4 5 4 1 5 4 2 5 4 3 Do 5 5 1 D022 Netezza ODBC DIV seed ae es ee 55 Recommended SetU ira scscnceicecgnsaatenanetisernanaastanatioacannneeseaeiivads 55 Netezza and Unicode ceccecoscsecocceccessccecceccsseccecceccseaces 55 Example Configuration for UNiX ooooocccncccononoooonnnncnnnnonanaccnancnnnnns 55 DataDirect ODBC Driver for NeteZZa cscescesceccscscescecescesces 56 Other Databases s cccsssccecosscascececaccececnccececscnccsceencs 56 Easyooit ODBC Driver Packages iran 57 Oe a 57 aba WC A NR 57 OE at 118 G eee ee Ee Pre mre PE nO er er OE 57 Alternative solution mxODBC Connect csceccsceccsceccsceccscscesceces 57 mxODBC Overview cccccccccscscscscccscscscscsccsssseees DO mxODBC and the Python Database API Specification 58 A A saan ented tae aes eet see eee 58 mxODBC and the ODBC SpecificatiOn oooooomommmmmmm 59 Full access to most ODBC featureS cccooooccnccnnoncnnnnnnnanannncnnnnarannccnnnnss 59 Supported ODBC Versi0NS ococcccccnnncncnnnnnnnnnnnnnnnnnnnnnnnnnnnos 60 ODBO Manage sis 60 Changes between ODBC 2 x 003 Mo sissies vsssisessnnvosadvecsiavesndwosed vecistans 6
183. ntal subpackage mx ODBC FreeTDS which allows connecting to MS SQL Server from Unix This is still far from even being called alpha due to the current lack of implementation support of many important ODBC APIs in the FreeTDS ODBC driver Changed Exception classes of subpackages are now identical to the base classes defined in mx ODBC Error They are no longer defined on a per subpackage basis This should make writing cross database applications a little easier Updated the Solid subpackage from Solid 2 2 to Solid 3 52 This update involved several small tweaks to make the Solid ODBC driver happy Fixed a bug in the code for fetching Unicode BLOBs which caused NUL Characters to be inserted into the resulting string Made the BLOB fetching code a little smarter to work around bugs in ODBC drivers which don t 0 terminate character data hunks this resulted in missing bytes at 1024 byte boundaries Strings in Python binding mode will now bind as SQL_VARBINARY SQL_LONGVARBINARY if necessary Wrap them in buffer objects to always force binding them as VARBINARY data fields This fixes compatibility problems with some ODBC drivers which don t support SQL type binding Integrated mxLicenseManager In order for mxODBC to work a license py file must be present in the mx ODBC directory of the package Added work around for binding large data chunks in Python binding mode This solves a problem with EasySoft s Oracle ODBC driver Unfortunately
184. o pass in extra configuration information such as names of log files etc 13 mx ODBC Subpackages 13 3 2 Supported Datatypes The subpackage defaults to SQL type binding mode see the Datatypes section for details but reverts to Python type binding in case the connection does not support the ODBC SQLDescribeParam API MS Access is one candidate for which this API is not useable 13 3 3 File Data Sources 13 4 13 4 1 151 If you want to connect to a file data source without having to configure it using the ODBC manager you can do so by using the FILEDSN parameter instead of the DSN parameter DriverConnect FILEDSN test dsn UID test PWD test This is sometimes useful when you want to dynamically setup a data source e g a MS Access database For more information about the FILEDSN keyword and the other Windows ODBC manager features see the Microsoft SQLDriverConnect documentation Also note that ODBC drivers working on single files e g the MS Excel file driver usually do not support transactions mxODBC will not clear auto commit for these drivers it may sometimes still be necessary to set the clear auto commit flag in the connect constructors to 0 mx ODBC IODEC ODBC Driver Manager Tested with ODBC 3 52 7 ODBC is an Open Source ODBC manager for Unix maintained by OpenLink It compiles against mxODBC without problems and is the preferred way of talking to an ODBC data source from Unix using
185. o to Michael Bayer for working with us to make this happen Driver Compatibility e Added support for returning SQL Server TIME columns as time value instead of as string e Added a work around to prevent truncation warnings with the SQL Server ODBC driver when using executemany direct 1 Changes from 3 1 2 to 3 2 0 Features e mxODBC connection objects can now be used as context managers to implicitly commit rollback transactions e mxODBC cursor objects can now be used as context managers to implicitly close the cursor when leaving the block regardless of whether an exception was raised or not e mxODBC added support for adjustable paramstyles Both qmark default and named styles are supported and can be set on connections and cursors The named style allows easier porting of e g Oracle native interface code to mxODBC e mxODBC now supports a writable connection autocommit attribute to easily turn on off the connection s auto commit mode e mxODBC added support for adjustable TIMESTAMP precision via the new connection cursor timestampresolution attribute e mxODBC will round to nearest nanosecond fraction instead of truncating the value This will result in fewer conversion errors due to floating point second values e mxODBC s connect APIs Connect and DriverConnect support setting connection options prior to connecting to the database via a new connection_options parameter This allows enabling e g t
186. ocated teradata Driver opt teradata client 13 10 odbc 64 lib tdata so Description Teradata ODBC DBCName 192 168 0 250 DefaultDatabase mydb RuniInQuietMode Yes DSNTraceEnable No DSNTraceFilePath tmp teradata txt DSNTraceOverwrite Yes CharacterSet UTF16 DateTimeFormat AAA Disable preparing statements DisablePREPARE Yes Max response packet size in bytes MaxRespSize 10000000 Disable parsing of SQL statements by the driver do not set to res if using callproc in the application NoScan No SessionMode can be Teradata or ANSI SessionMode Cursor open checks StCheckLevel 0 Enable TOE NODELAY 7 TCPNoDelay Yes Port to use on the database servers TDMSTPortNumber Use BLOB and CLOB UseNativeLOBSupport Yes Using these settings you can then connect to Netezza using a simple connection string such as DSN teradata UID username PWD password DataDirect ODBC Driver for Teradata Homepage http www datadirect com 4 Accessing Popular Databases 4 10 Netezza 4 10 1 Available ODBC Drivers 55 Netezza ODBC Driver Homepage http www netezza com Tested with Netezza 4 6 6 ODBC driver The Netezza ODBC driver is available to Netezza customers or partners eGenix com partnered up with Netezza to make sure that mxODBC performs well with Netezza s driver Recommended Setup The recommended setup is to use the mx ODBC unixODBC subpackage
187. ology tech oci instantclient index html Tested with Oracle Instant Client ODBC driver 11 2 The Oracle Instant Client ships with an ODBC driver part of the ODBC Supplement for most supported platforms mxODBC works well when using the Oracle Instant Client 11 2 with the unixODBC ODBC manager package mx ODBC unixODBC on Unix or the mx ODBC Windows package on Windows Driver Notes e eGenix com has had reports about memory leaks occurring with the Oracle driver when used in long running applications mxODBC itself does not have any known memory leaks and there are no problems with other available drivers for Oracle e Oracle regards empty strings as NULL values as a result inserting an empty string into a VARCHAR column can result in the Oracle driver returning NULL for that column when fetching data e The Oracle driver returns numeric values as floats even integers so unless you use a converter function you will get floats when querying integer columns e The automatic reuse of prepared SQL commands does not work with the Oracle driver so the optimization for the cursor execute method does not work with the Oracle driver 4 Accessing Popular Databases 41 cursor executedirect as well as the other execute methods used with the direct 1 option don t work when used with parameters It results in function sequence errors This is likely a bug in the Oracle driver we have tested so may work in later versions The Oracl
188. olumn The catalog method generates a result set having the following schema mxODBC Python ODBC Database Interface 110 Column Name Column Datatype Comment SCOPE SMALLINT The duration for which the name in COLUMN_NAME is guaranteed to point to the same row Contains one of the following values SQL SCOPE CURROW SQL SCOPE_TRANSACTION SQL SCOPE_SESSION COLUMN NAME VARCHAR 1 28 not NULL Name of the column that is or part of the table s primary key DATA TYPE SMALLINT not NULL SQL data type of column identified by COLUMN_NAME TYPE_NAME VARCHAR 128 not NULL Character string representing the name of the data type corresponding to DATA_TYPE COLUMN SIZE INTEGER If the DATA_TYPE column value denotes a character or binary string then this column contains the maximum length in characters for the column For date time timestamp data types this is the total number of characters required to display the value when converted to character For numeric data types this is either the total number of digits or the total number of bits allowed in the column depending on the value in the NUM_PREC_RADIX column in the result set BUFFER_LENGTH INTEGER The maximum number of bytes for the associated C buffer to store data from this column if SQL C_DEFAULT were specified on the SOLBindCol SOLGetData and SOLBindParameter ODEC calls used internally by mxODB
189. on application you can connect to your databases with a single Python call ODBC Application Stack The typical ODBC application setup looks like this Network or Local Connection The upper blue part in the diagram executes within the process of the Python application The green part usually runs in a separate process and possibly also on a different machine Architecture 32 bit vs 64 bit As a result of this process setup outlined in the previous section it is important that you choose the right ODBC driver type for your application 3 Access Databases using mxODBC Dow 3 2 1 19 e If you are running a 64 bit Python application you will also have to have a 64 bit ODBC manager and ODBC driver installed e If you are running a 32 bit Python application you need an 32 bit ODBC manager and ODBC driver Note that the ODBC manager may be capable of translating 32 bit or 64 bit function calls to whatever the ODBC driver supports this is called thunking Please check the documentation of your ODBC manager for details Accessing Databases from Windows Most database ship with ODBC drivers for Windows so setting up database access for Python applications on Windows is fairly straight forward Once you ve installed the ODBC drivers on the machine you are running your Python application on you will need to setup an ODBC Data Source This can be done using the ODBC Manager on Windows To avoid problems with system p
190. on occurs SOL REAL SOL FLOAT Float or any other object which can be Conversion from the Python float a C double to the SQL type is left to the ODBC driver manager so expect 124 8 Data Types supported by mxODBC 125 SQL Type Python Type Comments SOL DOUBLE converted to a Python float the usual truncations SOL DATE DateTime instance or While you should use DateTime datetime date instance or instances the module also accepts a tuple Python datetime date instances year month day or ticks Python numbers indicating the String or number of seconds since the Unix a ticks value as Python Epoch these are converted to local number time and then stored in the database and tuples year month day on input SOL TIME DateTimeDelta instance or While you should use DateTimeDelta datetime time instance or a tuple hour minute second or String or a tocks value as Python number instances the module also accepts Python datetime time instances tocks Python numbers indicating the number of seconds since 0 00 00 00 and tuples hour minute second on input Seconds are rounded to the nearest nanosecond in order to avoid issues with float second values which sometimes cannot be represented with full accuracy SQL TIMESTAMP DateTime instance or datetime datetime instance or datetime date instance or atuple year month day hour minute second or String or a
191. on the used query options the result set will contain information for only one table the whole database or just a single column The catalog method generates a result set having the following schema Column Name Column Datatype Comment TABLE_CAT VARCHAR 128 Always NULL 7 mxODBC Cursor Objects Column Name Column Datatype Comment TABLE_SCHEMA VARCHAR 128 The name of the schema containing TABLE_NAME TABLE_NAME VARCHAR 128 not NULL The name of the table or view or alias or synonym COLUMN_NAME VARCHAR 128 not NULL Name of the column of the specified table view alias or synonym DATA TYPE SMALLINT not NULL SQL data type of column identified by COLUMN_NAME TYPE_NAME VARCHAR 128 not NULL Character string representing the name of the data type corresponding to DATA_TYPE COLUMN SIZE INTEGER If the DATA_TYPE column value denotes a character or binary string then this column contains the maximum length in characters for the column For date time timestamp data types this is the total number of characters required to display the value when converted to character For numeric data types this is either the total number of digits or the total number of bits allowed in the column depending on the value in the NUM_PREC_RADIX column in the result set BUFFER_LENGTH INTEGER The maximum number of bytes for the associat
192. onnection methods calls prior to executing the call except for the info and connection option methods calls to avoid excessive memory usage and can also be cleared by executing del connection messages All error and warning messages generated by the ODBC driver are placed into this list so checking the list allows you to verify correct operation of the method calls paramstyle Sets the default parameter binding style for cursors created on this connection i e all cursors created on the connection will use connection paramstyle as their default cursor paramstyle value The attribute can be set or queried and takes the following string values following the paramstyle module global as defined in the DB API qmark default This is the default ODBC parameter binding style and also used as native database binding style by MS SQL Server and IBM DB2 Parameters in SQL statements used on cursor execute methods are marked with the question mark letter and the variables are bound to these parameter locations using a positional mapping Parameter values for a SQL statement must be specified as sequence normally a list or a tuple Example SELECT FROM MyTable WHERE A AND B used with a parameter tuple 1 2 would result in the database executing the query SELECT FROM MyTable WHERE A 1 AND B 2 named The named parameter binding style is used by the native database interfaces of e g Oracle 79 mxODBC
193. ons and the SQL Server Native Client 37 Static vs forward Only Cursors cccccccnnnonocccnnnncnnnnnnnncnnnncncnnnnnnnccnnnos 37 Multiple Cursors on CONNECTIONS cccccoonoccccncncnnnonanoncnnnnnnnnnnnanancnnnos 38 International Character Data coconnnonccccnnnnnnoooconnnnnnnnnnnnncnnnncncnnnnnnnss 38 ACCESS VIOLA ION S ein dicta 38 Distributed Transaction Managers ooooocccccnnnooccnnnnnnnnnnnnoccnnncncnnnnannss 39 Other Common Problems and Solutions ccccnonocccnncncnnnnnancnnnnos 39 MS Access Database do 39 Contents 4 2 1 4 3 4 3 1 4 3 2 4 4 4 4 1 4 4 2 4 5 4 5 1 AVANA DIS OD BE Drivers Di 39 WS ACCESS ODBC DIVE aida 39 MDBTOOIS ODBC DAVE acia ai ias 40 A A 40 Available ODBC Driver S a iy eines 40 Oracle Instant Client ODBC driver ccooocccnnnnioccnnnnnccnnnnnccnnnnnoccnnonoss 40 DRIVER INGOTS A A 40 Example Configuration for UNiX oooococccccconononoccnnnnnnnnananocccancnnnnns 41 EasySoft ODBC Driver for Oracle oooooooconcccnnononocconncccnnonanacacanancnnnn 42 OpenLink ODBC Driver for Oracle ccoccononcccnnccnnnnnonoccnnnnnnnnnnannss 42 DataDirect ODBC Driver for Oracle cccccseecccceesescceeseccceeeeecees 42 Actual Technologies Mac OS X ODBC Driver for Oracle 42 General NOTES eair odds 42 Oracle tnSnames Ora file ooooooccnnnnnocnnnonoccnnnnanonnnnnocnnnnnaccnnonoss 42 BM DB2 canadian 43 Ava lape ODBC Driver S danen ae a
194. ontaining TABLE_NAME TABLE_NAME VARCHAR 128 not The name of the table or view or alias or NULL synonym NON_UNIQUE SMALLINT Indicates whether the index prohibits duplicate values Returns SQL TRUE if the index allows duplicate values SQL FALSE if the index values must be unique NULL is returned if the TYPE column indicates that this row is SQL TABLE_STAT statistics information on the table itself INDEX_QUALIFIER VARCHAR 128 The string that would be used to qualify the index name in the DROP INDEX statement Appending a period plus the INDEX_NAME 111 mxODBC Python ODBC Database Interface 112 Column Name Column Datatype Comment results in a full specification of the index INDEX_NAME VARCHAR 128 The name of the index If the TYPE column has the value SQL TABLE_STAT this column has the value NULL TYPE SMALLINT not NULL Indicates the type of information contained in this row of the result set SQL TABLE_STAT Indicates this row contains statistics information on the table itself SQL INDEX_CLUSTERED Indicates this row contains information on an index and the index type is a clustered index SQL INDEX_HASHED Indicates this row contains information on an index and the index type is a hashed index SQL INDEX_ OTHER Indicates this row contains information on an index and the index type is other than clustered or hashed ORDINAL POSITION SMALLINT Ordi
195. option When connecting to a user DSN you have to specify the DSN name as part of the connection string of mx ODBC Manager DriverConnect using the form DSN mydsn If you use the mx ODBC Manager Connect API to connect pass the DSN name as first parameter System Data Sources System DSN System data sources are available to all users of the system This is the recommended setup if you run services that need to access the data sources from more than just one account Systems DSNs can be defined via the ODBC manager GUI administration tools or by editing the system ODBC configuration file etc odbc ini See 3 3 5 ODBC Configuration Files for details When connecting to a system DSN you have to specify the DSN name as part of the connection string of mx ODBC Windows DriverConnect using the form DSN mydsn If you use the mx ODBC Windows Connect API to connect pass the DSN name as first parameter mxODBC Python ODBC Database Interface 3 3 7 30 File Data Sources File DSN File data sources are special in the sense that they store the data source connection information and options in a dedicated file rather than in the registry This can be useful if you want to manage data sources across many servers and keep the data source files on a central file server You create such DSN files using the ODBC manager if supported or by using a text editor A DSN file uses the same syntax as the ODBC connection strings
196. or or subclass exception is raised if the previous call to execute did not produce any result set or no call was issued yet prepare sqlcmd Prepare a database operation query or command statement for later execution and set cursor command To execute a prepared statement pass cursor command to one of the execute methods sqlcmd may be a Unicode object in case the ODBC driver and or database support this Return values are not defined This method is may not be available in all mxODBC subpackages Even if it is available the used ODBC driver or database may not support preparing database operations for later reuse scroll value mode relative Scroll the cursor in the result set according to mode If mode is relative default value is taken as offset to the current position in the result set if set to absolute value gives the absolute position An IndexError is raised in case the scroll operation leaves the result set In this case the cursor position is not changed This method will use native scrollable cursors if the data source provides these or revert to an emulation for forward only scrollable cursors Please check whether the data source supports this method using the included mx ODBC Misc test pyc script Warning Some ODBC drivers have trouble scrolling in result sets which use BLOBs or other data types for which the data size cannot be determined at prepare time mxODBC currently ra
197. ored procedures prepared statements database introspection and in flight customization of connections and cursors mxODBC Python ODBC Database Interface 1 2 Features e Python Database API 2 0 Compliance the mxODBC API is fully Python DB API_ 2 0 compatible and implements a large number of powerful extensions e Support for all recent ODBC Version mxODBC works with ODBC drivers implementing the ODBC version specifications 2 0 3 52 e Uses ODBC 3 APIs provided the ODBC driver is capable of using ODBC 3 APIs mxODBC will use them for added efficiency e 32 bit and 64 bit ODBC mxODBC supports both 32 bit and 64 bit versions of the ODBC standard including special 64 bit builds on Unix e Supports all major ODBC driver managers mxODBC can work with the MS ODBC Driver Manager on Windows unixODBC iODBC and the DataDirect ODBC Driver Manager on Unix and the Mac OS X ODBC Driver Manager on Mac OS X If needed multiple ODBC managers can be used at the same time giving you full flexibility e Stable robust and reliable the mxODBC API has been in active production use since 1997 e ODBC Catalog amp Introspection Functions mxODBC Client API provides methods e g to list tables find column specifications query index relationships etc e Dynamic ODBC Configuration adjust ODBC connection parameters dynamically e g set timeouts read only access auto commit etc e Full Unicode Support use Unicode for managing text d
198. osoft com en us library ms713558 aspx for details on what kind of information is available Many drivers extend this list with additional database specific information Renamed mxODBC Distribution to mxODBC for Python mxODBC now uses PyObject_ MALLOC for memory allocation which should make memory allocation a little faster in a few places Improved the documentation of the catalog methods and included hints for their use cursor execute will no longer treat lists passed in as parameters as emulation for cursor executemany This was a Python DB API 1 0 related feature which was kept for backwards compatibility but has recently caused some confusion among new users If you want to run multiple parameter sets against a single SQL command e g for inserts please use cursor executemany Added a new section on the ODBC configuration files and environment variables to the documentation mxODBC will now be more careful when trying to determine the row position of the first row in the result set This enhances compatibility with the SQL Server 2000 drivers and possibly others as well mx ODBC Manager will now use the mx ODBC DataDirect package if no other ODBC managers are found Fixed a bug that prevented prepare from accepting Unicode strings Fixed problem with passing Unicode arguments to catalog methods mx ODBC Misc test now provides an option ignore warnings Fixed test script to not report bogus memory leaks The
199. ound with the drivers We have also included the resp version information of the drivers we have tested successfully with mxODBC MS SQL Server Available ODBC Drivers MS SQL Server Native Client for SQL Server 2005 2008 and later Homepage http msdn microsoft com en us sq server connectivity aspx Tested with MS SQL Server Native Client for 2005 2008 2008R2 and 2012 SQL Server Native Client is the new native client and ODBC driver for SQL Server 2005 2008 and later on Windows Versions for 32 bit and 64 bit Windows are available Finding the latest version of the SQL Server Native Client Microsoft always ships the SQL Server Native Client ODBC driver together with the SQL Server database packages but also makes it available as separate download in the feature packs for each new SQL Server version Since the client can typically also be used with older SQL Server installations it s worth trying the latest available version in case of problems or to benefit from new features As of this writing the latest version is SQL Server Native Client 11 Here s a list of feature packs that include the SQL Server Native Client You have to look for an installation file called sqincli msi on the pages e Microsoft SQL Server 2012 Feature Pack Supports SQL Server 2005 2008 2008R2 2012 This version no longer supports SQL Server 2000 e Microsoft SOL Server 2008 R2 SP1 Feature Pack 4 Accessing Popular Databases 33 Sup
200. ows application and is called py2exe Note Freezing mxODBC together with an application and redistributing the resulting executables requires that you have obtained developer licenses from eGenix com permitting you to redistribute mxODBC along with a product Please see the License section for more information When freezing mxODBC you may experience problems with py2exe related to py2exe not finding the DLLs needed by mxODBC In this case you have to help py2exe to find the correct subpackage for Windows ie mx ODBC Windows and mx DateTime This can be done by adding i mx ODBC Windows mx DateTime to the py2exe command line python py2exe i mx ODBC Windows mx DateTime yourapp py After doing so py2exe should have no problem finding the files mxODBC pyd and mxDateTime pyd needed by mx ODBC Windows and mx DateTime mxODEC also uses the md5 or hashlib module depending on the Python version and the license module mxodbc license internally You will have to add them to the above list if you run into license verification problems when running the py2exe compiled application More Sources of Information There are several resources available online that should help you getting started with ODBC Here is a small list of links useful for further reading 14 Hints Links to other Resources 159 Microsoft MDAC Site Microsoft is constantly developing new forms of database access For a close up on what they have come up recent
201. p downloads egenix com python index ucs4 egenix mxodbc If you manually downloaded the egg archive from the eGenix com website to a temporary directory pass the file name directly to easy install to start the installation easy install path to egg file egenix mxodbc 3 1 0 py2 6 win32 egg replace the file name with the one of the file you downloaded After installation the egg file can be removed from the temporary directory without causing harm For more information on how to use easy install please see the easy install documentation Step 3 Now that you have installed the product code you need to install the proper licenses in order for the mxODBC to startup correctly Go to the temporary directory where you unzipped the license archive and change to the license subdirectory which contains the license for the installation you are currently working on Copy the two files mxodbc_license py and mxodbc license txt from the license subdirectory to the Python site packages directory Step 4 Test the installation by trying to import mxODBC S python Python 2 6 4 r264 75 06 Jan 4 2010 20 40 33 GCC 4 2 1 SUSE Linux on linux24 Type help copyright credits or license for more information gt gt gt import mx ODBC Manager Pee mxODBC Python ODBC Database Interface If you don t get any ImportError you have successfully installed mxODBC 2 3 4 Uninstall 2 4 2 4 1 14 Since set
202. ports SQL Server 2000 2005 2008 2008R2 e Microsoft SQL Server 2008 Service Pack 2 Feature Pack Supports SQL Server 2000 2005 2008 e Microsoft SQL Server 2005 Feature Pack Downloads Supports SQL Server 2000 and 2005 Optimizing SQL Server Native Client Performance When installing the SQL Server Native Client please make sure that you choose the most efficient database access method If the ODBC driver resides on the same server as the database shared memory is the most efficient protocol available For most other purposes TCP IP is the best option See http msdn microsoft com en us library ms187892 aspx for details Configuring the SQL Server Native Client Network Protocol When configuring an ODBC data source using the SQL Server Native Client you can choose the protocol by providing a server address with protocol prefix tcp db example com 1434 connect to the server db example com using TCP IP over port 1434 the default SQL Server post is 1433 lpc LOCALHOST SQLEXPRESS connect to the instance SQLEXPRESS running on the local host via shared memory np EXAMPLE pipe MSSQLS SQLEXPRESS sql query connect to the instance SQLEXPRESS running on the computer EXAMPLE via named pipe See http msdn microsoft com en us library ms188635 aspx for details on the various formats and how to configure them Multiple active result sets MARS on a single connection The SQL Server Native Client per default does not support
203. ports unixODBC 2 3 1 and later on 64 bit platforms Previous versions are no longer supported Added much improved documentation on how to connect to various popular databases including tips amp tricks for each database driver mxODEC can now be licensed to single database backends mxODBC Standard Edition Licenses reducing licensing costs mxODBC Python ODBC Database Interface 172 We have simplified the licensing terms for multi core processors and virtual machines In most cases this results in greatly reduced licensing costs mxODBC now clearly separates ODBC 2 x and ODBC 3 x support for date time types This improves compatibility with a few ODBC drivers notably the one for Netezza mxODBC now always uses ODBC 3 x APIs where available instead of ODBC2 APIs mxODBC now also accepts Python 2 7 memoryview object where buffer objects were already supported This is useful when writing code in preparation for the transition to Python 3 x mxODBC now uses the read data buffer interface for buffer objects rather than the character data interface in order to enhance support for binary buffer data objects Added a work around for unixODBC issuing warnings instead of errors when not finding ODBC driver shared libraries Added a direct parameter to execute Turned execute executemany and executedirect into keyword parameter methods Setting bindmethod BIND_USING PYTHONTYPE will now have mxODBC ignore the
204. pport the context manager API so the above could be simplified even more to WEN Connection with connection cursor ds cursor cursor execute INSERT INTO table VALUES 1 2 a other tasks su Unicode ANSI Connections Starting with mxODBC 3 1 it is possible to tell the ODBC driver manager whether to use the Unicode ODBC interface of a supporting ODBC driver or the ANSI 8 bit string ODBC interface at connection time Unicode ODBC Interface If the ODBC driver supports the ODBC Unicode interface and you select the Unicode interface by using a Unicode string as connection parameter the ODBC manager will subsequently convert all ANSI parameters to Unicode and then call the Unicode APIs of the ODBC driver Unicode parameters are passed through as is to the ODBC driver For ODBC drivers that natively support the ODBC Unicode interface connecting using a Unicode connection string and subsequently using Unicode parameters for all execution and catalog methods may result in better performance or improved compatibility Example Use the Unicode ODBC API of the driver by using a Unicode connection string db mx ODBC Windows DriverConnect u DSN mydb UID uid PWD pwd ANSI ODBC Interface If the ODBC driver does not support the ODBC Unicode interface or you connect using an ANSI 8 bit string the ODBC driver manager will subsequently convert all Unicode parameters to the connection s ANSI code page before calli
205. r Warning InterfaceError DatabaseError DataError OperationalError IntegrityError InternalError ProgrammingError NotSupportedError Exception objects used by the mxODBC subpackages See section 10 mxODBC Exceptions and Error Handling for details 13 mx ODBC Subpackages 13 mx ODBC Subpackages This section includes specific notes for preconfigured subpackages and setups 13 1 Subpackage Notes The following sections provide hints that apply to all mx ODBC sub packages Please read carefully 13 1 1 Windows Platform Notes You should always use the mx ODBC Windows subpackage and access the databases through the MS ODBC Driver Manager The other packages provide Unix based interfaces to the databases 13 1 2 Unix Platform Notes Even though there are many subpackages for specific databases which then sometimes provide more functionality for that particular database we would like to encourage the use of ODBC managers such as the ODBC unixODBC or DataDirect ODBC managers since these provide the best flexibility in terms of database setup and configuration Using ODBC managers also enables you to easily switch from local databases to cross network databases by adding additional tiers in between The binary distributions of mxODBC for Unix platforms usually only contain the mx ODBC unixODBC and mx ODBC iODBC subpackages For some platforms the mx ODBC DataDirect subpackage is also included e g Linux x86 and x86_ 64
206. r supports transactions Overriding the Default The value of the clear auto commit connection parameter overrides this default behavior Passing a 0 as value disables the clearing of the auto commit flag and lets the connection use the database s default commit behavior Please see the database documentation for details on its default transaction setting Use the connection method connection setconnectoption SQL AUTOCOMMIT SQL AUTOCOMMIT ON OFF DEFAULT to adjust the connection s behavior to your needs after the connection has been established but before you have opened a database cursor With auto commit turned on transactions are effectively disabled The rollback method will raise a NotSupportedError when used on such a connection mxODBC Python ODBC Database Interface 6 4 2 6 5 6 5 1 6 5 2 72 Errors due to missing Transaction Support If you get an exception during connect telling you that the driver is not capable or does not support transactions e g mxODBC NotSupportedError S1C00 84 Microsoft ODBC Excel Driver Driver not capable 4226 try to connect with clear auto commit set to 0 mxODBC will then keep auto commit switched on and the connection will operate in auto commit mode Connection objects as context managers Introduction to Context Managers Python 2 5 introduced the new concept of context manager to Python Context managers are Python objects implementing the context manager API
207. r Manual ODBC User Manual DataDirect User Manual e Mac OS X ODBC Administrator Manual Since the layout and operation of these tools is often similar to the Windows ODBC manager you can also have a look at the Windows ODBC documentation for details Starting the ODBC manager will bring up a dialog with tabs for data source creation ODBC tracing and connection pooling as well as a few information tabs showing the versions of installed drivers ODBC Configuration Files On Windows you should always use the Windows ODBC Manager to configure ODBC data sources Even though the Windows ODBC Manager also exposes the standard ODBC configuration files C Windows ODBC INI and C Windows ODBCINST INI these do not contain the full configuration information since this is stored in the Windows registry etc odbc ini System ODBC Data Source Configuration Depending on your ODBC manager installation or OS the file may also reside in a different directory Please consult your ODBC manager documentation for details On Mac OS X the file is located in Library ODBC odbc ini This INI file provides data source information using one INI section per data source In addition to the data source sections there are also a number of higher level sections 1 For Mac OS X 10 6 Snow Leopard you may have to install the ODBC Administrator separately It is available from Apple as disk image http support apple com kb DL895 26 3 Access D
208. r handler on the connection will not see or use the new error handler An error handler has to be a callable object taking the arguments connection cursor errorclass errorvalue where connection is a reference to the connection cursor a reference to the cursor or None in case the error does not apply to a cursor errorclass is an error class which to instantiate using errorvalue as construction argument The default handler will append the tuple errorclass errorvalue to the messages list of the cursor or connection if cursor is None and then raise the exception by instantiating errorclass with errorvalue Note that only database and ODBC driver manager related errors are processed through the error handlers Other errors such as mxODBC internal or AttributeErrors are not processed by these handlers Examples Here s an example of an error handler that allows to flexibly ignore warnings or only record messages Error handler configuration record messages only 0 ignore warnings 0 Error handler function def myerrorhandler connection cursor errorclass errorvalue Default mxODBC error handler The default error handler reports all errors and warnings using exceptions and also records these in connection messages as list of tuples errorclass errorvalue Append to messages list if Cursor is not None cursor messages append errorclass errorvalue elif connection is not None connection messages
209. r than a C long Some ODBC drivers are buggy in that they fail to correctly convert these small integers to longs Added documentation of the exception value layout Added all exception objects including the Warning exception as attributes to the connection objects This enables writing code which can catch exceptions mxODBC Python ODBC Database Interface 176 independent of the mxODBC subpackage being used Added some support for CYGWIN Thanks to Steve Holden for suggesting the needed tweaks Added cursor connection attribute which allows accessing the Connection object used by the cursor Fixed parameter input binding to not change the SQL type due to None parameters after having already bound a different type This should solve the problem with some Oracle drivers complaining about this Added cursor rownumber providing a way to query the current result set position of the cursor Added cursor getcursoroption which can be used to query low level details about the cursor such as timeouts etc Added cursor scroll which enables result set scrolling cursor executemany now accepts sequences of sequences as required by API 2 0 Changed cursor execute no longer accepts list of tuples as parameter Use cursor executemany instead The new SAP DB support is now official Added extensive documentation to the cursor catalog methods Changed the cursor freeset method name to cursor flush The old name is still
210. rces ODBC See the Windows ODBC documentation for details Starting the ODBC manager will bring up a dialog with tabs for data source creation ODBC tracing and connection pooling as well as a few information tabs showing the versions of installed drivers ODBC on 64 bit Windows Versions On 64 bit versions of Windows there are two separate ODBC managers which also keep and manage different lists of ODBC data sources the 64 bit version can be found in C windows system32 odbcad32 exe the 32 bit version is located in C windows sysWOW64 odbcad32 exe 64 bit applications can only use the 64 bit ODBC manager and drivers whereas 32 bit applications can only use the 32 bit ODBC manager and drivers Please make sure that you use the right variant of the ODBC manager when configuring ODBC data sources on 64 bit Windows If not you will get errors from the ODBC manager mentioning problems in finding the given ODBC data source or an architecture mismatch e g Microsoft ODBC Driver Manager The specified DSN contains an architecture mismatch between the Driver and Application ODBC Configuration Files On Windows you should always use the Windows ODBC Manager to configure ODBC data sources Even though the Windows ODBC Manager also exposes the standard ODBC configuration files C Windows ODBC INI and C Windows ODBCINST INI these do not contain the full configuration information since this is stored in the Windows registry 3 Ac
211. re passing it to the underlying ODBC API Result Set Layouts Note that the result set layouts described here may not apply to your data source Some databases do not provide all the information given here and thus generate slightly different result sets Expect column additions and even omissions and do not rely on the column names used in the result set descriptions Search Pattern Parameters The standard catalog method parameters qualifier owner and table accept SQL search patterns as input e g table Sys would return all tables whose name starts with SYS In some cases the catalog functions provide additional search parameters such as procedure or column These parameters then also accept SQL search pattern strings Case sensitivity of Search Patterns The search patterns given as parameters to these catalog methods are usually interpreted in a case sensitive way This means that even if the database itself behaves case insensitive for identifiers you may still not find what you re looking for if you don t use the case which the database internally uses to store the identifier 13 Note that this was changed in mxODBC 3 0 Previously the catalog methods used to return the number of rows in the result set 95 mxODBC Python ODBC Database Interface 96 As an example take the SAP DB it stores all unquoted identifiers using uppercase letters Trying to fetch e g information about a table using a lowercase version of t
212. res of the DB API 2 0 standard Many DB API 1 0 features are still supported too for backward compatibility paramstyle String constant stating the type of parameter marker formatting expected by the interface This is set to qmark since ODBC interfaces always expect to be used as positional placeholder for variables in an SQL statement Parameters are bound to these placeholders in the order they appear in the SQL statement e g the first parameter is bound to the first question mark the second to the second and so on BIND USING SQLTYPE BIND USING PYTHONTYPE Integer values returned by connection bindmethod SQL type binding means that the interface queries the database to find out which conversion to apply and which input type to expect while Python type binding looks at the parameters you pass to the methods to find out the type information and then lets the database apply any conversions The bind method is usually set at compilation time but can also differ from database to database when accessing them via an ODBC manager DATETIME DATETIME FORMAT PYDATETIME DATETIMEFORMAT TIMEVALUE DATETIMEPORMAT TUPLE DATETIMEFORMAT SIRING DATE TIMEPORMAT Integer values which are used by connection datetimeformat and Cursor datetimetormat mxODEC can handle different output formats for date time values on a per connection and per cursor basis See the documentation of the two attributes for more information EIGHTBI
213. ribute to adjust the rounding applied when passing second values with fractions to the database i e from Python to the database Some databases complain about their data types not being capable of representing the precision as given in the fraction value With others it is possible to get rounding errors due to truncation e g of 0 4999 to 0 49 instead of 0 50 The attribute value must be given as integer and defines the resolution of the timestamp values in nanoseconds ns Default is 1 ns Setting the attribute to 1000 would result in Python seconds values to get rounded to the nearest microsecond prior to passing the value to the database Setting it to 250 1000000 would result in seconds to get rounded to the nearest 1 4 second mxODBC applies this rounding when using the ODBC timestamp interface structures and also applies the rounding to mxDateTime input objects in case the database requests the date time value as string It currently does not apply the rounding for strings in case Python datetime objects are used on input 81 mxODBC Python ODBC Database Interface 6 8 1 82 Note Rounding to a full second is prevented to not cause possibly illegal time values This value is inherited by all cursors created from the connection at creation time Note that changing the value of this attribute will not change the timestamp resolution for existing cursors using this connection warningformat Use this attribute to chan
214. ring objects assuming the connection s encoding setting see the encoding attribute of connection objects This setting emulates the behavior of previous mxODEC versions and is the default MIXED STRINGEFORMAT This format lets the ODBC driver decide which string format to use for the communication providing the most efficient way of communicating with the driver Input and output conversion is dependent on the data format the ODBC driver expects or returns for a given column If the driver returns a string a Python string is created if it returns Unicode data a Python Unicode object is used UNICODE STRINGFORMAT This format can be used to emulate Unicode support with a database backend that doesn t have a native Unicode data type or where the ODBC driver cannot handle Unicode data On input Python strings are passed to the ODBC driver as is Unicode objects are converted to 8 bit strings using the connection s encoding setting see the encoding attribute of connection objects and then passed to the ODBC driver 6 mxODBC Connection Objects On output string data is converted to Python Unicode objects based on the same conversion technique Use this setting if you plan to use Unicode objects with non Unicode aware databases e g by setting the encoding to UTF 8 be careful though multibyte character encodings usually take up more space and are not necessarily compatible with the database s string functions NATIVE
215. ris or the BSDs the situation is a lot less encouraging If you have trouble finding a suitable driver you can contact the database vendor or check the SQLSummit list of ODBC drivers eGenix com also provides a generic solution to such problems in form of the mxODBC Connect product which helps you work around the problem of finding a suitable ODBC driver for the client platform See the next section for detail 3 Access Databases using mxODBC 3 3 2 3 3 3 25 mxODBC Connect a general purpose client server solution Since finding good quality ODBC drivers for Unix platforms is often not easy eGenix has developed a new general solution to the problem a client server product called mxODBC Connect The product provides a highly portable client side Python interface module mxODBC Connect Client which connects to a server side service application called mxODBC Connect Server On the client side the mxODBC Connect Client provides an interface which is almost 100 compatible to the standard mxODBC Python interface so you can easily port applications using mxODBC or other DB API compatible adapters to the mxODBC Connect Client On the server side the mxODBC Connect Server takes care of managing the incoming network connections from the mxODBC Connect Clients and interfaces directly to the database using an ODBC driver on the server machine Since the mxODBC Connect Server is typically installed on the database server itself the
216. rite with connection cursor as cursor cursor execute INSERT INTO table VALUES 1 2 Other tasks This not only looks a lot better and also takes care of freeing the resources in case of an error in the block Cursor Type Object mxODBC uses a dedicated object type for cursors Each subpackage defines its own object type but all share the same name CUrsorType mxODBC Python ODBC Database Interface 7 5 Cursor Object Constructors Cursor objects are created using the connection method connection cursor commecti n cursor neme Non e Cursor optiones 1 Constructs a new Cursor Object with the given name using the connection and initializes any provided cursor options If no name is given the ODBC driver or database backend will create one dynamically Please see section 6 7 Connection Object Methods for details 7 6 Cursor Object Methods The following cursor methods are defined in the DB API callproc procname parameters Call a stored database procedure with the given name The sequence of parameters must contain one entry for each argument that the procedure expects The result of the call is returned as modified copy of the input sequence Input parameters are left untouched output and input output parameters replaced with possibly new values The procedure may also provide a result set as output This must then be made available through the standard fetch methods This metho
217. river Manager To enable ODBC level tracing open the etc odbcinst ini or odbcinst ini file and add this section to it ODBC Trace 1 TraceFile tmp odbc log If you already have such entries in the ODBC section make sure that the settings are correct and that Trace is set to 1 After that is done start you application or script using mxODBC and run the code that is causing problems with the driver in question After you ve run the application or script open the odbcinst ini file again and set Trace to 0 This will disable ODBC call level tracing Finally pick up the ODBC trace file from the location you ve chosen tmp odbc log in the example and email it to support egenix com 18 1 4 DataDirect ODBC Driver Manager 165 Please use the same approach as for the iODBC Driver Manager mxODBC Python ODBC Database Interface 18 1 5 Mac OS X ODBC Driver Manager 18 2 166 Open the Mac OS X ODBC Administrator This can be found under Applications Utilities Go to the Tracing tab and select a trace output file under Log File and then click the checkbox Enable Tracing to enable ODBC tracing output Click on Apply have the change take effect After that is done start you application or script using mxODBC and run the code that is causing problems with the driver in question After you ve run the application or script open the ODBC administrator again and disable the Enable Tracing checkbox Finally pic
218. rmation for Unicode data when running in Python type mode Use the VAR variants of character SQL types in favor of the plain SQL type codes to work around issues with padding in some drivers notably the SQL Server ODBC driver Added better documentation for cursor errorhandler and how this inherits from connection errorhandler Added cursor errorhandler example to the documentation Updated the documentation of the SQL types used in both SQL type and Python type binding mode Changes from 2 0 7 to 3 0 0 Added cursor callproc with support for input parameters Added cursor nextset Added aliasing support for platform specific ODBC managers mx ODBC Manager is aliased to the most commonly used ODBC manager for the platform running mxODBC the Windows subpackage on Windows iODBC on all other platforms Added new messages list attribute to both connection and cursor objects All error and warning messages tuples exception class exception value will be appended to these lists The lists are automatically cleared by most cursor and connection methods except the fetch methods and the connection info option methods Changed the type names and repr output of connections and cursor type objects to better reflect the used interface e g on Windows the type name will be mx ODBC Windows cursor rather than just mxODBC Cursor Rearranged the code for fetching SMALLINTs TINYINTs and BITs to do the fetching using a C short rathe
219. rs None Colsep Meadersgp stringify repr Fetch the result set from cursor and format it into a list of strings one for each row header headersep rowl row2Z headers may be given as list of strings It defaults to the header names from cursor description The function will add numbered columns as appropriate if it finds more columns than given in headers Columns are separated by colsep the header is separated from the result set by a line of headersep characters The function calls stringify to format the value data returned by the driver into a string It defaults to repr prin resul rel cursor headers Nons Pretty prints the current result set available through cursor See format_resultset for details on formatting mxODBC Python ODBC Database Interface 12 1 146 mxODBC Globals and Constants Subpackage Globals and Constants Each mxODBC subpackage exports the following constants SOL Singleton object which defines nearly all values available in the ODBC 3 5 header files The sou part of the ODBC symbols is omitted e g SQL AUTOCOMMIT is available as SOL AUTOCOMMIT errorclass Writeable dictionary mapping SQL error code strings ODBC s SQLSTATE to exception objects used by the module If you need to specify your own SQLSTATE to exception class mappings you can assign to this dictionary Changes will become visible immediately sqltype Dictionary mapping SQL
220. ry to point LD LIBRARY PATH to the directory where the driver itself is located mssql Driver usr local freetds lib libtdsodbc so Description MS SQL Server 2008 running on Monet Trace 0 Servername MONET Database tempdb Note that the libtdsodbc so file may be located in a different directory on your machine e Using these settings you can then connect to SQL Server using a simple connection string such as DSN mssql UID username PWD password 4 1 2 General Notes ODBC API Extensions and the SQL Server Native Client The ODBC API is the native MS SQL Server call level interface and provides the best performance when interfacing to SQL Server Microsoft has also extended ODBC with various custom extensions they make available in their SQL Server Native Client API If you need support for those extensions please contact support egenix com Static vs forward only Cursors MS SQL Server supports static ODBC cursors and this results in mxODBC 3 2 to default to using static cursors on all connections While static cursors allow scrolling through the result set and also provides ways of accessing the correct rowcount value it does come with a significant performance penalty We have seen slow downs in fetching rows of 2 3x times for average queries up to 300x for simple ones so we recommend configuring Please note that in mxODBC 3 3 this will always be the default value 37 mxODBC Python ODBC Databa
221. s of this License Agreement and to the extent authorized by this Proof of Authorization Covered Software Software Name lt product name gt Software Version lt product version gt including all patch level releases Software Distribution As officially made available by eGenix com on http www egenix com Operating System any compatible operating system Authorizations 7 1 Application Development eGenix com hereby authorizes Licensee to copy install compile modify and use the Software on the following Developer Installation Targets for the purpose of developing products using the Software as integral part Developer Installation Targets one 1 Developer CPU mxODBC Python ODBC Database Interface 190 7 2 Redistribution eGenix com hereby authorizes Licensee to redistribute the Software bundled with a product developed by Licensee on the Developer Installation Targets the Product subject to the terms and conditions of this License Agreement for installation and use in combination with the Product on the following Redistribution Installation Targets provided that 1 Licensee shall not and shall not permit or assist any third party to sell or distribute the Software as a separate product 2 Licensee shall not and shall not permit any third party to i market sell or distribute the Software to any end user except subject to the terms and conditions of this License Agreement li rent sell lease or otherw
222. s this column returns NULL NUM_PREC_RADIX SMALLINT Either 10 or 2 or NULL If DATA_TYPE is an approximate numeric data type this column contains the value 2 then the COLUMN SIZE column contains the number of bits allowed in the column If DATA_TYPE is an exact numeric data type this column contains the value 10 and the COLUMN SIZE contains the number of decimal digits allowed for the column For numeric data types the database can return a NUM_PREC_RADIX of either 10 or 2 INTERVAL PRECISION SMALLINT Datetime interval precision or NULL is interval types are not supported by the database primarykeys qualifier None owner None table None Query the data source for information on the primary keys of a given table The table parameter is mandatory The method is useful when inspecting unknown database schemas It only supports returning the primary key column s for a single table The catalog method generates a result set having the following schema Column Name Column Datatype Comment TABLE CAT VARCHAR 128 Always NULL TABLE SCHEMA VARCHAR 128 The name of the schema containing TABLE NAME TABLE NAME VARCHAR 128 not NULL The name of the table or view or alias or synonym COLUMN NAME VARCHAR 128 not Primary Key column name 7 mxODBC Cursor Objects 105 Column Name Column Datatype Comment NULL
223. se named pipes as best connectivity option when connecting to a database server running on the same machine MS SQL Server Native Client for Linux Homepage http msdn microsoft com en us library hh477150 28v sql 10 29 aspx Tested with MS SQL Server Native Client for Linux 1 0 The new Microsoft SQL Server Native Client for Linux is a port of the SQL Server Native Client for Windows to Linux It provides an ODBC driver for SQL Server 2008 R2 and 2012 on Linux but also works with SQL Server 2005 and 2008 At the moment only a 64 bit version is available and then only for RedHat RHEL 5 and 6 systems This driver also support the MARS feature See Multiple active result sets MARS on a single connection Driver Limitations e Version 1 0 still has some issues and can produce segfaults but it s already good enough for testing and simple setups e Version 1 0 only works on 64 bit Linux distributions and requires the unixODBC 2 3 1 ODBC manager 2 2 won t work due to ABI differences e The mxODBC DriverConnect API cannot be used with Unicode connection strings when using this driver the SQL Server Native Driver causes a segfaults when trying to connect using a Unicode connection string which triggers the use of Unicode ODBC APIs 4 Accessing Popular Databases 35 Example Configuration for Unix Here is a sample setup for the SQL Server Native Client for Linux e Install the driver following the instructions given by
224. se Interface 38 connections that do not need scroll support to use forward only cursors per default connection mx ODBC Windows DriverConnect connection cursortype mx ODBC Windows SQL CURSOR FORWARD ONLY All cursors created on connection will then default to forward only cursor type Please refer to section 5 7 ODBC Cursor Types for more details on cursor types Multiple Cursors on Connections If you have troubles with multiple cursors on connections to MS SQL Server the MS Knowledge Base Article 140896 INF Multiple Active Microsoft SQL Server Statements has some valuable information for you It seems that you ll have to force the usage of server side cursors to be able to execute multiple statements on a single connection to MS SQL Server According to the article this is done by setting the connection option SQL CURSOR_TYPE to e g SQL CURSOR DYNAMIC dbe seteconnectoption SQL CURSOR TYPE SOL CURSOR DYNAMIC thanks to Damien Morton for tracking this down and digging up the MS KB article International Character Data If you are experiencing problems with MS SQL Server not storing or fetching international character data Unicode Asian encodings etc correctly please have a look at the following MS Knowledge Base Articles e 232580 INF Storing UTF 8 Data in SOL Server e 257668 FIX SQL Server ODBC Driver May Cause Incorrect Code Conversion of Some Characters e 234748 PRB SOL Server ODBC Driv
225. ssued for important warnings like data truncations while inserting etc if the mxODBC default error handler is active and the connection warningformat Or cursor warningformat as set to WARN WARNINGFORMAT DatabaseWarning is a subclass of the standard Python Warning base class This may change in a future release if the DB API is changed to provide a warning class hierarchy as well mxODBC Python ODBC Database Interface 10 6 10 6 1 142 Database Warnings The default behavior of mxODBC is to raise all errors including Warnings which many ODBC drivers issue for truncations loss of precision in data conversions etc This may not always be desirable For this reason mxODBC provides a way to handle database warnings in different ways Default Error Handler The mxODBC default error handler can be adjusted to handle database warnings in three different ways 1 raise a Warning exception for all database warnings this is the default 2 issue a Python Warning for all database warnings compatible with the warning framework in Python 3 ignore all database warnings Adjusting the mxODBC behavior is possible using the connection warningformat Or cursor warningformat attributes As always for these format settings the cursors inherit the setting from the connection they were created from using the value set on the connection at creation time These mx ODBC constants are available for the warningformat attribute
226. t processing binary data using strings wrap the data object using Python buffers via the buffer constructor or Python memory views via the memoryview constructor to have mxODBC use a binary SQL type for interfacing to the driver manager The Oracle ODEC drivers usually need this The long variant is used for binary data longer than 256 bytes Integer SOL SLONG signed long Conversion from the signed long to the SQL column type is left to the ODBC driver manager so expect the usual truncations Long Integer SO CHAR Conversion from the Python long integer is Char done via the string representation since there usually is no C type with enough precision to hold the value Float SQL DOUBLE Conversion from the Python float a C double double to the SQL column type is left to the ODBC driver manager so expect the usual truncations decimal Decimal SOL VARCHAR SOL LONGVARCHAR char Conversion from a Python decimal Decimal instance is done via the string representation to avoid losing precision The long variant is used for decimal representations longer than 256 characters DateTime SOL TIMESTAMP Or SQL DATE Converts the DateTime instance into a TIMESTAMP or DATE struct defined by the ODBC standard The ODBC driver may use the time part of the instance or not depending on the SQL column type DATE or TIMESTAMP Seconds are rounded according to the setting
227. t parameters in stored procedures The reason for this is that the interface for passing back data from the mxODBC Python ODBC Database Interface stored procedure requires knowledge of the data types and sizes before calling the procedure which is often impossible to deduce e g for string data Using result sets to pass back output data Passing back such data in form of one or more result sets gives you a much better alternative which also let s you implement variable length output parameter lists and special output value conversions This can easily be done by adding a SELECT to the stored procedure which then returns the data as additional result set SELECT OutputParaml OutputParam2 or even using multiple result sets SELECT OutputParaml SELECT QutputParame You can then pick up the data using cursor nextset and cursor fetchall rsl c fetchall c nextset rs2 c fetchall c nextset rs3 c fetchall Example gt gt gt c execute select 1 select 2 gt gt gt Tetehialld 1 gt gt gt c nextset True gt gt gt tTetenalli L 27 Oracle Ref Cursors make this easy Oracle has a very nice feature to make this even easier Instead of defining an output variable or a set of output variables you simply define a REF CURSOR as output variable in your stored procedure You can then access the open cursor after calling the stored procedure by simply using t
228. ted that in some Sybase configurations notably when using a statement cache in the server the problem also occurs with the 32 bit versions of the driver According to Sybase a work around is to turn on trace flag numbers 8021 and 7741 in the server BIGINT columns can cause data corruption Even though Sybase ASE 15 does support a BIGINT column type the Sybase ESD 3 ODBC driver has problems interfacing to it and data is corrupted As example inserting a 2 to a BIGINT columns results in 1 being read back inserting 2147483648 results in 47493012874424 read from the column Since this is a bug in the ODBC driver future ESDs may fix the issue In any case please carefully check for this problem before using BIGINT columns with the driver Driver Notes e The Sybase ASE driver only supports forward scrolling so cursor scroll will just work with relative and positive increments e There is no support for cursor rownumber in the driver Example Configuration for Unix e Add a Sybase driver section to the odbcinst ini file the location of the driver file may be different on your system ODBC Drivers SybaseASE Installed SybaseASE Description SybaseASE ODBC Driver Driver opt sybase DataAccess ODBC 1ib libsybdrvodb so setup e Edit the odbc ini file based and add a sybasease section the location of the driver file may be different on your system It is also necessary to point LD LIBRARY PATH to the dire
229. tent of CREATE_PARAMS is to enable an application to customize the interface for a DDL builder NULLABLE SMALLINT not NULL Indicates whether the data type accepts a NULL value SQL NO_NULLS NULL values are disallowed SQL NULLABLE NULL values are allowed CASE SENSITIVE SMALLINT not NULL Indicates whether the data type can be treated as case sensitive for collation purposes valid values are SQL TRUE and SQL FALSE SEARCHABLE SMALLINT not NULL Indicates how the data type is used in a WHERE clause Valid values are SQL UNSEARCHABLE if the data type cannot be used in a WHERE clause 7 mxODBC Cursor Objects 103 Column Name Column Datatype Comment SQL LIKE_ONLY if the data type can be used in a WHERE clause only with the LIKE predicate SQL ALL_EXCEPT_LIKE if the data type can be used in a WHERE clause with all comparison operators except LIKE SQL SEARCHABLE if the data type can be used in a WHERE clause with any comparison operator UNSIGNED_ ATTRIBUTE SMALLINT Indicates where the data type is unsigned The valid values are SQL TRUE SQL FALSE or NULL A NULL indicator is returned if this attribute is not applicable to the data type FIXED_PREC_SCALE SMALLINT not NULL Contains the value SQL TRUE if the data type is exact numeric and always has the same precision and scale otherwise it contains SQL FALSE AUTO INCREMENT SM
230. the work around oes not work for CLOB columns if you pass in data with less than 256 bytes an error is raised by the driver Added work around for EasySoft driver to always bind using the SQL_LONGxxx types Fixed a typo in the FETCH_UNKNOWN_TYPES_AS STRINGS and SEND_UNKNOWN_TYPES_AS_ STRINGS compile time options Added work around for bug in MS Access ODBC driver to always send at least sqllen 1 for bound parameters It rejects parameters bound with sqllen 0 and issues an HY104 error Added statistics API which allows checking the number of currently open connections and cursors mxODBC Python ODBC Database Interface e Ported to Python 2 5 and tested with that version e Fixed bugglet in mxODBC_UnicodeAsSQLWCHAR where two parameters were switched causing the buffer length to appear as string length e Changed HY019 error mapping from InterfaceError to ProgrammingError MS SQL Server returns this for integer overflow errors e PyNumber_Int can return a Python long in Python 2 5 and later Fixed mxODEC to deal with this case so that binding to integer columns continues to work even if you pass in a Python long and the database requested an integer e Fixed 64 bit integer binding on 64 bit platforms SQL_C_SLONG does not map to a 64 bit type but a 32 bit type weird but true and caused by the fact that Win64 works this way longs on Win64 only have 32 bits e Added test cases for BYTEA PostgreSQL e Added mapping
231. the line Threading N to the driver entry in odbcinst ini where N is the locking level O 3 13 6 mx ODBC DataDirect DataDirect ODBC Manager Tested with DataDirect ODBC Manager 5 1and 6 0 DataDirect is a proprietary ODBC manager for Unix developed by DataDirect It is used by a number of ODBC drivers available for Unix platforms 13 mx ODBC Subpackages eGenix com provides binary subpackages for this ODBC driver manager only on Linux x86 and x64 platforms If you need the subpackage on other platforms as well please contact support egenix com for help 13 6 1 Notes General Recommendations e Please always use the DriverConnect API to connect to the data source if you need to pass in extra configuration information such as names of log files etc e The DataDirect ODBC manager may not work correctly with Unicode data even though the driver may support Unicode This is due to the fact that the DataDirect manager provides three different options of encoding Unicode data UTF 8 UTF 16 ODBC standard on Windows and UTF 32 Most drivers assume UTF 16 but don t necessarily implement the special call needed to configure the DataDirect manager to assume this as well The manager then defaults to UTF 8 and this causes the Unicode transport to fail You can try to work around this by adding an entry Needed by the DataDirect ODBC manager possible values 1 UTF 16 2 UTF 8 DriverUnicodeType 1 to the dri
232. the previous call to execute did not produce any result set or no call was issued yet mxODBC will move the associated database cursor forward by one row only pr lust Frees any pending result set used by the cursor If you only fetch some of the rows of large result sets you can optimize memory usage by calling this method Note that execute and all the catalog methods do an implicit flush prior to executing a new query sgetcolattribute position info id Get information about the result set column position The column index must be given as 0 based integer i e the first result setup column has the index 0 info id must be an integer and identifies the requested field information Suitable values are available through the sor object see the Constants section 10 5 for details The method returns a tuple integer string giving an integer decoding in native integer byte order of the first bytes of the API s result as well as the raw buffer data as string It is up to the caller to decode the data e g using the struct module This API gives you a wide range of information about the result set column See the ODBC SQLColAttribute AP Documentation for more information Some of these values are also available through the cursor description attribute This is a list of useful info ids Option Comment 7 mxODBC Cursor Objects 89 Option Comment oba DESC AUTO UNIQUE VAL
233. thin the Python application If you need to specify your own SQLSTATE to exception mappings you can assign to the errorclass dictionary Exception Value Format All ODBC driver generated exceptions use a standard exception value layout The error value will always bea tuple sqlstate sqlcode messagetext lineno with the following meanings sqlstate SQL state as string these values are defined in the ODBC Documentation and by the ODBC driver manager sqlcode Numeric SQL error code as integer these values are defined in the ODBC Documentation and by the ODBC driver manager messagetext Message text as string explaining the error These strings usually have the format Vendor Driver Database Message Text 11ne no Line number in the mxODBC source code which generated the message This is very useful for support purposes mxODBC Python ODBC Database Interface 10 4 10 4 1 140 Error Handlers If you want to provide your own error handler e g to mask database warnings you can do so by assigning to the errorhandler attribute of connections and cursors or passing a callback function to the connection constructors at connection creation time using the errorhandler keyword argument Error handlers are inherited from connections to cursors so it normally suffices to set an error handler on the connection object to have it take affect for all subsequently created cursors Cursors created prior to setting the erro
234. thod makes cursor objects usable as context manager together with the exit__ method and is called when entering a with block new in Python 2 5 e Kit exc type exc value exe tb Returns True in case exc_type is set to None no exception set and closes the cursor Returns False in case exc_type is set to an exception and also closes the cursor This method is part of the context manager API and is called when leaving a with block new in Python 2 5 94 7 mxODBC Cursor Objects 7 6 1 Catalog Methods Catalog methods allow you to access meta level and structural information about a data source in a portable way Some ODBC drivers do not support all of these methods or return unusable data As a result you should verify correct operation for your target data sources prior to relying on these methods Common Interface All of the following catalog methods use the same interface they do an implicit call to cursor execute and return their output in form of a list of rows which that can be fetched with the cursor fetch methods in the usual way The number of available rows is available via cursor rowcount All catalog methods support keywords and use the indicated default values for parameters which are omitted in the call Please refer to the ODBC Documentation for more detailed information about parameters if you pass None as a value where a string would be expected that entry is converted to NULL befo
235. ticks value as Python number While you should use DateTime instances the module also accepts Python datetime datetime instances datetime date instances the time part is then set to 00 00 00 ticks Python numbers indicating the number of seconds since the epoch these are converted to local time and then stored in the database and tuples year month day hour minute second on input Seconds are rounded according to the setting of the timestampresolution setting which defines the resolution of the timestamps in nanoseconds mxODBC will round the timestamp s second value to the nearest nanosecond fraction defined by this setting in order to avoid issues with float second values which sometimes cannot be represented with full accuracy If not set the timestampresolution attribute defaults to 1 nanosecond so rounding usually is done to the nearest nanosecond which is also the smallest fraction supported by the ODBC standard mxODBC Python ODBC Database Interface 3 4 126 stringified object SQL Type Python Type Comments Any nullable column None The Python None singleton is converted to the special SQL NULL value Unsupported Type String or Input binding to these columns is done via strings or stringified versions of the input data Note that for mxDateTime input objects seconds rounding is applied just like for SQL TIMESTAMP SQL types Python Type Input Binding
236. ting old Python applications to the new interface Differences Here is a list of differences between mxODBC and the DB API 2 0 specifications e cursor description doesn t return display size and internal_size both values are always None since this information is not always available through ODBC interfaces and the values are not commonly used in applications If you need to access this information you can use the 5 mxODBC Overview 5 2 5 2 1 59 cursor getcolattribute method with info ids SQL DESC DISPLAY SIZE and SQL DESC_OCTET LENGTH e cursor callproc is only implemented for input parameters for reasons explained in section 5 6 Stored Procedures e db setinputsizes and db setoutputsizes are dummy functions this is allowed by DB API 2 0 e The type objects constructors formerly found in the dbi module defined by DB API 1 0 are only needed if you want to write database independent code e The connection constructor is available under three different names ODBC DB API 1 0 connect DB API 2 0 and Connect mxODBC specific See the next section for details on the used parameters mxODEC also defines a DriverConnect constructor which is available for ODBC managers and some ODBC drivers If you can please use the DriverConnect API since this provides more flexibility in configuring the connection mxODBC extends the DB API specification in a number of ways If you want to stay compatible to
237. tion on a closed connection or cursor will result in a ProgrammingError to be raised This variable can be used to conveniently test for this state 114 7 mxODBC Cursor Objects coLcoun This read only attribute specifies the number of columns in the current result set The attribute is 1 in case no execute has been performed on the cursor command Provides access to the last SQL command string or Unicode object that was passed to prepare or execute If no such command is available None is returned It is set by prepare and execute and reset by calling one of the catalog methods or close on the cursor Note that command may be a Unicode object in case a Unicode object was passed to one of the above methods connect oT Connection object on which the cursor operates lt Curscrly pe Read write attribute that sets the ODBC cursor type this cursor It takes the same values as the connection cursortype instance variable and defaults to the creating connection object s settings for connection cursortype For possible values please see the connection cursortype attribute in section 6 8 Connection Object Attributes Changes to the cursor type must be made before opening the cursor ie before executing a statement on it Please refer to section 5 7 ODBC Cursor Types for more details on cursor types datetimeformat Attribute to set the output format for date time timestamp columns
238. to and from longchar and ntext columns for MS SQL Server Changes from 2 0 3 to 2 0 4 e Enhanced compatiblity to Unicode aware ODBC drivers such as the latest MS SQL Server and MS Access ODBC drivers Exchanging native Unicode data with these drivers is now supported for input parameters and output data retrieved using the fetchXXX APIs Catalog methods and other APIs do not support Unicode e Rearranged the code for fetching SMALLINTs TINYINTS and BITs to do the fetching using a C short rather than a C long Some ODBC drivers are buggy in that they fail to correctly convert these small integers to longs Changes from 2 0 2 to 2 0 3 e Enhanced test script mx ODBC Misc test to show available data sources for ODBC managers before connecting e Added docs about usage of mxODBC with Thomas Heller s py2exe e Added work around for some ODBC drivers which don t initialize the buffers for small integers correctly This lead to wrong results when reading data from SMALLINT columns with these drivers Writing to these column types did not pose a problem Thanks to Villiam Manera for bringing this to my attention again mxODBC already included a hint to the problem but no actual fix for it Changes from 2 0 1 to 2 0 2 e Added a new section on stored procedures to the docs Thanks to Jim Vickroy for finding out about the usage of PRINT in MS SQL Server stored procedures e Tested under Python 2 1 Changes from 2 0 0 to 2 0 1
239. tudents for educational purposes Installations aimed at administrational or organizational purposes are not regarded as Educational Environment License Grant Subject to the terms and conditions of this License Agreement eGenix com hereby grants Licensee a non exclusive world wide license to 1 use the Software to the extent of authorizations Licensee has acquired and 2 distribute make and install copies to support the level of use authorized providing Licensee reproduces this License Agreement and any other legends of ownership on each copy or partial copy of the Software If Licensee acquires this Software as a program upgrade Licensee s authorization to use the Software from which Licensee upgraded is terminated Licensee will ensure that anyone who uses the Software does so only in compliance with the terms of this License Agreement Licensee may not 1 use copy install compile modify or distribute the Software except as provided in this License Agreement 2 reverse assemble reverse engineer reverse compile or otherwise translate the Software except as specifically permitted by law without the possibility of contractual waiver or 3 rent sublicense or lease the Software Authorizations The extent of authorization depends on the ownership of a Proof of Authorization for the Software Usage of the Software for any other purpose not explicitly covered by this License Agreement or granted by the Proof of Aut
240. type SQL INTEGER sqltype SQL FLOAT return sqltype sqllen Now tell the cursar to use this converter cursor setconverter converter Auto Conversions While you should always try to use the above Python types for passing input values to the respective columns the package will try to automatically convert the types you give into the ones the database expects when using the SQL Type bind method e g an integer literal 123 will be converted into an integer 123 by mxODBC if the database ODBC driver requests an integer The situation is different in Python type binding mode BIND USING PYTHONTYPE the Python type used in the parameter is passed directly to the database thus passing 123 or 123 does make a difference and could result in an error from the database 8 Data Types supported by mxODBC 3 3 133 Unicode and String Data Encodings mxODBC also supports Unicode objects to interface with databases As more databases and ODBC drivers support Unicode natively using Unicode for text data stored in database becomes more attractive than ever and allows you to avoid the problems you typically face when having to deal with different text encodings and code pages in databases Even if you don t have access to an ODBC capable of dealing with Unicode natively you can still take advantage of the auto conversion mechanisms in mxODBC to simulate Unicode capabilities mxODBC provides several different run time configurations to
241. type codes these are returned in the type field of cursor description to type strings All natively supported SQL type codes are included in this dictionary The contents may vary depending on whether the ODBC driver manager defines these types or not CHAR VARCHAR LONGVARCHAR BINARY VARBINARY LONGVARBINARY TINYINT SMALLINT INTEGER BIGINT DECIMAL NUMERIC BIT REAL FLOAT DOUBLE DATE TIME TIMESTAMP CLOB BLOB TYPE DATE TYPE TIME TYPE TIMESTAMP UNICODE UNICODE LONGVARCHAR UNICODE VARCHAR WCHAR WVARCHAR WLONGVARCHAR ODBC 2 0 type code integers for the various natively supported SQL types These map to integers as returned in the type field of cursor description They are also available through the SQL singleton e g SOL CHAR The dictionary sqlt ype provides the inverse mapping The codes mentioned in square brackets are optional and only available if the ODBC driver manager supports a later ODBC version than 2 5 Note that mxODBC has support for unknown SQL types it returns these types converted to strings The conversion is done by the ODBC driver and may be driver dependent threadsafety Integer constant stating the level of thread safety the interface supports It is always set to 1 meaning that each thread must use its own connection 12 mxODBC Globals and Constants 147 apilevel String constant stating the supported DB API level This is set to 2 0 since mxODEC supports nearly all featu
242. ually and point the package tools directly at the downloaded egg package files if needed This may be needed in case the package tools cannot determine which egg package files to download For installation using Windows installers or our distutils compatible prebuilt package format you will also have to manually download the files Manual Download You can download the binary archives Windows installers egg files or prebuilt archives for your combination of platform Python version and Unicode variant from the eGenix com web site at http www egenix com 2 Installation Please make sure that you download the right version for your Python installation If you get import errors or notices of failed initialization you likely have the wrong product version installed These parameters make a difference Operating System Platform All recent versions of these operating systems are supported e Windows e Linux e Mac OS X e FreeBSD e Solaris Please check the eGenix com web site for the detailed list of available downloads for these platforms If your platform is not among those listed above or on the web site eGenix also provides custom porting services to have mxODBC ported to your platform Please write to sales egenix com for details Python Build Version To check which Python version you are using startup the Python interpreter using the V option python y This will print out the Python version number
243. ubpackages or build custom ones on request if there is a need Please contact support egenix com for details 14 Hints Links to other Resources 14 14 1 14 2 157 Hints Links to other Resources Running mxODBC from a CGI script ODBC drivers and managers are usually compiled as a shared library When running CGI scripts most HTTP daemons or web servers don t pass through the path for the dynamic loader e g LD_LIBRARY_PATH to the script thus importing the mxODBC C extension will fail with unresolved symbols because the loader doesn t find the ODBC driver manager s libs To have the loader find the path to those shared libs you can either wrap the Python script with a shell script that sets the path according to your system configuration or tell the HTTP daemon to set or pass these through see the daemon s documentation for information on how to do this for Apache the directives are named SetEnv and PassEnv On Windows you also have to take into account that the ODBC data sources defined in the ODBC manager are usually restricted to specific user accounts You can work around this by either setting up the ODBC data sources for the web server service account or by configuring the data as system data sources Running mxODBC with mod_wsgi Using mxODBC with mod wsgi is generally possible However since the script will run under a restricted user account some care has to be taken to make the setup work Please s
244. uding all patch level releases Software Distribution As officially made available by eGenix com on http www egenix com Operating System any compatible operating system Authorizations eGenix com hereby authorizes Licensee to copy install compile modify and use the Software on the following Installation Targets under the terms of this License Agreement Installation Targets one 1 CPU Use of the Software for any other purpose or redistribution IS NOT PERMITTED BY THIS PROOF OF AUTHORIZATION mxODBC Python ODBC Database Interface 4 Proof This Proof of Authorization was issued by lt name gt lt title gt Langenfeld lt date gt Proof of Authorization Key lt license key gt 188 20 Copyright License 189 EGENIX COM PROOF OF AUTHORIZATION 1 Developer CPU License Example This is an example of a Proof of Authorization for a 1 Developer CPU License These proofs are either wet signed by the eGenix com staff or digitally PGP signed using an official eGenix com PGP key License Grant eGenix com Software Skills and Services GmbH eGenix com having an office at Pastor Loeh Str 48 D 40764 Langenfeld Germany hereby grants the Individual or Organization Licensee Licensee lt name of the licensee gt a non exclusive world wide license to use the software listed below in source or binary form and its associated documentation the Software under the terms and condition
245. uptools doesn t provide an uninstall command you have to manually remove the installation 1 remove the egenix mxodbc egg directory from your Python site packages directory and 2 edit the file easy install pth in that directory to remove the corresponding egg entry Installation using prebuilt package archives Prebuilt package archives are standard distutils source distribution packages which have been built on the respective platforms without performing the installation step The source parts are also removed from those packages You can think of the prebuilt packages as source package installations that were frozen just before running the install command When installing these you just need to run the last step after unpacking the package the distutils insta11 command No additional software is needed to install these packages Before You Start Upgrading When upgrading from a previous version of mxODBC you can either install the new version over the previous version or first uninstall the previous version See 2 4 3 Uninstall for instructions License Files In order to use mxODBC you will need license files from eGenix com If you want to test the product before buying it you can request evaluation licenses via the eGenix com web site at http www egenix com 2 Installation 2 4 2 15 When buying licenses from the eGenix com online shop http shop egenix com you will receive the license files i
246. ur application Supported ODBC Versions mxODBC can be configured to use ODBC 2 x or 3 x interfaces by setting the ODBCVER symbol in mxODBC h to the needed value It uses the value provided by the ODBC driver header files per default which usually is the latest ODBC standard version available Most ODBC drivers today support ODBC 3 x and thus mxODBC will try to use APIs from this version if available ODBC Managers All supported ODBC managers MS ODBC Manager iODBC unixODBC and DataDirect provide the ODBC 3 x interfaces and map these to ODBC 2 x interfaces in case the driver for the database does not comply to ODBC 3 x However some drivers only pretend to be ODBC 3 x compliant and raise Driver not capable exceptions when using certain ODBC 3 x APIs or features If you run into such an situation please contact support for help The only way to solve this problem currently lies in adding workarounds which are specific to a database To find out which ODBC version is being supported by the ODBC driver you can use connection getinfo SQL DRIVER ODBC VER 1 This will return a string giving you the ODBC version number e g 03 51 00 Changes between ODBC 2 x and 3 x Please also note that there are some changes in behavior between ODBC 2 x and 3 x compatible drivers managers which means that certain option settings differ slightly between the two versions and that special cases are treated differently for ODBC 3 x than for ODB
247. using mxODBC 31 you upgrade an ODBC driver to a newer version you may have to change all DSN less connection setups due to changes in the ODBC driver name We recommend to only use DSN less setups if absolutely necessary or in cases where access to the ODBC configuration files is otherwise not possible DNS less Connection String A DNS less connection provides all configuration information you d normally place into the odbc ini file including a textual representation of the driver location based on the name used in odbcinst ini e g Driver MySQL ODBC 3 51 Driver Server mysql example net Database mydb Note the curly brackets around the driver name The name given here must match the one used in the odbcinst ini or etc odbcinst ini file The ODBC manager will then map the name to the registered driver file location A DSN mydsn entry in the connection string is no longer needed For a list of common DSN less connection strings have a look at the ConnectionStrings com website In order to connect to a database using a DSN less connection string you simply pass the string to the mx ODBC Manager DriverConnect API mxODBC Python ODBC Database Interface 4 1 4 1 1 32 Accessing Popular Databases This section provides information on available ODBC drivers for various popular database as well as notes regarding setup functionality or available workarounds for compatibility problems eGenix com f
248. ut each of the result columns of a query The type code compares equal to one of Type Objects defined below Type Objects may be equal to more than one type code e g DATETIME could be equal to the type codes for date time and timestamp columns mxODEC returns more detailed description about type codes in the description attribute See the section 8 Supported Data Types for details The type objects are only defined for compatibility with the DB API standard and other database interfaces Each subpackage exports the following constructors and singletons Date year month day This function constructs an mxDateTime DateTime object holding the given date value The time is set to 0 00 00 Time hour minute second This function constructs an mxDateTime DateTimeDelta object holding the given time value Timestamp year month day hour minute second This function constructs an mxDateTime DateTime object holding a time stamp value DateFromTicks ticks This function constructs an mxDateTime DateTime object holding the date value from the given ticks value number of seconds since the epoch see the documentation of the standard Python time module for details Usage of Unix ticks number of seconds since the Epoch for date time database interfacing can cause troubles because of the limited date range they cover mxODBC Python ODBC Database Interface TimeFromTicks ticks This function constructs an mxDateTime DateTimeDelta
249. ute is 1 in case no execute has been performed on the cursor or the rowcount of the last operation is not determinable by the interface or the database You should check whether the database you are interfacing to supports rowcount before writing code which relies on it Many databases such as MS Access and Oracle do not provide this information to the ODBC driver so rowcount will always be 1 cownumber This read only attribute provides the current O based row position of the cursor in the result set The next fetch will return rows starting at the given position The row position is automatically updated whenever the cursor moves through the result set either due to fetches or scrolls The attribute is None in case no execute has been performed on the cursor or the cursor position cannot be determined You should check whether the database you are interfacing to supports rownumber before writing code which relies on it Many databases such as MS Access and Oracle do not provide this information to the ODBC driver so rownumber will always be None prtringtormat Attribute to set the conversion format for string columns on a per cursor basis It takes the same values as the connection stringformat instance variable and defaults to the creating connection object s settings for connection stringformat mxODBC Python ODBC Database Interface timestampresolution Attribute to set the timestamp reso
250. ver section in your odbc ini file See this page for details http web datadirect com resources odbc unicode unix html e In some cases we have observed segfaults when using ODBC drivers with the DataDirect ODBC manager These were related to the odbc ini being to large Reducing the size of the ODBC configuration file resolved the problem It is not clear whether the segfaults was caused by the driver or the driver manager or just a specific combination of both 64 bit Platforms e There are no known issues regarding 64 bit platforms 13 7 ODBC Driver Subpackages In previous mxODBC releases eGenix com included a limited set of additional subpackages with support for directly linking against specific ODBC drivers on Unix platforms 155 mxODBC Python ODBC Database Interface 156 Since these setups caused a lot of support requests due to configuration problems and version mismatches between the driver versions we used to build the binary mxODBC distribution and the ones deployed at customer sites we have decided to drop general support for these additional subpackages It is usually better to use one of the available ODBC driver manager packages to configure and manage the data sources These driver managers also provide a further abstraction layer between ODBC applications and the drivers removing ODBC level compatibility issues which makes the ODBC setup a lot less error prone eGenix com can still provide specific s
251. with Unicode connection strings which causes stack corruption Please don t use Unicode connection strings with the MS SQL Server Native Client for Linux driver since there s no way we can work around this problem we only know the type of driver after connection and then it s already too late Changes from 3 1 0 to 3 1 1 Added compatibility with eGenix com mx Base Distribution 3 2 0 GA which now also supports Python2 7 and Windows x64 Changes from 3 0 4 to 3 1 0 Added native Win64 support to mxODBC Added Python 2 7 support and builds for all platforms Added workarounds for Oracle Instant Client ODBC driver This is now fully supported by mxODBC We found that cursor executedirect is not supported by the Oracle Instance Client ODBC driver Please use execute instead Updated support for the latest IBM DB2 9 7 ODBC drivers Enhanced compatibility of mxODBC with the Sybase ASE 15 ODBC drivers on Unix mxODBC will now accept datetime date objects for datetime timestamp columns in SQL type binding mode by using 00 00 00 as time value This is useful when working with MS SQL Server 2000 and 2005 which don t support DATE columns Added support for Netezza to mxODBC Added new ODBC manager subpackage mx ODBC DataDirect for the DataDirect ODBC manager This is currently only available on 32 bit and 64 bit Linux platforms mxODBC now supports the Teradata database via the new mx ODBC DataDirect subpackage mxODBC now sup
252. with the difference that the file must start with the line oDBc and each keyword value pair must be on a separate line e g postgresql dns ODBC Driver usr local postgresgl lib psqlodbcw so Database mydb ServerName postgresql example net Port 5432 Debug 0 Optimizer CommLog 0 ReadOnly 0 SSLmode require ByteaAsLongVarBinary 1 TextAsLongVarchar 1 0 Please see the FILEDSN MS Knowledge Base article 165866 for details regarding the file format In order to connect to such a data source you have to use the mx ODBC Manager DriverConnect API and provide a FILEDSN etc postgresql dns entry instead of the usual DSN mydsn as part for the connection string See the ODBC File Data Source documentation for more details DSN less Connections If you don t want to bother setting up a data source in the ODBC manager you can also use a DSN less connection setup Pros and Cons of using DSN less Connections These setups include all required driver and connection information in the connection string itself All connection information is thus under the control of the application without any system ODBC manager being aware of the connection setup This has both up and downsides The most important downside is that changes to the server system can no longer be administered through the ODBC manager but instead have to be repeated in each application using a DSN less setup Even 3 Access Databases
253. word of the pseudo literal e g CURRENT DATE with no enclosing quotes If NULL was specified as the default value then this column returns NULL If the default value cannot be represented without truncation then this column contains TRUNCATED with no enclosing single quotes If no default value was specified then this column is NULL It is possible that no usable information is returned in this column due to optimizations SQL DATA TYPE SMALLINT not NULL ODBC3 SQL data type This column is the same as the DATA_TYPE column except for date time types SQL DATETIME SMALLINT The subtype code for datetime data types SUB SQL CODE DATE SQL CODE_TIME SQL CODE_TIMESTAMP For all other data types this column returns NULL CHAR_OCTET_ INTEGER Contains the maximum length in octets for a LENGTH Character data type column For Single Byte character sets this is the same as COLUMN SIZE For all other data types it is NULL ORDINAL _ INTEGER not NULL The ordinal position of the parameter column in POSITION the procedure call The first column has an ordinal position of 1 IS NULLABLE VARCHAR 254 Contains the string NO if the column is known to be not nullable if this cannot be determined or YES if it is known to be nullable 7 mxODBC Cursor Objects 109 specialcolumns qualifier None owner None table None coltype S0L BEST ROWLD Scope s0l SCOPE SESSION nullable S
254. xODBC tries to convert the input variable into that type This is the preferred binding mode since it allows to choose the right conversion before passing the data to the ODBC driver Python type BIND USING PYTHONTYPE mxODBC looks at the type of the binding input variable and passes its value to the database directly conversion is done by the ODBC driver manager as necessary The default depends on the capabilities of the ODBC driver being used on the connection mxODBC will always try to use the SQL type binding mode BIND USING SQLTYPE since this offers more flexibility than Python type binding mxODBC Python ODBC Database Interface 8 2 1 Adjusting the Type Binding Mode If you run into problems when using mxODBC in SQL type binding mode please try to use Python type binding mode by configuring the connections to use Python type binding mode connection bindmethod BIND USING PYTHONTYPE 8 2 2 Per Statement Binding Mode With some database drivers it is also possible to trigger the Python type binding mode in a more fine grained way by using cursor executedirect method or the direct 1 parameters on other execution methods for running SQL statements against the database mxODBC will then send the statements as is to the database server and apply Python type binding for the parameters 8 3 SQL Type Input Binding The following data types are used for SQL type input binding mode connection bind

Download Pdf Manuals

image

Related Search

Related Contents

  Dynamics Customer Agreement      Skywalk NVRs User`s Manual  Fresh 'n Rebel 2LC050YL USB cable    

Copyright © All rights reserved.
Failed to retrieve file