Hi all,

I'm a newbie in C..Right now, I have to write a code to read a text file and then insert all the info inside that text file into database. Should anyone have a simple sample of it, maybe you can share with me in order for me to learn on how to do it.

Thanks in advance

Dani AI

Generated

Since confirmed this is C (and flagged the C vs C# distinction), the practical approach is: read the file line-by-line with stdio, parse each line into fields, and use the target database's C API. For a simple assignment and quick setup, SQLite is convenient because it has a small C API and no separate server. Below is a compact example that reads a CSV-like file and inserts rows into an SQLite table using a prepared statement and a transaction.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>

int main(int argc, char *argv[]) {
    if (argc < 2) { fprintf(stderr, "Usage: %s datafile.csv\n", argv[0]); return 1; }
    FILE *fp = fopen(argv[1], "r");
    if (!fp) { perror("fopen"); return 1; }

    sqlite3 *db;
    if (sqlite3_open("import.db", &db) != SQLITE_OK) { fprintf(stderr, "db open error\n"); fclose(fp); return 1; }

    sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS people (name TEXT, age INTEGER, email TEXT);", 0,0,0);
    sqlite3_exec(db, "BEGIN TRANSACTION;", 0,0,0);

    sqlite3_stmt *stmt;
    sqlite3_prepare_v2(db, "INSERT INTO people (name, age, email) VALUES (?, ?, ?);", -1, &stmt, 0);

    char line[4096];
    while (fgets(line, sizeof(line), fp)) {
        size_t len = strlen(line);
        while (len && (line[len-1]=='\n' || line[len-1]=='\r')) line[--len]=0;
        if (!len) continue;
        char *name = strtok(line, ",");
        char *age_s = strtok(NULL, ",");
        char *email = strtok(NULL, ",");
        if (!name || !age_s) continue;
        sqlite3_bind_text(stmt, 1, name, -1, SQLITE_TRANSIENT);
        sqlite3_bind_int(stmt, 2, atoi(age_s));
        if (email) sqlite3_bind_text(stmt, 3, email, -1, SQLITE_TRANSIENT); else sqlite3_bind_null(stmt, 3);
        if (sqlite3_step(stmt) != SQLITE_DONE) fprintf(stderr, "insert failed: %s\n", sqlite3_errmsg(db));
        sqlite3_reset(stmt);
        sqlite3_clear_bindings(stmt);
    }

    sqlite3_finalize(stmt);
    sqlite3_exec(db, "COMMIT;", 0,0,0);
    sqlite3_close(db);
    fclose(fp);
    return 0;
}

Notes and troubleshooting: compile with gcc -o import import.c -lsqlite3. Use prepared statements (shown) to avoid SQL injection and to improve performance. Wrap inserts in a transaction — it speeds bulk import by orders of magnitude. Handle CR/LF trimming (Windows files). This example assumes simple comma-separated fields without quoted commas; for full CSV support use a CSV parser. If the target DB is MySQL or MS SQL, use their C client libraries or ODBC instead and follow a similar pattern: open connection, prepare statement, bind, step, commit. Common errors: linker complaints mean -lsqlite3 (or the appropriate client lib) is missing; file-not-found means check path/permissions; parsing errors appear when fields contain commas or newlines.

Recommended Answers

All 3 Replies

First of all declare some library as:
Using System.IO;

So that you have acces to files, than write something like:
StreamReader sr = new StreamReader(@"yourpathandfilewithextension)";
string containsoffile = sr.ReadToEnd();
sr.Close();

So now you have all the file into string declared above. Regarding the database is more to it. Try to figure out first of all to which type of database you want to register data (ms sql, mysql, oracle, access etc), than regarding this find appropriate provider, mysqlclient, oracleclient, sqlclient or for both oracle and ms sql you could use oledbclient.

Quick question:

Are you wanting C# or C? C is not the same language as C#.

Hi alc6379,

I'll be using C for this assignment

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.