Sqlite study notes 7: Open the database using sqlite in C language, sqlite Study Notes

Source: Internet
Author: User

Sqlite study notes 7: Open the database using sqlite in C language, sqlite Study Notes

The basic content of the database has been mentioned earlier. Next, let's take a look at how to use sqlite in the C language.

Interface 1


sqlite3_open(const char *filename, sqlite3 **ppDb)

Open the database. If the database does not exist, create a new database and open




sqlite3_close(sqlite3*)

Shut down the database. If you close a statement that has not been executed, SQLITE_BUSY is returned.



Example 2

1. directory structure

Projects {

Main. c // file where the code is located

Sqlite {// directory of the decompressed sqlite package downloaded from the official website

Shell. c // This file is not actually used in the project. This file is used to generate the sqlite command tool. For details, refer to: sqlite study note 1.

Sqlite3.c

Sqlite3.h

Sqlite3ext. h

}

}


2 source code


// main.c
#include <stdio.h>
#include <stdlib.h>
#include "sqlite/sqlite3.h"

#define DB_NAME "hanfeng.db"

int main()
{
    sqlite3* db = NULL ;
    char* msg = NULL ;
    int ret = 0 ;
    
    ret = sqlite3_open(DB_NAME, &db);
    if (ret){
        fprintf(stderr, "error open datebase:%s\n.", DB_NAME) ;
        exit(0) ;
    }
    else{
        fprintf(stdout, "successfully open datebase.\n") ;
    }
    sqlite3_close(db) ;
    return 0;
}


For future extension convenience, the code is modified as follows:


#include <stdio.h>
#include <stdlib.h>
#include "sqlite/sqlite3.h"
#define DB_NANE "sqlite/test.db"
sqlite3 *db = NULL;
char* sql = NULL;
char *zErrMsg = NULL;
int ret = 0;
typedef enum{
    false,
    true
} bool;
static int callback(void *NotUsed, int argc, char **argv, char **azColName)
{
    int i = 0;
    for(i=0; i < argc; i++){
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
}
bool connectDB()
{
    ret = sqlite3_open(DB_NANE, &db);
    if( ret != SQLITE_OK){
        fprintf(stderr, "Error open database: %s\n", sqlite3_errmsg(db));
        sqlite3_free(zErrMsg);
        return false;
    }
    fprintf(stdout, "Successfully opened database\n");
    return true;
}
bool closeDB()
{
    int ret = 0;
    ret = sqlite3_close(db);
    if ( ret == SQLITE_BUSY ){
        return false;
    }
    return true;
}
int main(int argc, char* argv[])
{
    connectDB();
    closeDB();
    return 0;
}




3 compile and run


There are two ways to run the command. Based on the preceding notes, we didn't configure the sqlite environment. We just downloaded and decompressed the file to get a folder named sqlite. Therefore, we need to use the following command:


gcc -o main main.c ./sqlite/sqlite3.c -lpthread -ldl

If sqlite is installed in the download configuration, you need to change the header file:



#include <sqlite3.h>

Then run the following command:



gcc -o main main.c  -lsqlite3



After the command is executed, an executable file named main is generated. Enter:


./main

You can see the result.



# If g ++ is used during compilation, the following error occurs: error: invalid conversion from 'const void * 'to 'const char *'

G ++ seems to have stricter requirements on type conversion and does not support such conversion.

If you know how to compile with g ++, please advise ......


Build an sqlite database in C Language

). Open VC and create a "Win32 Dynamic-Link Library" project named sqlite32 ). in the following dialog box, select "An empty DLL project", click FINISH-> OK3 ). set all *. c *. h *. def copy to the project folder 4 ). in the Source File of the project, add all the SQLite Source files you downloaded *. c file. Do not add shell here. c and tclsqlite. c. 5 ). add the sqlite3.def File in the SQLite Source File to the Source File of the Project. 6 ). add all the files in the SQLite source File you downloaded to the Header File *. h file, 7 ). start compiling. Build (F7) may encounter an error here: e: \ zieckey \ sqlite \ sqlite3 \ sqlite3ext. h (22): fatal error C1083: Cannot open include file: 'sqlite3. h': No such file or directory check found that the source code contains sqlite3.h is included in the # include <sqlite3.h> method, which means the compiler searches in the default system path, in this case, the header file sqlite3.h cannot be found. You can change it to # include "sqlite3.h" to allow the compiler to search in the project path, but if there are other This method is also included in the # include <sqlite3.h> method, so it is a little troublesome to change the source code. Well, we can choose Tools> Options in the menu bar... -> Directeries: enter your sqlite3.h path in the Directeries option below. Here is your project directory. after adding the file, compile the file. Finally, we generated the following two important files in the Debug directory of the project directory: Dynamic Link Library File sqlite3.dll and import library file sqlite3.lib. using the dynamic link library, let's write a program to test our dynamic link library. create an empty "Win32 Console Application" Win32 Console program under VC, name the project TestSqliteOnWindows, and create a new test. the source code of the C ++ language of cpp is as follows: // name: test. cpp // This prog is u Sed to test C/C ++ API for sqlite3. It is very simple, ha! // Author: zieckey // data: 2006/11/28 # include <stdio. h> # include <stdlib. h> # include "sqlite3.h" # define _ DEBUG_int main (void) {sqlite3 * db = NULL; char * zErrMsg = 0; int rc; rc = sqlite3_open ("zieckey. db ", & db); // open the specified database file. if not, a database file with the same name will be created if (rc) {fprintf (stderr, & q ...... remaining full text>

SQLITE database C language API to make sqlite3_open do not create a database when the database does not exist

Use the sqlite3_open_v2 function.
Int sqlite3_open_v2 (const char * filename, sqlite3 ** ppDb, int flags, const char * zVfs );
Like sqllite3_open, flags is set to SQLITE_OPEN_READWRITE. If the database does not exist, only one error is returned.
The zVfs parameter allows an application to name a Virtual File System module to connect to a database. VFS is an abstraction layer between SQlite library and underlying storage systems (such as a file system). Generally, a customer application can simply pass a NULL pointer to this parameter, to use the default VFS module.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.