Sqlite3: Difference between revisions

From 탱이의 잡동사니
Jump to navigation Jump to search
No edit summary
No edit summary
Line 125: Line 125:


[[category:linux]]
[[category:linux]]
[[category:database]]

Revision as of 08:48, 28 January 2015

Overview

사용 예

데이터베이스 자체로써

Example

Database 생성 후, 샘플 데이터를 입력한 뒤, 이를 프로그램을 통해 출력하는 예제를 작성해보자.

database 생성

$ sqlite3 test.db
sqlite> create table t1(
   ...> id int 
   ...> id int primary key not null,
   ...> name text not null,
   ...> age int not null,
   ...> address char(50),
   ...> salary real
   ...> );
sqlite> .table
t1

sqlite> .schema t1
CREATE TABLE t1(
id int primary key not null,
name text not null,
age int not null,
address char(50),
salary real
);

sqlite> insert into t1 (id, name, age, address, salary) values (1, "test_1", 10, "Somewhere in the earth", 10000);
sqlite> select * from t1;
1|test_1|10|Somewhere in the earth|10000.0

샘플 프로그램

<source lang=c> /*

* main.c
* 
* Copyright 2015 sungtae kim <pchero@mywork>
* 
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* 
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* 
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
* 
* 
*/


  1. include <stdio.h>
  2. include <sqlite3.h>

static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i < argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); }

printf("\n"); return 0; }


int main(int argc, char **argv) { sqlite3 *db; char *zErrMsg = 0; int rc;

if(argc != 3) { fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]); return 1; } rc = sqlite3_open(argv[1], &db); if(rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return(1); }

rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg); if(rc != SQLITE_OK) { fprintf(stderr, "SQL_error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db); return 0; } </source>

$ gcc -o main main.c -lsqlite3

$ ./main test.db "select * from t1"
id = 1
name = test_1
age = 10
address = Somewhere in the earth
salary = 10000.0

References

<references />