티스토리 뷰
SQLite DB on Raspberry Pi
SQLite는 경량의 디스크 기반 데이터베이스를 제공하는 내장 SQL 데이터베이스 엔진입니다. 별도의 서버 프로세스가 필요하지 않으며 SQL 쿼리 언어의 비표준 변형을 사용하여 데이터베이스에 액세스 할 수 있습니다.
SQLite는 IoT 디바이스에 적합합니다 (자체 포함, 서버리스, 구성 필요 없음). 이것의 위에, 어떤 목적을 위해 사용을 위해 자유롭다.
이제 라즈베리파이에 SQLite를 설치하고 사용하는 방법을 알아 보도록하겠습니다.
1. 업데이트 및 라즈베리 파이 패키지 업그레이드 :
업데이트 라스베리 파이 패키지 -
sudo apt-get update
라스베리 파이 패키지 업그레이드 -
sudo apt-get upgrade
2. SQLite 설치 :
다음 명령을 사용하여 SQLite3을 설치하십시오 -
sudo apt-get install sqlite3
이를 통해 SQLite를 Raspberry Pi에 설치하고 사용할 수 있습니다.
3. SQLite CLI 쉘로 실행 :
Create SQLite DB –
다음 명령을 사용하여 Raspbian CLI 인터페이스에서 SQLite DB를 생성 할 수 있습니다 -
sqlite3 <DB File Name>
pi@raspberrypi:~ $ sqlite3 my_DB
SQLite version 3.8.7.1 2014-10-29 13:59:56
Enter ".help" for usage hints.
sqlite>
Create Table –
다음 명령을 사용하여 DB 테이블을 생성 할 수 있습니다 -
CREATE TABLE <Table Name> (<Field 1 Name> <Data Type>, ........ <Field n Name> <Data Type>);
sqlite> create table sensors (sensor_ID integer, sensor_Name text);
sqlite>
Insert Data in Table –
다음 명령을 사용하여 테이블에 데이터를 삽입 할 수 있습니다.
INSERT INTO <Table Name> (<Field 1>, <Field 2>, ......... <Field n>) VALUES (<Value 1>, <Value 2>, .......... <Value n>);
sqlite> insert into sensors (sensor_ID, sensor_Name) values (1,"Light Sensor");
sqlite> insert into sensors (sensor_ID, sensor_Name) values (2,"Temperature");
sqlite>
Read Data from Table –
다음 쿼리를 사용하여 테이블 데이터를 나열 할 수 있습니다 -
SELECT * FROM <Table Name>;
sqlite> select * from sensors;
1|Light Sensor
2|Temperature
sqlite>
Delete Table –
DROP TABLE IF EXISTS <Table Name>;
sqlite> drop table if exists sensors;
sqlite>
SQLite CLI 쉘 종료 -
시스템의 End-Of-File 문자 (일반적으로 Control-D)를 입력하여 sqlite3 프로그램을 종료 할 수 있습니다.
SQLite 쉘은 ".exit"명령을 사용하여 종료 할 수도 있습니다 -
sqlite> sqlite> .quit pi@raspberrypi:~ $
4. 파이썬을 사용하여 SQLite DB 초기화 :
Python Script를 사용하여 SQLite DB를 초기화 할 수 있습니다. 이 방법은 DB 스키마를 자주 (초기 개발 단계에서) 변경해야하거나 여러 시스템에 동일한 DB를 작성하려는 경우 (코드 배포 또는 테스트 중에 예를 들어) 매우 유용 할 수 있습니다.
테이블 정의 및 기본 데이터로 SQL 파일 생성 -
다음은 SQL 파일의 예입니다. 이 파일을 Raspberry Pi에 "Table_Schema.sql"이라는 이름으로 저장하십시오.
drop table if exists StdSensorTypes;
create table StdSensorTypes (
SensorCode text,
SensorType text,
SensorImage text
);
INSERT INTO StdSensorTypes (SensorCode, SensorType) VALUES ("s0", "Temperature and Humidity Sensor: DHT22");
INSERT INTO StdSensorTypes (SensorCode, SensorType) VALUES ("s1", "Pressure Sensor: BMP180");
INSERT INTO StdSensorTypes (SensorCode, SensorType) VALUES ("s2", "Light Sensor: LDR");
INSERT INTO StdSensorTypes (SensorCode, SensorType) VALUES ("s3", "Door-Windows Sensor");
SQLite DB를 초기화하는 Python 스크립트 생성 -
SQL 파일이 준비되면 다음 코드로 Python 스크립트를 작성하십시오. 요구 사항에 따라이 스크립트에서 'DB_NAME'변수를 변경할 수 있습니다. 이 파일을 "DB_Ini.py"로 저장하십시오. 두 파일 ( "DB_Ini.py"및 "Table_Schema.sql")이 모두 Raspberry Pi의 동일한 디렉토리에 있는지 확인하십시오.
import sqlite3 ############### Settings #################### #DB Name DB_NAME = "My_DB" #SQL File with Table Schema and Initialization Data SQL_File_Name = "Table_Schema.sql" ############################################## #Read Table Schema into a Variable and remove all New Line Chars TableSchema="" with open(SQL_File_Name, 'r') as SchemaFile: TableSchema=SchemaFile.read().replace('\n') #Connect or Create DB File conn = sqlite3.connect(DB_NAME) curs = conn.cursor() #Create Tables sqlite3.complete_statement(TableSchema) curs.executescript(TableSchema) #Close DB curs.close() conn.close()
Python 스크립트 실행 -
테이블과 데이터로 SQLite DB를 만들고 초기화하려면 다음 명령을 사용하여 python 스크립트를 실행하기만 하면 됩니다.
python DB_Ini.py
DB 및 테이블 검증 -
다음은 Raspberry Pi의 콘솔 출력입니다. 스크립트 실행 및 DB / 테이블 확인 명령 포함 -
pi@raspberrypi:~/pradeep $ ls DB_Ini.py Table_Schema.sql pi@raspberrypi:~/pradeep $ python DB_Ini.py pi@raspberrypi:~/pradeep $ ls DB_Ini.py My_DB Table_Schema.sql pi@raspberrypi:~/pradeep $ sqlite3 My_DB SQLite version 3.8.7.1 2014-10-29 13:59:56 Enter ".help" for usage hints. sqlite> .tables StdSensorTypes sqlite> select * from StdSensorTypes; s0|Temperature and Humidity Sensor: DHT22| s1|Pressure Sensor: BMP180| s2|Light Sensor: LDR| s3|Door-Windows Sensor| sqlite> pi@raspberrypi:~/pradeep $