当前位置:首页 > 行业动态 > 正文

c 访问不同的数据库

C语言访问不同数据库通常需要使用对应的数据库驱动和API,如MySQL的libmysqlclient等。

C 语言访问不同数据库的详细指南

在C语言中,访问不同的数据库通常需要使用特定的库或API,这些库提供了与数据库进行交互的功能,包括连接、查询、插入、更新和删除数据等操作,以下是一些常见的数据库及其在C语言中的访问方法:

MySQL

MySQL 是一个广泛使用的开源关系型数据库管理系统,要在C语言中访问MySQL数据库,可以使用MySQL Connector/C

安装 MySQL Connector/C:

下载并安装 MySQL Connector/C。

包含头文件和链接库文件。

示例代码:

 #include <mysql/mysql.h>
  #include <stdio.h>
  #include <stdlib.h>
  int main() {
      MYSQL *conn;
      MYSQL_RES *res;
      MYSQL_ROW row;
      const char *server = "localhost";
      const char *user = "root";
      const char *password = "your_password"; /* set me first */
      const char *database = "testdb";
      conn = mysql_init(NULL);
      // Connect to database
      if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
          fprintf(stderr, "%s
", mysql_error(conn));
          exit(1);
      }
      // Send SQL query
      if (mysql_query(conn, "SELECT * FROM your_table")) {
          fprintf(stderr, "%s
", mysql_error(conn));
          exit(1);
      }
      res = mysql_use_result(conn);
      // Output result set
      while ((row = mysql_fetch_row(res)) != NULL) {
          printf("%s %s
", row[0], row[1]);
      }
      // Clean up
      mysql_free_result(res);
      mysql_close(conn);
      return 0;
  }

PostgreSQL

PostgreSQL 是一个强大的开源对象关系型数据库系统,要在C语言中访问PostgreSQL数据库,可以使用libpq 库。

安装 libpq:

下载并安装 PostgreSQL 开发库。

包含头文件和链接库文件。

示例代码:

 #include <stdio.h>
  #include <stdlib.h>
  #include <libpq-fe.h>
  int main() {
      PGconn *conn;
      PGresult *res;
      const char *conninfo = "host=localhost dbname=testdb user=postgres password=your_password";
      conn = PQconnectdb(conninfo);
      // Check to see that the backend connection was successfully made
      if (PQstatus(conn) == CONNECTION_BAD) {
          fprintf(stderr, "Connection to database failed: %s", PQerrorMessage(conn));
          PQfinish(conn);
          exit(1);
      }
      // Execute SQL query
      res = PQexec(conn, "SELECT * FROM your_table");
      if (PQresultStatus(res) != PGRES_TUPLES_OK) {
          fprintf(stderr, "Query failed: %s", PQerrorMessage(conn));
          PQclear(res);
          PQfinish(conn);
          exit(1);
      }
      // Process and print query results
      while (PQgetisnull(res, 0, 0) == 0) {
          printf("%st%s
", PQgetvalue(res, 0, 0), PQgetvalue(res, 0, 1));
          PQclear(res);
      }
      // Close connection to the database
      PQfinish(conn);
      return 0;
  }

SQLite

SQLite 是一个轻量级的嵌入式关系型数据库,要在C语言中访问SQLite数据库,可以使用SQLite3 库。

安装 SQLite3:

下载并安装 SQLite3 开发库。

包含头文件和链接库文件。

示例代码:

 #include <sqlite3.h>
  #include <stdio.h>
  #include <stdlib.h>
  int callback(void *NotUsed, int argc, charargv, charazColName) {
      int i;
      for (i = 0; i < argc; i++) {
          printf("%s = %s
", azColName[i], argv[i] ? argv[i] : "NULL");
      }
      printf("
");
      return 0;
  }
  int main() {
      sqlite3 *db;
      char *zErrMsg = 0;
      int rc;
      const char *sql;
      // Open database
      rc = sqlite3_open("test.db", &db);
      if (rc) {
          fprintf(stderr, "Can't open database: %s
", sqlite3_errmsg(db));
          exit(0);
      } else {
          fprintf(stderr, "Opened database successfully
");
      }
      // Create SQL statement
      sql = "CREATE TABLE YOUR_TABLE(" 
            "ID INT PRIMARY KEY     NOT NULL," 
            "NAME           TEXT    NOT NULL," 
            "AGE            INT     NOT NULL);";
      // Execute SQL statement
      rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg);
      if (rc != SQLITE_OK) {
          fprintf(stderr, "SQL error: %s
", zErrMsg);
          sqlite3_free(zErrMsg);
      } else {
          fprintf(stdout, "Table created successfully
");
      }
      // Close database
      sqlite3_close(db);
      return 0;
  }

Oracle

Oracle 数据库是企业级的关系型数据库管理系统,要在C语言中访问Oracle数据库,可以使用OCI(Oracle Call Interface)

安装 OCI:

下载并安装 Oracle Instant Client。

包含头文件和链接库文件。

示例代码:

 #include <stdio.h>
  #include <oci.h>
  int main() {
      OCIEnv *envhp;
      OCIError *errhp;
      OCISvcCtx *svchp;
      OCIStmt *stmthp;
      OCIDefine *defnp;
      OCIBind *bindpp;
      sb4 id;
      text name[30];
      ub2 age;
      // Allocate environment handle and initialize it
      OCIHandleAlloc(NULL, (dvoid *)&envhp, OCI_HTYPE_ENV, 0, NULL);
      OCIEnvInit(&envhp, OCI_DEFAULT, 0, NULL);
      // Allocate error handle and attach it to the environment handle
      OCIHandleAlloc(envhp, (dvoid *)&errhp, OCI_HTYPE_ERROR, 0, NULL);
      OCIAttrSet(envhp, OCI_HTYPE_ENV, &errhp, 0);
      // Allocate service context handle and establish a connection to the database
      OCIHandleAlloc(envhp, (dvoid *)&svchp, OCI_HTYPE_SVCCTX, 0, NULL);
      OCIServerAttach(svchp, errhp, NULL, 0, NULL, 0, 0, NULL);
      OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, &errhp, 0);
      OCIHandleAlloc(envhp, (dvoid *)&stmthp, OCI_HTYPE_STMT, 0, NULL);
      OCIStmtPrepare(svchp, stmthp, errhp, (text *)"SELECT ID, NAME, AGE FROM YOUR_TABLE", strlen((text *)"SELECT ID, NAME, AGE FROM YOUR_TABLE"), OCI_NTV_SYNTAX, OCI_DEFAULT);
      OCIStmtExecute(svchp, stmthp, errhp, 0, 0, NULL, NULL, OCI_DEFAULT);
      OCIDefineByPos(stmthp, &defnp, errhp, 1, &id, sizeof(id), SQLT_INT, NULL, NULL, NULL, OCI_DEFAULT);
      OCIDefineByPos(stmthp, &defnp, errhp, 2, name, sizeof(name), SQLT_STR, NULL, NULL, NULL, OCI_DEFAULT);
      OCIDefineByPos(stmthp, &defnp, errhp, 3, &age, sizeof(age), SQLT_INT, NULL, NULL, NULL, OCI_DEFAULT);
      while (OCIStmtFetch(stmthp, errhp, 1) == OCI_SUCCESS) {
        printf("ID: %d, Name: %s, Age: %d
", id, name, age);
    }
    OCIStmtRelease(stmthp, errhp);
    OCITransRollback(svchp, errhp);
    OCIServerDetach(svchp, errhp, NULL, 0, NULL);
    OCIHandleFree(svchp, OCI_HTYPE_SVCCTX);
    OCIHandleFree(errhp, OCI_HTYPE_ERROR);
    OCIHandleFree(envhp, OCI_HTYPE_ENV);
    return 0;
  }

SQL Server

Microsoft SQL Server 是一个关系型数据库管理系统,要在C语言中访问SQL Server数据库,可以使用ODBC(Open Database Connectivity)

安装 ODBC:

下载并安装 Microsoft ODBC Driver for SQL Server。

配置数据源名称(DSN)。

示例代码:

 #include <stdio.h>
  #include <windows.h>
  #include <sql.h>
  #include <sqlext.h>
  int main() {
      SQLHENV env; /* environment handle */
      SQLHDBC dbc; /* connection handle */
      SQLHSTMT stmt; /* statement handle */
      SQLRETURN ret; /* return code */
      SQLCHAR outstr[1024]; /* output string */
      SQLINTEGER outlen; /* length of output string */
      SQLSMALLINT colnum; /* column number */
      SQLLEN ind; /* indicator */
      SQLCHAR instr[] = "SELECT * FROM your_table"; /* input string */
      SQLLEN inlen = strlen((char*)instr); /* length of input string */
      SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env); /* allocate environment handle */
      SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); /* set version environment attribute */
      SQLAllocHandle(SQL_HANDLE_DBC, env, &dbc); /* allocate connection handle */
      SQLConnect(dbc, (SQLCHAR*)"DSN=yourDSN;UID=yourUsername;PWD=yourPassword;", SQL_NTS, outstr, sizeof(outstr), &outlen, &ind); /* connect to data source */
      if (ind != SQL_SUCCESS) { /* check for successful connection */
          printf("Error connecting to data source
");
          return -1;
      } else {
          printf("Successfully connected to data source
");
      }
      SQLAllocHandle(SQL_HANDLE_STMT, dbc, &stmt); /* allocate statement handle */
      SQLExecDirect(stmt, instr, inlen); /* execute SQL query */
      while (SQLFetch(stmt) == SQL_SUCCESS) { /* fetch each row */
          colnum = 1; /* reset column number */
          while (SQLGetData(stmt, colnum++, SQL_C_CHAR, outstr, sizeof(outstr), NULL) == SQL_SUCCESS) { /* get data */
              printf("%st", outstr); /* print data */
          }
          printf("
"); /* end row */
      }
      SQLDisconnect(dbc); /* disconnect from data source */
      SQLFreeHandle(SQL_HANDLE_STMT, stmt); /* free statement handle */
      SQLFreeHandle(SQL_HANDLE_DBC, dbc); /* free connection handle */
      SQLFreeHandle(SQL_HANDLE_ENV, env); /* free environment handle */
      return 0;
  }

FAQs:

Q1: 如何在C语言中使用MySQL Connector/C连接到MySQL数据库?

A1: 确保已安装MySQL Connector/C库,通过mysql_init初始化连接句柄,使用mysql_real_connect函数建立与数据库的连接,可以使用mysql_query执行SQL语句,并通过mysql_store_result获取结果集,不要忘记使用mysql_free_result释放结果集,并使用mysql_close关闭连接。

MYSQL *conn;
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, "localhost", "username", "password", "database", 0, NULL, 0)) {
    fprintf(stderr, "%s
", mysql_error(conn));
    exit(1);}

Q2: 如何在C语言中使用libpq连接到PostgreSQL数据库?

A2: 确保已安装libpq库,使用PQconnectdb函数建立与数据库的连接,如果连接成功,可以通过PQexec执行SQL命令,并通过PQgetvalue获取查询结果,记得使用PQfinish关闭连接。

#include <libpq-fe.h>PGconn *conn;conn = PQconnectdb("host=localhost dbname=testdb user=postgres password=your_password");if (PQstatus(conn) == CONNECTION_BAD) {fprintf(stderr, "Connection to database failed: %s
", PQerrorMessage(conn));PQfinish(conn);exit(1);}else {fprintf(stderr, "Connected to database successfully
");}```
0