我想连接到SQLite数据库。请告诉我WORKS的示例代码。此外,我想将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();
答案 0 :(得分:3)
您可以使用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"));
...
}
}
}
答案 1 :(得分:2)
除了Darin提供的答案之外,SQLite中没有“create database”命令(从我记忆中)。当您启动“SQLiteConnection”时,如果给定的数据库(.db3)不存在,它会自动创建它......然后,您可以在那里创建表。