选择正确的 DB2 驱动程序对于确保高效的数据访问和性能优化至关重要。以下是一些常见的 DB2 驱动程序及其适用场景:
适用场景:
优点:
示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DB2JDBCExample {
public static void main(String[] args) {
String url = "jdbc:db2://hostname:port/database";
String user = "username";
String password = "password";
try {
Class.forName("com.ibm.db2.jcc.DB2Driver");
Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM your_table");
while (rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
适用场景:
优点:
示例:
#include <sqlcli1.h>
#include <stdio.h>
int main() {
SQLHENV henv;
SQLHDBC hdbc;
SQLHSTMT hstmt;
SQLRETURN retcode;
SQLCHAR *dsn = (SQLCHAR *)"DSN_NAME";
SQLCHAR *user = (SQLCHAR *)"username";
SQLCHAR *password = (SQLCHAR *)"password";
SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (void *)SQL_OV_ODBC3, 0);
SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
SQLConnect(hdbc, dsn, SQL_NTS, user, SQL_NTS, password, SQL_NTS);
SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
SQLExecDirect(hstmt, (SQLCHAR *)"SELECT * FROM your_table", SQL_NTS);
SQLCHAR col1[256];
while (SQLFetch(hstmt) == SQL_SUCCESS) {
SQLGetData(hstmt, 1, SQL_C_CHAR, col1, sizeof(col1), NULL);
printf("%s\n", col1);
}
SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);
return 0;
}
适用场景:
优点:
示例:
using System;
using System.Data;
using IBM.Data.DB2;
class Program
{
static void Main()
{
string connectionString = "Server=hostname:port;Database=database;UID=username;PWD=password;";
using (DB2Connection conn = new DB2Connection(connectionString))
{
conn.Open();
using (DB2Command cmd = new DB2Command("SELECT * FROM your_table", conn))
{
using (DB2DataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
}
}
}
}
领取专属 10元无门槛券
手把手带您无忧上云