Sqlite3: Difference between revisions
Line 78: | Line 78: | ||
CREATE TABLE test(seq integer PRIMARY KEY AUTOINCREMENT, test text); | CREATE TABLE test(seq integer PRIMARY KEY AUTOINCREMENT, test text); | ||
CREATE TABLE sample1(seq integer); | CREATE TABLE sample1(seq integer); | ||
</pre> | |||
=== .headers === | |||
결과를 표시할 때, 헤더 정보를 표시할지 말지를 설정한다. | |||
<pre> | |||
sqlite> .headers on | |||
sqlite> select * from test; | |||
seq|uniq_id | |||
3926|ec1d7c92-83b0-4410-a6f4-897fc1522485 | |||
</pre> | </pre> | ||
Revision as of 09:50, 23 June 2016
Overview
Sqlite3 사용법 정리.
Commands
원문은 이곳<ref>https://www.sqlite.org/cli.html</ref>을 참조하자.
sqlite> .help .backup ?DB? FILE Backup DB (default "main") to FILE .bail ON|OFF Stop after hitting an error. Default OFF .databases List names and files of attached databases .dump ?TABLE? ... Dump the database in an SQL text format If TABLE specified, only dump tables matching LIKE pattern TABLE. .echo ON|OFF Turn command echo on or off .exit Exit this program .explain ?ON|OFF? Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on. .header(s) ON|OFF Turn display of headers on or off .help Show this message .import FILE TABLE Import data from FILE into TABLE .indices ?TABLE? Show names of all indices If TABLE specified, only show indices for tables matching LIKE pattern TABLE. .load FILE ?ENTRY? Load an extension library .log FILE|off Turn logging on or off. FILE can be stderr/stdout .mode MODE ?TABLE? Set output mode where MODE is one of: csv Comma-separated values column Left-aligned columns. (See .width) html HTML <table> code insert SQL insert statements for TABLE line One value per line list Values delimited by .separator string tabs Tab-separated values tcl TCL list elements .nullvalue STRING Use STRING in place of NULL values .open ?FILENAME? Close existing database and reopen FILENAME .output FILENAME Send output to FILENAME .output stdout Send output to the screen .print STRING... Print literal STRING .prompt MAIN CONTINUE Replace the standard prompts .quit Exit this program .read FILENAME Execute SQL in FILENAME .restore ?DB? FILE Restore content of DB (default "main") from FILE .schema ?TABLE? Show the CREATE statements If TABLE specified, only show tables matching LIKE pattern TABLE. .separator STRING Change separator used by output mode and .import .show Show the current values for various settings .stats ON|OFF Turn stats on or off .tables ?TABLE? List names of tables If TABLE specified, only list tables matching LIKE pattern TABLE. .timeout MS Try opening locked tables for MS milliseconds .trace FILE|off Output each SQL statement as it is run .vfsname ?AUX? Print the name of the VFS stack .width NUM1 NUM2 ... Set column widths for "column" mode .timer ON|OFF Turn the CPU timer measurement on or off
.tables
현재의 데이터베이스에 있는 테이블 내용을 보여준다. 특정 테이블 이름을 같이 입력할 경우, 입력한 테이블이 데이터베이스에 존재하는지를 리턴한다.
sqlite> .tables sample1 test sqlite> .tables test test sqlite> .tables test1 sqlite>
.schema
입력한 테이블의 상세 내용을 확인한다. 만약, 입력한 테이블 내용이 없을 경우, 해당 데이터베이스의 전체 테이블의 상세 내용을 출력한다.
sqlite> .schema test CREATE TABLE test(seq integer PRIMARY KEY AUTOINCREMENT, test text); sqlite> .schema CREATE TABLE test(seq integer PRIMARY KEY AUTOINCREMENT, test text); CREATE TABLE sample1(seq integer);
.headers
결과를 표시할 때, 헤더 정보를 표시할지 말지를 설정한다.
sqlite> .headers on sqlite> select * from test; seq|uniq_id 3926|ec1d7c92-83b0-4410-a6f4-897fc1522485
Datatypes
Strong classes and datatypes
Sqlite 에서는 크게 다음과 같은 분류로 데이터타입을 정의한다.
NULL. The value is a NULL value. INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value. REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number. TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE). BLOB. The value is a blob of data, stored exactly as it was input.
Boolean Datatype
SQLite 에는 Boolean 타입을 위한 데이터 타입이 없다. 대신, integer 0(false), integer 1(true) 로 저장된다.
Date and Time Datatype
SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:
TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar. INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.
Pragma
table_info()
입력된 table 의 정보를 출력한다. 각각의 라인마다 테이블에 있는 모든 칼럼과 속성을 하나씩 출력한다. table 뿐만 아니라 view 정보도 확인할 수 있다. 각각의 항목별 내용은 아래 순서와 같다.
- Index
- Column name
- Data type
- Set NULL 가능 여부.(0:가능, 1:불가능)
- Default value
- Primary key 여부
sqlite> pragma table_info(test); 0|seq|integer|0||1 1|uniq_id|text|1||0
Attach
다른 데이터베이스 내용을 참조하고자 할 때 사용한다.
> attach /tmp/sqlite3/tmp.db as test;
Example
Database 생성 후, 샘플 데이터를 입력한 뒤, 이를 프로그램을 통해 출력하는 예제를 작성해보자.
Create 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
Sample programs
<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. * * */
- include <stdio.h>
- 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
See also
- https://www.sqlite.org/datatype3.html - Datatypes In SQLite Version 3
- https://www.sqlite.org/pragma.html - PRAGMA Statements
References
<references />