2015-06-14 66 views
1

我正在試驗數據庫,我找到了不同的方法來優化我的代碼。在這裏,我正在使用不同的類來停止重新編寫相同的代碼,例如添加,刪除和更新,我們使用相同的ExecuteNonQuery()方法。到目前爲止,更新刪除方法運行良好,除了插入。編譯器不會給出任何錯誤,但是從文本框中獲取的值不會轉到變量字符串查詢。我是新來的C#編碼。誰能幫我?或建議?如何將數據插入數據庫? - 用戶定義的類

using DBconnectionExercise.DBConnection_Components; 
namespace DBconnectionExercise 
{ 
    public partial class Student_Form : Form 
    { 
     DBComps dc = new DBComps(); 

     //public string constring; 
     //public SqlConnection con = null; 
     //public SqlCommand com = null; 
     public String query; 

     public Student_Form() 
     { 
      InitializeComponent(); 

      //constring = "Data Source=ASHANE-PC\\ASHANESQL;Initial Catalog=SchoolDB;Integrated Security=True"; 
      //con = new SqlConnection(constring); 

      dc.ConnectDB(); 


     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

      loadGridData(); 

     } 
     private void dtp_dob_ValueChanged(object sender, EventArgs e) 
     { 
      DateTime Now = DateTime.Today; 
      DateTime Dob = dtp_dob.Value.Date; 
      int a = Now.Year - Dob.Year; 
      if (Now < Dob.AddYears(a)) a--; 
      tb_Age.Text = a.ToString(); 
     } 

     private void loadGridData() 
     { 
      try 
      { 
       query = "Select * from tb_Student"; 
       //dc.OpenCon(); 
       //SqlDataAdapter da = new SqlDataAdapter(query, con); 
       DataTable dt1 = new DataTable(); 
       dt1 = dc.Data_Table(query); 
       //da.Fill(dt); 
       Stu_DataGrid.DataSource = dt1; 
       //con.Close(); 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
     } 

     private void ClearData() 
     { 
      tb_Name.Clear(); 
      tb_Address.Clear(); 
      tb_Telno.Clear(); 
      tb_Search.Clear(); 
      tb_Age.Clear(); 
      dtp_dob.Value = DateTime.Today; 

     } 

     private void btn_Add_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       String name = tb_Name.Text; 
       DateTime dob = dtp_dob.Value.Date; 
       int age = Convert.ToInt32(tb_Age.Text); 
       String Address = tb_Address.Text; 
       int telno = Convert.ToInt32(tb_Telno.Text); 
       int line = 0; 


       //con.Open(); 
       query = "Insert into tb_Student values(@Stu_Name, @Stu_DOB, @Age, @Stu_Address, @Stu_Tel_no)"; 
       //query = "Insert into tb_Student (Stu_Name, Stu_DOB, Age, Stu_Address, Stu_Tel_no) Values('" + name + "','" + dob + "','" + age + "','" + Address + "','" + telno + "')"; 
       MessageBox.Show(query); 
       //com = new SqlCommand(query, con); 

       // This is the Insert/save code 

       DBComps.com.Parameters.AddWithValue("@Stu_Name", name); 
       DBComps.com.Parameters.AddWithValue("@Stu_DOB", dob); 
       DBComps.com.Parameters.AddWithValue("@Age", age); 
       DBComps.com.Parameters.AddWithValue("@Stu_Address", Address); 
       DBComps.com.Parameters.AddWithValue("@Stu_Tel_no", telno); 

       //line = com.ExecuteNonQuery(); 
       line = dc.ExeNonQuery(query); 
       //com.Dispose(); 
       //con.Close(); 

       if (line > 0) 
       { 
        loadGridData(); 
        ClearData(); 
        MessageBox.Show("Data saved sucessfully!", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information); 
       } 
       else 
        MessageBox.Show("Data not Saved", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
      catch(Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
     } 

這是DBComps類以前寫SQL函數的方法。

namespace DBconnectionExercise.DBConnection_Components 
    { 
     public class DBComps 
     { 
      public String conSring; 
      public SqlConnection con = null; 
      public static SqlCommand com = null; 

      public void ConnectDB() 
      { 
       conSring = "Data Source=ASHANE-PC\\ASHANESQL;Initial Catalog=SchoolDB;Integrated Security=True"; 
       con = new SqlConnection(conSring); 
      } 

      public void OpenCon() 
      { 
       con.Open(); 
      } 

      public void CloseCon() 
      { 
       con.Close(); 
      } 

      public int ExeNonQuery(String query) //the method for Insert, update and delete. 
      { 

       int line = 0; 
       OpenCon(); 
       com = new SqlCommand(query, con); 
       line = com.ExecuteNonQuery(); 
       com.Dispose(); 
       CloseCon(); 

       return line; 
      } 
    } 
} 
+0

每次調用'dc.ExeNonQuery'時,都會創建一個新的命令實例'com = new SqlCommand(query,con);',從而失去了之前添加到以前'com'值的所有參數。最簡單的解決方案是每次停止創建新的命令實例,通過設置[命令文本屬性](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.com和text (v = vs.110).aspx)的現有命令(!!!它可以是空的第一次!!!)。 –

+0

P.S .:當實例方法和靜態字段不是實際需要時混合使用它是一個壞主意。此外,[使用](https://msdn.microsoft.com/en-us/library/yh598w02.aspx)聲明可能會對您感興趣。 –

+0

@EugenePodskal是的,我真的很傻。我刪除了所有這些,最後我找到了答案。謝謝您的幫助。 –

回答

1

好吧,終於我想出了我的問題的答案,因爲我的預期。在這裏如何做到這一點;

private void btn_Add_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       String name = tb_Name.Text; 
       DateTime dob = dtp_dob.Value.Date; 
       int age = Convert.ToInt32(tb_Age.Text); 
       String Address = tb_Address.Text; 
       int telno = Convert.ToInt32(tb_Telno.Text); 
       int line = 0; 


       query = "Insert into tb_Student values('"+ name +"','"+ dob +"','"+ age +"','"+ Address +"','"+ telno +"')"; 

       MessageBox.Show(query); //To see it works! 

       line = dc.ExeNonQuery(query); 

       if (line > 0) 
       { 
        loadGridData(); 
        ClearData(); 
        MessageBox.Show("Data saved sucessfully!", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information); 
       } 
       else 
        MessageBox.Show("Data not Saved", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error); 
      } 
      catch(Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
     } 

一定要記得寫查詢語句的變量/值,以便與表頭一致。否則會產生錯誤。感謝大家幫助解決這個問題! :-)

+0

最好的使用方法是使用參數! –

2

這是交談的數據庫非常非常糟糕的方式,它被破解利用SQL注入和因爲你正在學習,它的合適的時間來指出這一點:

query = "Insert into tb_Student values('"+ name +"','"+ dob +"','"+ age +"','"+ Address +"','"+ telno +"')"; 

SQL注入爲已讀了爲什麼以及如何,尋找最佳實踐以找出更好的方法。

+0

OK @mladen已經在上面了。謝謝。 –

+0

現在我看到我處於極度危險之中。我應該使用這個問題的參數。還修復了日期時間選擇器中惱人的錯誤。哇,謝謝你讓我知道SQL注入。 –