杰瑞科技汇

Python如何连接Informix数据库?

Of course! Here is a comprehensive guide to using informixdb, a popular Python library for connecting to IBM Informix databases.

What is informixdb?

informixdb is a Python extension module that allows Python programs to access IBM Informix database servers. It provides a Python DB-API 2.0 compliant interface, which means if you know how to use libraries like psycopg2 (for PostgreSQL) or mysql-connector-python (for MySQL), you will feel right at home with informixdb.

It's important to note that informixdb is a C extension. This means it requires the Informix Client SDK to be installed on the machine where your Python code is running.


Prerequisites: Installing the Informix Client SDK

This is the most critical step. The informixdb module acts as a bridge between Python and the Informix client libraries. Without the SDK, the C extension cannot be compiled or will fail to run.

Step 1: Download the Informix Client SDK

  • Go to the IBM website: IBM Informix Client Downloads
  • You will need an IBM ID to download it. Select the appropriate version for your operating system (Linux, Windows, macOS, etc.).
  • The download is typically a large file (e.g., informix_client_sdk_4.x.x_linuxx86_64.tar.gz).

Step 2: Install the SDK

The installation process varies by OS.

For Linux (e.g., Red Hat/CentOS/Fedora):

# Unpack the downloaded archive
tar -xvzf informix_client_sdk_4.x.x_linuxx86_64.tar.gz
# Navigate to the directory
cd informix_client_sdk
# Run the installer as root
sudo ./installclients

During the installation, you will be asked to choose an installation directory. A common choice is /opt/IBM/informix. Remember this path.

For Windows: Run the downloaded .exe installer and follow the on-screen instructions. Note the installation path, for example, C:\IBM\infx.

Step 3: Set Environment Variables

After installation, you must tell your system where to find the Informix libraries.

  • INFORMIXDIR: This must point to the SDK installation directory.
  • LD_LIBRARY_PATH (Linux/macOS) or PATH (Windows): This must include the $INFORMIXDIR/lib (or %INFORMIXDIR%\bin) directory so the system can find the .so (Linux) or .dll (Windows) files.

Example for Linux (add to ~/.bashrc or ~/.profile):

export INFORMIXDIR=/opt/IBM/informix
export LD_LIBRARY_PATH=$INFORMIXDIR/lib:$LD_LIBRARY_PATH

Then, run source ~/.bashrc to apply the changes.

Example for Windows (add to "Environment Variables" in System Properties):

Variable name: INFORMIXDIR
Variable value: C:\IBM\infx
Variable name: PATH
Variable value (add to the end): ;C:\IBM\infx\bin

Installing the informixdb Python Package

Once the Informix Client SDK is correctly installed and configured, you can install the Python module using pip.

pip install informixdb

If you encounter compilation errors, it's almost always because the INFORMIXDIR environment variable is not set correctly for the pip installation process.


Connecting to an Informix Database

You connect using the informixdb.connect() function. The connection string (DSN) is crucial and follows a specific format.

Connection String Format

The standard format is: 'INFORMIXDB_SERVER:<server_name>;DATABASE=<database_name>;HOST=<hostname_or_ip>;SERVICE=<port_number_or_service_name>;USER=<username>;PASSWORD=<password>'

  • INFORMIXDB_SERVER: The name of the Informix server as defined in the sqlhosts file on the client machine.
  • DATABASE: The name of the database you want to connect to.
  • HOST: The IP address or hostname of the database server.
  • SERVICE: The port number or the service name (from /etc/services on Linux) that the Informix listener is using.
  • USER and PASSWORD: Your database credentials.

Example Code

Here is a complete, runnable example.

import informixdb
# Define the connection string
# Replace with your actual server details
connection_string = (
    'INFORMIXDB_SERVER:ol_serveur;'  # Server name from sqlhosts
    'DATABASE=testdb;'                # Database name
    'HOST=192.168.1.100;'            # IP or hostname of the DB server
    'SERVICE=9088;'                  # Port number
    'USER=informix;'                 # Database user
    'PASSWORD=mysecretpassword'      # User's password
)
try:
    # 1. Establish the connection
    print("Connecting to the database...")
    conn = informixdb.connect(connection_string)
    print("Connection successful!")
    # 2. Create a cursor object
    cursor = conn.cursor()
    # 3. Execute a simple query
    print("\nExecuting query: SELECT COUNT(*) FROM customer;")
    cursor.execute("SELECT COUNT(*) FROM customer;")
    # 4. Fetch the result
    # fetchone() returns a tuple, e.g., (12345,)
    count = cursor.fetchone()[0]
    print(f"Total customers: {count}")
    # 5. Execute a query with parameters (prevents SQL injection)
    print("\nExecuting query with parameters: SELECT * FROM customer WHERE customer_num = %s;")
    customer_num_to_find = 101
    cursor.execute("SELECT customer_num, company FROM customer WHERE customer_num = %s;", (customer_num_to_find,))
    # 6. Fetch all results
    results = cursor.fetchall()
    if results:
        print(f"Found customer: {results[0]}")
    else:
        print(f"Customer with number {customer_num_to_find} not found.")
    # 7. Commit the transaction (if you made any changes)
    # conn.commit()
