为什么会话在插入数据和从SQL LITE获取数据时变为null

时间:2012-04-09 11:01:12

标签: asp.net sql-server-2008 sqlite

我编写了一个代码,用于将数据插入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;
    }

}

在检索数据Session时插入后null我不知道为什么

 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文件夹,如图片

所示

enter image description here

1 个答案:

答案 0 :(得分:1)

您的应用写入数据库(位于BIN文件夹中)。这导致app restart =>进程内会话丢失。你不应该解决后果(通过使用StateServer模式),你应该修复原因 - 将db文件移动到另一个文件夹,远离BIN文件夹。