我想连接到SQLite数据库。请给我看示例代码,该代码可以工作。我也想将datagridview与数据库链接。我使用此代码,但它不起作用:
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();
最佳答案
您可以使用System.Data.SQLite ADO.NET提供程序。一旦下载并引用了程序集,它就是非常简单的ADO.NET代码:
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"));
...
}
}
}