except informixdb.Error as e:
    # 8. Handle database errors
    print(f"An Informix database error occurred: {e}")
    # If an error occurs, you might want to roll back any uncommitted changes
    # conn.rollback()
finally:
    # 9. Always close the cursor and connection
    if 'cursor' in locals():
        cursor.close()
    if 'conn' in locals() and conn:
        conn.close()
        print("\nDatabase connection closed.")

Common Operations

Fetching Data

  • cursor.fetchone(): Fetches the next single row from the query result set. Returns None if no more rows are available.
  • cursor.fetchall(): Fetches all remaining rows from the query result set. Returns an empty list if no rows are found.
  • cursor.fetchmany(size): Fetches the next size number of rows. Returns an empty list when all rows are exhausted.

Using Context Managers (with statement)

The informixdb library supports context managers, which is the recommended way to handle connections and cursors as they are automatically closed.

import informixdb
connection_string = 'INFORMIXDB_SERVER:ol_serveur;DATABASE=testdb;HOST=192.168.1.100;SERVICE=9088;USER=informix;PASSWORD=mysecretpassword'
try:
    with informixdb.connect(connection_string) as conn:
        with conn.cursor() as cursor:
            cursor.execute("SELECT customer_num, company FROM customer WHERE city = %s;", ('Paris',))
            # Iterate over the results row by row
            for row in cursor:
                print(f"Customer Num: {row[0]}, Company: {row[1]}")
except informixdb.Error as e:
    print(f"Database error: {e}")

Handling DATETIME and DATE Types

Informix has specific date/time types. informixdb handles them by converting them into Python's standard datetime objects.

import informixdb
from datetime import datetime
# ... connection setup ...
cursor.execute("SELECT order_date, order_date + 1 DAY FROM orders WHERE order_num = 100;")
row = cursor.fetchone()
if row:
    order_date, next_day = row
    print(f"Order Date: {order_date} (Type: {type(order_date)})")
    print(f"Next Day: {next_day} (Type: {type(next_day)})")
    # You can now use these datetime objects directly
    if isinstance(order_date, datetime):
        print(f"The year of the order is: {order_date.year}")

Troubleshooting

  • ImportError: No module named informixdb: The pip install failed. Re-run pip install informixdb.
  • informixdb.InterfaceError: Client library not found: This is the most common error. It means the Informix Client SDK is not installed or the LD_LIBRARY_PATH / PATH environment variables are not set correctly. Double-check that the SDK is installed and the variables point to the lib and bin directories, respectively.
  • informixdb.OperationalError: [Informix][Informix ODBC Driver][Server]Unable to connect to database server on host '...': This is a network or connection string issue.
    • Check the server name (INFORMIXDB_SERVER), hostname (HOST), and port (SERVICE).
    • Ensure the Informix server is running and accessible from your client machine.
    • Verify that the sqlhosts file on the client machine is correctly configured.
  • informixdb.ProgrammingError: (-201, 'A syntax error has occurred.': There is a mistake in your SQL query (e.g., a typo in a table or column name).

Important Considerations and Alternatives

  • informixdb is not actively maintained: The last release was several years ago. While it's stable for many use cases, it may not support the very latest Informix features or Python versions.

  • Alternative: pyodbc with Informix ODBC Driver: A more modern and often more robust alternative is to use the standard pyodbc library. This requires:

    1. Installing the Informix ODBC Driver (part of the Client SDK).
    2. Configating an ODBC Data Source Name (DSN) in your system's ODBC Administrator.
    3. Using a connection string like DSN=my_informix_dsn;UID=informix;PWD=password;.

    Example with pyodbc:

    import pyodbc
    conn_str = (
        "DRIVER={IBM INFORMIX ODBC DRIVER};"
        "DSN=my_informix_dsn;" # DSN name configured in ODBC Manager
        "DATABASE=testdb;"
        "HOST=192.168.1.100;"
        "SERVICE=9088;"
        "UID=informix;"
        "PWD=mysecretpassword"
    )
    conn = pyodbc.connect(conn_str)
    # ... rest of the code is similar to other DB-API libraries ...

For new projects, pyodbc is often recommended for its better long-term support and compatibility. However, informixdb remains a solid, lightweight choice if it meets your needs and you have it working correctly.

分享:
扫描分享到社交APP
上一篇
下一篇