0

我已经编写了一个代码来将数据插入到SQL LITE数据库中,如下所示

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        count = 0;
       Session["x"] = "session value";

    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    string path = Server.MapPath("bin/sampldb.db");
    SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
    try
    {
        conn.Open();
        SQLiteCommand cmd = new SQLiteCommand();
        cmd.Connection = conn;
        string txt="insert into stu values("+TextBox1.Text  +",'"+TextBox2.Text+"')";
        cmd.CommandType = CommandType.Text;
        cmd.CommandText  = txt;
        cmd.ExecuteNonQuery();
        conn.Close(); 
    }
    catch (Exception ex)
    {
        Label1.Visible = true;
        Label1.Text = "Error:" + ex.Message;
    }

}

在检索数据时插入后Sessionnull不知道为什么

 protected void Button2_Click(object sender, EventArgs e)
{
    if (Session["x"] != null) // Getting Null here
    {
        Label1.Visible = true;
        Label1.Text = Session["x"].ToString();
        DataSet m_oDataSet = new DataSet();
        string path = Server.MapPath("bin/sampldb.db");
        SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
        try
        {
            conn.Open();
            SQLiteCommand cmd = new SQLiteCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.Text;
            string txt = "select * from stu";
            cmd.CommandText = txt;

            SQLiteDataAdapter adp = new SQLiteDataAdapter();
            adp.SelectCommand = cmd;
            adp.Fill(m_oDataSet);
            GridView1.DataSource = m_oDataSet.Tables[0];
            GridView1.DataBind();

        }
        catch (Exception ex)
        {
            Label1.Visible = true;
            Label1.Text = "Error:" + ex.Message;
        }
        finally
        {
            conn.Close();
        }

    }
}

测试时相同的代码Sql server 2008可以正常工作

protected void BtnSqlInsert_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(cnstr);
    con.Open();
    SqlCommand cmd = new SqlCommand("Insert into [User] values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
    cmd.ExecuteNonQuery();
    con.Close();
}
protected void BtnSqlGet_Click(object sender, EventArgs e)
{
    if (Session["x"] != null) //Able to get session here
    {
        Label1.Visible = true;
        Label1.Text = Session["x"].ToString();
    }
}

我的sql lite路径来自Bin文件夹,如图所示

在此处输入图像描述

4

1 回答 1

1

您的应用程序写入 DB(位于 BIN 文件夹中)。这会导致应用重启 => 进程内会话丢失。您不应该解决后果(通过使用 StateServer 模式),您应该解决最初的原因 - 将 db 文件移动到另一个文件夹中,远离 BIN 文件夹。

于 2012-04-11T12:14:46.370 回答