SQLite Getting started with SQLite in C#

2017.04.24 21:47

졸리운_곰 조회 수:1828

 

Getting started with SQLite in C#

This tutorial will teach you how to create and connect to an SQLite database in C#. You will also learn how to create and modify tables and how to execute SQL queries on the database and how to read the returned results.

I’ll assume that you’re already familiar with SQL and at least have some knowledge of how it works (for example: what to expect as a result from “select * from table1” )

There will probably be two parts, with the first one discussing the basics needed to do pretty much anything, and in the second part I’ll discuss some miscellaneous subjects like how to parameterize your queries to make them much faster and safer.

Let’s get started.

Create a standard C# console project.

Since we’re working in C# we’ll be using the System.Data.SQLite library. This library is not a standard library (packaged with .NET for example) so we’ll need to download it. It is being developed by the people who’re also working on the (original) SQLite.

All you’ll need are two files, a .dll and a .xml file for some documentation. These files are available for download at the end of this article, you can also download these from their website, but you’ll also get some files that you don’t need.

Put these files in the folder of your project and add an assembly reference to the .dll. Just browse to System.Data.SQLite.dll and select it.

Now add using System.Data.SQLite; to the usings and you’re done. You’ve successfully added the SQLite library to you project!

Creating a database file:

You usually don’t need to create a new database file, you work with an existing one, but for those cases where you do need to create a brand new one, here’s the code:

1
SQLiteConnection.CreateFile("MyDatabase.sqlite");

Connecting to a database:

Before you can use the database, you’ll need to connect to it. This connection is stored inside a connection object. Every time you interact with the database, you’ll need to provide the connection object. Therefore, we’ll declare the connection object as a member variable.

1
SQLiteConnection m_dbConnection;

When creating a connection, we’ll need to provide a “connection string” this string can contain information about the… connection. Things like the filename of the database, the version, but can also contain things like a password, if it’s required.

You can find a few of these at: http://www.connectionstrings.com/sqlite

The first one is good enough to get our connection up and running, so we get:

1
2
3
m_dbConnection =
new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

After we create the connection object, we’ll have to open it. And with every Open() there comes a Close(), so don’t forget to call that after you’re done with your connection.

Creating a table:

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Let’s write some SQL now. We’ll create a table with two columns, the first one contains names and the second one contains scores. See it as a high scores table.

1
string sql = "create table highscores (name varchar(20), score int)";

You could also spam caps if you like and get something like this:

1
string sql = "CREATE TABLE highscores (name VARCHAR(20), score INT)";

Now we’ll need to create an SQL command in order to execute it. Luckily, we’ve got the SQLiteCommand class for this. We create a command by entering the sql query along with the connection object.

1
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

Afterwards, we execute the command. But before we execute our command, i’d like to mention that not all commands are the same, some commands return results (like SELECT etc.) and others don’t (like the one we just wrote) That’s why there are two execute methods (actually, there are three) One returns the actual results (the rows of the table) the other returns an integer indicating the number of rows that have been modified. We’ll use the last one now.

1
command.ExecuteNonQuery();

At this time, we’re not interested in the number of rows that have been modified (it’s 0) But you could imagine that it might be interesting to know this information in UPDATE queries.

Filling our table:

Let’s fill our table with some values, so we can do some SELECT queries. Let’s create a new command. We’ll see later that this process can be made a bit easier and faster with command parameters.

1
string sql = "insert into highscores (name, score) values ('Me', 9001)";

We create and execute the command the same way as we created the table. I added two more rows (or records) to the table. Here’s the code:

1
2
3
4
5
6
7
8
9
string sql = "insert into highscores (name, score) values ('Me', 3000)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('Myself', 6000)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
sql = "insert into highscores (name, score) values ('And I', 9001)";
command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

As you can see, this is three times pretty much the same piece code. But it works!

Getting the high scores out of our database:

Let’s query the database for the high scores sorted on score in descending order. Our SQL query becomes: “select * from highscores order by score desc”

We create a command in the regular fashion:

