2011/10/14

C#에서 SQLite 사용하기

C#에 대해서 잘 알지는 못하고 요즘 조금 관심을 두고 있는데 C#의 데이터베이스 관련하여 모르는 상태에서 SQLite 의 예제와 관련 정보를 찾아 SQLite를 연결하여 테스트 해 보았다.



우선 C#에서 SQLite를 사용하려면 아래 사이트를 통해 개발 환경에 맞는 파일을 다운 받아야 한다.

System.Data.SQLite Download Page 



내려받은 파일들 중 System.Data.SQLite.dll 와 System.Data.SQLite.Linq.dll 을 Add Reference... 를 통해 추가한다. 테스트에 사용한 코드는 아래와 같다.

string strQuery;

textResult.Text = "Begin...\n";

SQLiteConnectionStringBuilder SQLiteConString
= new SQLiteConnectionStringBuilder();
SQLiteConString.DataSource = "test.db";

SQLiteConnection SQLite3Con
= new SQLiteConnection(SQLiteConString.ToString());
SQLite3Con.Open();

bool bPrevStepSuccess = false;

textResult.AppendText(" Try to connect with test.db ...");
if (SQLite3Con.State == ConnectionState.Open)
{
textResult.AppendText("OK\n");

// 테이블 생성
strQuery = "CREATE TABLE IF NOT EXISTS TestTable ("
+ " name VARCHAR(20)"
+ " ,age int"
+ " ,country VARCHAR(20)"
+ ")";

SQLiteCommand SQLite3Cmd = SQLite3Con.CreateCommand();
SQLite3Cmd.CommandText = strQuery;
try
{
SQLite3Cmd.ExecuteNonQuery();
textResult.AppendText(" Test Table Create ... OK\n");

bPrevStepSuccess = true;
}
catch (System.Data.SQLite.SQLiteException ex)
{
int nResult = SQLite3Con.ResultCode();
textResult.AppendText(" Test Table Create ... FAIL, Error Msg : "
+ ex.Message + "\n");

bPrevStepSuccess = false;
}

if (bPrevStepSuccess)
{
// Insert
textResult.AppendText(" Inserting ...\n");
strQuery = "INSERT INTO TestTable (name, age, country) VALUES (?,?,?);";

SQLite3Cmd.CommandText = strQuery;
SQLiteParameter paramName = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramName);
SQLiteParameter paramAge = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramAge);
SQLiteParameter paramCountry = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramCountry);

for (int i = 0; i < 10; ++i)
{
paramName.Value = "Name " + i.ToString();
paramAge.Value = 20 + i;
paramCountry.Value = "None";

int InsertRow = SQLite3Cmd.ExecuteNonQuery();

if (InsertRow == 1)
{
textResult.AppendText(" Insert ... OK\n");
}
else
{
textResult.AppendText(" Insert ... FAIL\n");
}
}

strQuery = "SELECT COUNT(*) FROM TestTable;";

SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;

using (SQLiteDataReader SQLite3Reader = SQLite3Cmd.ExecuteReader())
{
if (SQLite3Reader.Read())
{
string strRow = " Row Count ... "
+ SQLite3Reader.GetValue(0).ToString() + "\n";

textResult.AppendText(strRow);
}
}

// Selecting
textResult.AppendText(" Selecting ...\n");
strQuery = "SELECT * FROM TestTable;";

SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;

using (SQLiteDataReader SQLite3Reader = SQLite3Cmd.ExecuteReader())
{
while (SQLite3Reader.Read())
{
string strRow = " "
+ SQLite3Reader.GetValue(0).ToString() + " "
+ SQLite3Reader.GetValue(1).ToString() + " "
+ SQLite3Reader.GetValue(2).ToString()
+ "\n";

textResult.AppendText(strRow);
}
}

// Updating...
textResult.AppendText(" Updating ...\n");
strQuery = "UPDATE TestTable SET country=@country WHERE age<@age;";
SQLite3Cmd.CommandText = strQuery;

paramCountry.ParameterName = "@country";
paramCountry.Value = "KOREA";
SQLite3Cmd.Parameters.Add(paramCountry);

paramAge.ParameterName = "@age";
paramAge.Value = 25;
SQLite3Cmd.Parameters.Add(paramAge);

int nUpdated = SQLite3Cmd.ExecuteNonQuery();

string strMsg = " Updated Row(s) Count ... "
+ nUpdated.ToString() + "\n";
textResult.AppendText(strMsg);

// Deleting...
textResult.AppendText(" Deleting ...\n");
strQuery = "DELETE FROM TestTable WHERE age < @age;";

SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;

paramAge.ParameterName = "@age";
paramAge.Value = 25;
SQLite3Cmd.Parameters.Add(paramAge);

int nDeleted = SQLite3Cmd.ExecuteNonQuery();

strMsg = " Deleted Row(s) Count ... "
+ nDeleted.ToString() + "\n";
textResult.AppendText(strMsg);

// Drop Table
strQuery = "DROP TABLE IF EXISTS TestTable;";

SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;

SQLite3Cmd.ExecuteNonQuery();
textResult.AppendText(" Test Table dropped ... OK\n");
}
}
else
{
textResult.AppendText("FAIL\n");
}

SQLite3Con.Close();
textResult.AppendText("Finish.");





C#은 C++ 에서의 방법과 많이 다른 것 같다. 효과적으로 사용하기 위해서는 C#의 데이터베이스에 대한 공부가 필요할 것 같다.&

Original Post : http://neodreamer-dev.tistory.com/595

No comments :

Post a Comment