要想在ASP.NET项目中使用SQLite数据库,先需下载一个ADO.NET 2.0 SQLite Data Provider,下载地址为:http:///project/showfiles.php?group_id=132486&package_id=145568
如下图:
但是奇怪的是,我的安装完后,添加引用没有,所以我只能选择浏览,如下图:
找到 sqlite 的安装路径bin目录下,会发现 dll 文件
选中,添加即可:
aspx 前台界面仅仅添加了一个 button
aspx 界面 后台代码。如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SQLite;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SQLiteConnection.ClearAllPools();
SQLiteConnection.CreateFile(Server.MapPath("~")+"/UserData.dbx");
SQLiteConnection conn=new SQLiteConnection("Data Source="+Server.MapPath("~"+"/UserData.dbx"));
conn.Open();
Response.Write("打开数据库成功~~<br />");
SQLiteCommand cmd=new SQLiteCommand();
cmd.CommandText="create table Users (UserID int primary key,UserName varchar(100) not null,UserPassword varchar(100) not null)";
cmd.Connection=conn;
cmd.ExecuteNonQuery();
for(int i=0;i<100;i++)
{
cmd.CommandText="insert into Users (UserID,UserName,UserPassword) values ("+i+",'TestUser_"+i+"','"+DateTime.Now.ToString().Replace(" ","-").Replace(":","-")+"')";
cmd.ExecuteNonQuery();
}
Response.Write("插入成功~~<br />");
cmd.CommandText="select Username from Users where UserID=1";
cmd.Connection=conn;
string tempUserName=cmd.ExecuteScalar().ToString();
Response.Write("单个值查询结果为:"+tempUserName+"<br /><br />");
cmd.CommandText="select * from Users ";
cmd.Connection=conn;
SQLiteDataReader sdrInfo=cmd.ExecuteReader();
if(sdrInfo!=null)
{
int userID=0;
string userName=string.Empty;
string userPassword=string.Empty;
while(sdrInfo.Read())
{
userID=Convert.ToInt32(sdrInfo["UserID"]);
userName=sdrInfo["UserName"].ToString();
userPassword=sdrInfo["UserPassword"].ToString();
Response.Write("UserID:"+userID+"<br />");
Response.Write("UserName:"+userName+"<br />");
Response.Write("UserPassword:"+userPassword+"<br />");
Response.Write("<br />");
}
sdrInfo.Close();
sdrInfo.Dispose();
}
cmd.CommandText="update Users set UserPassword='linxiang'";
cmd.Connection=conn;
cmd.ExecuteNonQuery();
Response.Write("更新数据库中的数据成功.");
Response.Write("以下结果为查询从数据库中经过编辑过后的数据项<br /><br />");
cmd.CommandText="select * from Users ";
cmd.Connection=conn;
sdrInfo=cmd.ExecuteReader();
if(sdrInfo!=null)
{
int userID=0;
string userName=string.Empty;
string userPassword=string.Empty;
while(sdrInfo.Read())
{
userID=Convert.ToInt32(sdrInfo["UserID"]);
userName=sdrInfo["UserName"].ToString();
userPassword=sdrInfo["UserPassword"].ToString();
Response.Write("UserID:"+userID+"<br />");
Response.Write("UserName:"+userName+"<br />");
Response.Write("UserPassword:"+userPassword+"<br />");
Response.Write("<br />");
}
sdrInfo.Close();
sdrInfo.Dispose();
}
conn.Clone();
conn.Dispose();
}
}
运行后界面,如下:
点击按钮如下图:
源码下载
原文地址:http://space./12639172/viewspace-623439623439