What is the best way to connect and use a sqlite database from C#

前端 未结 9 1008
执笔经年
执笔经年 2020-11-29 19:24

I\'ve done this before in C++ by including sqlite.h but is there a similarly easy way in C#?

9条回答
  •  不知归路
    2020-11-29 19:50

    I'm with, Bruce. I AM using http://system.data.sqlite.org/ with great success as well. Here's a simple class example that I created:

    using System;
    using System.Text;
    using System.Data;
    using System.Data.SQLite;
    
    namespace MySqlLite
    {
          class DataClass
          {
            private SQLiteConnection sqlite;
    
            public DataClass()
            {
                  //This part killed me in the beginning.  I was specifying "DataSource"
                  //instead of "Data Source"
                  sqlite = new SQLiteConnection("Data Source=/path/to/file.db");
    
            }
    
            public DataTable selectQuery(string query)
            {
                  SQLiteDataAdapter ad;
                  DataTable dt = new DataTable();
    
                  try
                  {
                        SQLiteCommand cmd;
                        sqlite.Open();  //Initiate connection to the db
                        cmd = sqlite.CreateCommand();
                        cmd.CommandText = query;  //set the passed query
                        ad = new SQLiteDataAdapter(cmd);
                        ad.Fill(dt); //fill the datasource
                  }
                  catch(SQLiteException ex)
                  {
                        //Add your exception code here.
                  }
                  sqlite.Close();
                  return dt;
      }
    }
    

    There is also an NuGet package: System.Data.SQLite available.

提交回复
热议问题