2012-04-09 52 views
0

我已經寫了代碼來將數據插入到SQL LITE數據庫如下爲什麼會越來越空當插入數據和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

+0

你是什麼意思與「變得空」。 Session是否等於null,還是Session [「x」]等於null? – Patrick 2012-04-09 11:25:12

+0

意思'Session [x]'等於null' – Dotnet 2012-04-09 11:28:17

+0

這很奇怪,如果你在PostBack上設置它,會發生什麼。我知道它不應該有所作爲,但你的代碼看起來是正確的..你是否將值設置爲null其他地方..? – Patrick 2012-04-09 11:32:18

回答

1

您的應用程序寫入DB(這是BIN文件夾)。這會導致應用程序重新啓動=>進程內會話丟失。你不應該解決這個後果(通過使用StateServer模式),你應該修改原來的原因 - 將db文件移動到遠離BIN文件夾的另一個文件夾中。