Application of C Language in Database Programming and Interface Usage

Application of C Language in Database Programming and Interface Usage

The C language is a powerful programming language widely used in system programming, embedded development, and database programming. In this article, we will explore how to interact with databases using C, primarily focusing on the SQLite database. SQLite is a lightweight relational database that is very suitable for small projects and learning.

1. Environment Preparation

Before we begin, please ensure that the following software is installed on your computer:

  1. C Compiler: such as GCC.
  2. SQLite3: can be downloaded and installed from the SQLite official website.

Installing SQLite3

On Linux systems, you can install it via the package manager:

sudo apt-get install sqlite3 libsqlite3-dev

On Windows systems, you can download the precompiled binaries and add them to your system path.

2. Basic Concepts

Database Connection

To interact with a database, you first need to establish a connection. We will use the <span>sqlite3_open</span> function to open or create an SQLite database file.

SQL Operations

Common SQL operations include:

  • Creating tables (CREATE TABLE)
  • Inserting data (INSERT INTO)
  • Querying data (SELECT)
  • Updating data (UPDATE)
  • Deleting data (DELETE)

3. Code Example

Below is a simple example program that demonstrates how to operate an SQLite database using C, including creating tables, inserting records, and querying records.

Example Code

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h>
// Callback function to handle query results
static int callback(void *data, int argc, char **argv, char **azColName) {
    for (int i = 0; i < argc; i++) {
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
}

int main() {
    sqlite3 *db;
    char *errMsg = 0;
    // Open or create database
    if (sqlite3_open("test.db", &db)) {
        fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
        return EXIT_FAILURE;
    }
    // Create table
    const char *sqlCreateTable = "CREATE TABLE IF NOT EXISTS Users(Id INT PRIMARY KEY NOT NULL, Name TEXT NOT NULL);";
    if (sqlite3_exec(db, sqlCreateTable, 0, 0, &errMsg) != SQLITE_OK) {
        fprintf(stderr, "SQL error: %s\n", errMsg);
        sqlite3_free(errMsg);
        return EXIT_FAILURE;
    }
    // Insert data
    const char *sqlInsert = "INSERT INTO Users (Id, Name) VALUES (1, 'Alice'), (2, 'Bob');";
    if (sqlite3_exec(db, sqlInsert, 0, 0, &errMsg) != SQLITE_OK) {
        fprintf(stderr,"SQL error: %s\n", errMsg);
        sqlite3_free(errMsg);
        return EXIT_FAILURE;
    }
    // Query data
    const char *sqlSelect = "SELECT * FROM Users;";
    if (sqlite3_exec(db, sqlSelect , callback , 0 , &errMsg) != SQLITE_OK ) {
        fprintf(stderr,"SQL error: %s\n", errMsg);
        sqlite3_free(errMsg);
        return EXIT_FAILURE;
    }
    // Close database connection
    sqlite3_close(db);
    return EXIT_SUCCESS;
}

4. Code Analysis

  1. Including Header Files: We include <span>stdio.h</span>, <span>stdlib.h</span>, and <span>sqlite3.h</span>. Among them, <span>stdio.h</span> is used for input and output operations, <span>stdlib.h</span> provides some general utility functions, while <span>sqlite3.h</span> is the core header file for SQLite.

  2. Callback Function: A callback function <span>callback()</span> is defined to handle query results. When executing a SELECT query, this function will be called, and each row of results will be passed to it.

static int callback(void *data,int argc,char **argv,char **azColName)

Parameter Explanation:

  • <span>data</span>: User-defined data, which is not used here.
  • <span>argc</span>: The number of columns in the current row.
  • <span>argv</span>: Stores the data for each column in the current row.
  • <span>azColName</span>: Stores information about the names of each column.
  1. Opening/Creating Database: The <span>sqlite3_open()</span> function is called to open or create a database named <span>"test.db"</span>. If it fails, an error message is printed and the program exits.

  2. Executing SQL Commands:

  • Using <span>CREATE TABLE IF NOT EXISTS ...</span> to create a user table, which will not be recreated if it already exists.
  • Using the INSERT command to insert two records into the user table.
  • Querying and Displaying Results: The SELECT command is used to retrieve all user information, and the callback function is used to output the results row by row.

  • Closing Connection: Finally, the <span>sqlite3_close()</span> function is called to close the connection to the database and free resources.

  • 5. Conclusion

    This article introduced how to use the C language to interact with the SQLite database, including establishing connections, executing SQL commands, and handling query results. This is just a simple example; in practical applications, you may need to consider more complex situations, such as transaction management and security. However, I hope this basic tutorial helps you take the first step and gain a deeper understanding of the interaction between C and databases.

    Leave a Comment