1
2
string sql = "select * from highscores order by score desc";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);

However, we execute this command using a different method, we’ll use the ExecuteReader() method which returns an SQLiteDataReader object. We’ll use this object to read the results of the query.

1
SQLiteDataReader reader = command.ExecuteReader();

With this reader you can read the result row by row. Here’s some code that iterates trough all the rows and writes them to the console:

1
2
3
4
5
string sql = "select * from highscores order by score desc";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
       Console.WriteLine("Name: " + reader["name"] + "\tScore: " + reader["score"]);

The Read() method of the reader moves the reader to the next row. With the [] operators, you can read the value of a certain column. The value returned is of the type object. So you’ll usually need to cast it before you can use it. Fortunately, you usually know what this type is.

Well, that’s about it for this tutorial. You should now be able to do pretty much anything you want with your database.

Click here to download the project files that implement what we’ve discussed in this article.

The above link also contains the libraries. If you’d like to have only the library, click the link below: The version of the library provided here is the .NET 4.0 x86 version. This should work fine for anyone working in Visual Studio 2010. If it doesn’t work, download the correct version from their website (mentiond at the beginning of this article)

Download only the libraries.

 

[출처] http://blog.tigrangasparian.com/2012/02/09/getting-started-with-sqlite-in-c-part-one/

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
공지 오라클 기본 샘플 데이터베이스 졸리운_곰 2014.01.02 86160
공지 [SQL컨셉] 서적 "SQL컨셉"의 샘플 데이타 베이스 SAMPLE DATABASE of ORACLE 가을의 곰을... 2013.02.10 78656
공지 [G_SQL] Sample Database 가을의 곰을... 2012.05.20 95390
22 UNION과 UNION ALL 의 차이 및 주의 사항 졸리운_곰 2017.08.27 1282
21 컬럼내 특정 문자를 다른문자로 변경하고자 할때 졸리운_곰 2017.06.10 1499
20 [MySQL] 레코드 데이터 치환하기 (REPLACE) 졸리운_곰 2017.06.10 1418
19 MySQL / 테이블에서 특정 문자열 바꾸기 졸리운_곰 2017.06.10 1303
18 MySQL Redis Plugin file 졸리운_곰 2017.05.30 1720
17 [DB] MySQL Check, Repair, Optimize(개별/전체 테이블 포함) 졸리운_곰 2017.05.21 1249
16 Transfer from sqlite to MySQL/ sqlite에서 mysql로 변환 졸리운_곰 2017.03.18 1107
15 [MySQL] 힌트설정 / 쿼리캐시 졸리운_곰 2017.03.15 1504
14 [MySQL힌트 정리] 졸리운_곰 2017.03.15 1712
13 [mysql]Hint 사용방법 졸리운_곰 2017.03.15 1501
12 MySQL Ver. 5.1 힌트를 이용한 실행계획 제어 file 졸리운_곰 2017.03.15 1180
11 MySQL 덤프 / 임포트 dump / import 졸리운_곰 2017.01.05 1519
10 [질문] 두개의 컬럼에 대해 group by 적용 할 수 있을까요? 졸리운_곰 2016.12.17 841
9 MySQL 중복 키 관리 방법 (INSERT 시 중복 키 관리 방법 (INSERT IGNORE, REPLACE INTO, ON DUPLICATE UPDATE) 졸리운_곰 2016.12.17 1105
8 [mysql] 쿼리값이 NULL 일때 0으로 바꾸기 졸리운_곰 2016.12.14 1192
7 MySql] Insert Select 문 졸리운_곰 2016.12.06 1410
6 [MySQL] substring_index , substring ( split, explode ) 졸리운_곰 2016.12.06 1365
5 MySQL 테이블 이름변경, 테이블 복사 졸리운_곰 2016.11.23 1533
4 [MySQL] MySQL 테이블 수정 졸리운_곰 2016.11.16 1539
3 generate days from date range mysql 날짜검색시 between 안에 포함되는 날짜전체 출력 졸리운_곰 2016.11.02 1257
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED