我正在尝试在我的应用程序中使用SQLite,而且它一直很坎坷。一些事情,先关闭。
谢谢,
卡梅伦
答案 0 :(得分:1)
我从未在Visual Studio和SQLite中使用过设计支持我想知道它是否可行,所以我建议你进入编码:-)这是一个说明基本思想的示例。首先,您可以创建数据库:
的Global.asax:
public class Global : System.Web.HttpApplication
{
public string GetDbFile()
{
return Path.Combine(Server.MapPath("~/App_Data"), "data.db3");
}
public string GetConnectionString()
{
return "Data Source=" + GetDbFile() + ";Version=3;";
}
protected void Application_Start(object sender, EventArgs e)
{
var dbFile = GetDbFile();
if (File.Exists(dbFile))
{
File.Delete(dbFile);
}
ExecuteCommand("create table users (usr_id integer primary key, usr_name string)");
ExecuteCommand("insert into users (usr_id, usr_name) values (1, 'user 1')");
ExecuteCommand("insert into users (usr_id, usr_name) values (2, 'user 2')");
}
public void ExecuteCommand(string sql)
{
using (var connection = new SQLiteConnection(GetConnectionString()))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
}
当然,如果您已有SQLite数据库文件,则可以跳过此步骤。每次应用程序启动时都不需要重新创建它:-)
数据库填满数据后,您可以在网格中显示它。
的Default.aspx:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Data.SQLite" %>
<script type="text/C#" runat="server">
private class User
{
public int Id { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
usersGrid.DataSource = GetUsers();
usersGrid.DataBind();
}
}
private IEnumerable<User> GetUsers()
{
using (var connection = new SQLiteConnection(ApplicationInstance.GetConnectionString()))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "select usr_id, usr_name from users";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return new User { Id = reader.GetInt32(0), Name = reader.GetString(1) };
}
}
}
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="usersGrid" runat="server" />
</div>
</form>
</body>
</html>