如何使用C#操作SQLite数据库

前面的文章已经介绍了SQLite数据库和ADO.NET Provider for SQLite, 现在介绍下如何使用c#操作SQLite数据库。

1. 到 http://sourceforge.net/projects/sqlite-dotnet2/files/  下载ADO.NET provider for the SQLite database engine. 然后安装。

2. 在VS 2005 新建控制台程序,然后添加引用System.Data.SQLite.dll,该文件在ADO.NET provider for the SQLite 安装目录的bin目录下。

3. using 该命名空间,就可以和使用其他ADO.NET Provider一样使用它了。

 

代码如下:

 

Code
<!-- <br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->static   void  Main( string [] args)
        {
            
string  datasource  =   " c:/test.db " ;

            
if ! System.IO.File.Exists( datasource ))
                SQLiteConnection.CreateFile(datasource);
            
            SQLiteConnection conn 
=   new  SQLiteConnection();
            SQLiteConnectionStringBuilder conStr 
=   new  SQLiteConnectionStringBuilder();

            conStr.DataSource 
=  datasource;

            conn.ConnectionString 
=  conStr.ToString();
            
            
// open connetcion
            conn.Open();

            SQLiteCommand cmd 
=   new  SQLiteCommand();
            
string  sql  =   string .Empty;
            cmd.Connection 
=  conn;
            
/*
            //create a table
            string sql = "CREATE TABLE test(username varchar(20),password varchar(20));";
            cmd.CommandText = sql;
            cmd.Connection = conn;
            cmd.ExecuteNonQuery();
            
*/
            
// insert data
            
            
for  ( int  i  =   0 ; i  <=   10 ; i ++ )
            {
                sql 
=   " INSERT INTO test VALUES('cola','mypassword') " ;
                cmd.CommandText 
=  sql;
                cmd.ExecuteNonQuery();
                
            }


            sql 
=   " SELECT * FROM test " ;
            cmd.CommandText 
=  sql;

            
using  (SQLiteDataReader reader  =  cmd.ExecuteReader())
            {
                
while  (reader.Read())
                {
                    Console.WriteLine(reader[
" username " ].ToString()  +   " --- "   +  reader[ " password " ].ToString());
                }
            }

            conn.Close();

            Console.Read();



        }

 

 

运行结果:

cola---mypassword

cola---mypassword

cola---mypassword

cola---mypassword

cola---mypassword

cola---mypassword

cola---mypassword

cola---mypassword

cola---mypassword

cola---mypassword

cola---mypassword

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值