如何连接使用SQLite数据库C#应用程序 [英] How to connect C# app with SQLite database
本文介绍了如何连接使用SQLite数据库C#应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想连接到一个SQLite数据库。请告诉我其中工程示例代码。此外,我想用database.I使用此代码链接datagridview的,但它不工作:
私人的DataTable dt的;
公共Form1中()
{
的InitializeComponent();
this.dt =新的DataTable();
}
私人SQLiteConnection SQLiteConnection;
私人无效数据类()
{
SQLiteConnection =新SQLiteConnection(数据源= PasswordManager.s3db;版本= 3;);
}
私人无效的GetData()
{
SQLiteDataAdapter DataAdapter的;
试
{
SQLiteCommand CMD;
SQLiteConnection.Open(); //初始化连接到数据库
CMD = SQLiteConnection.CreateCommand();
cmd.CommandText =从PasswordManager选择*;; //设置通过查询
= DataAdapter的新SQLiteDataAdapter(CMD);
DataAdapter.Fill方法(DT); //填写数据源
dataGridView1.DataSource = DT;
}
赶上(SQLiteException前)
{
//这里添加您的异常代码。
}
SQLiteConnection.Close();
解决方案
您可以使用的 System.Data.SQLite ADO.NET提供。一旦你下载和引用的程序集,这是非常简单的ADO.NET代码:
使用(VAR康恩=新SQLiteConnection(@数据源= test.db3))使用
(VAR CMD = conn.CreateCommand())
{
conn.Open();
cmd.CommandText =SELECT ID从foo;使用
(VAR读卡器= cmd.ExecuteReader())
{
,而(reader.Read())
{
INT ID = reader.GetInt32(阅读器。 GetOrdinal(ID));
:
}
}
}
I want to connect to a SQLite database. Please show me example code which WORKS. Also I want to link datagridview with the database.I use this code but it doesn't work:
private DataTable dt;
public Form1()
{
InitializeComponent();
this.dt = new DataTable();
}
private SQLiteConnection SQLiteConnection;
private void DataClass()
{
SQLiteConnection = new SQLiteConnection("Data Source=PasswordManager.s3db;Version=3;");
}
private void GetData()
{
SQLiteDataAdapter DataAdapter;
try
{
SQLiteCommand cmd;
SQLiteConnection.Open(); //Initiate connection to the db
cmd = SQLiteConnection.CreateCommand();
cmd.CommandText = "select*from PasswordManager;"; //set the passed query
DataAdapter = new SQLiteDataAdapter(cmd);
DataAdapter.Fill(dt); //fill the datasource
dataGridView1.DataSource = dt;
}
catch(SQLiteException ex)
{
//Add your exception code here.
}
SQLiteConnection.Close();
解决方案
You could use the System.Data.SQLite ADO.NET provider. Once you download and reference the assembly, it's pretty straightforward ADO.NET code:
using (var conn = new SQLiteConnection(@"Data Source=test.db3"))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT id FROM foo";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = reader.GetInt32(reader.GetOrdinal("id"));
...
}
}
}
这篇关于如何连接使用SQLite数据库C#应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文