C# SQLite(데이터베이스)

이진호·2023년 12월 11일

C#... 그리고 Unity

목록 보기
10/15

기본 선언

  • table명과 DataBase파일명은 string으로 지정해준다.

  • 사용되는 클래스
    - IDbcommand, IDataReader

//아래의 예시는 엑셀의 .csv 확장자로 작성한 기준.

//데이터베이스 파일명 선언 & 초기화
string dbname = "TEST.db";
//파일의 주소를 지정
string strConnection = "URI=file:" + Application.streamingAssetsPath + "/" + dbname;
//데이터베이스 인스턴스 생성 & 초기화
IDbConnection dbConnection = new SqliteConnection(strConnection);
//데이터베이스 연결
dbConnection.Open();
//테이블명 선언 & 초기화
string tablename = "test"; 

//IDbcommand 인스턴트 생성 후 SQL쿼리 초기화
IDbCommand dbcommand = dbConnection.CreateCommand(); 
dbcommand.CommandText = "select *from "+tablename;
// IDatReader를 반환하는 ExecuteReader으로 dbcommand를 선언
IDataReader dataReader = dbcommand.ExecuteReader();

//반복문으로 test이름의 테이블에 있는 값을 디버그로 반환 하도록함.
while (dataReader.Read())
{
    int id = dataReader.GetInt32(0);
    string name = dataReader.GetString(1);
    int age = dataReader.GetInt32(2);

    Debug.Log(string.Format("id :{0}, name : {1}, age : {2}", id, name, age));
}
//새롭게 저장시킬 데이터 생성
int id = 3;
string wname = "unity";
int wage = 20;

//새로운 데이터를 저장시킬 SQL쿼리 생성 & 초기화
string insertQuery = $"insert into test(id,name, age) values('{id}','{wname}','{wage}')";

//IDbCommand의 인스턴스를 CreateCommand 메소드로 생성
IDbCommand dbcommand = dbConnection.CreateCommand();
//CommandText메소드로 insertQuery을 SQL쿼리 설정
dbcommand.CommandText = insertQuery;
//SQL쿼리 실행
dbcommand.ExecuteNonQuery();
//데이터베이스 연결 해제와 관련된 리소스 정리
dbConnection.Dispose();
//@"create table" = 새로운 테이블 생성 
//if notexists = 동일한 이름의 테이블이 존재할 경우는 생성시키지 않는 구문
//newtest = 새로생성시킬 테이블의 이름
//id, name, score는 새로 생성시킬 열의 이름과 타입
//첫번째 줄의 primary key = 기본키 선언 (현재는 id integer) 
//autoincrement = 기본 키 열을 한개씩 증가 시키는 옵션
string createblequery = @"create table if not exists newtest(
                                                              id integer primary key autoincrement,
                                                              name not null,
                                                              score integer)";
// 인스턴스 생성 & 초기화
IDbCommand dbcommand = dbConnection.CreateCommand();
dbcommand.CommandText = createblequery;
// SQL쿼리 실행(여기서는 dbcommand)
dbcommand.ExecuteNonQuery();
profile
콜라 없는 내 인생은 김빠진 콜라

0개의 댓글