2013-07-23 28 views
1

這是我訪問代碼:訪問SQL插入功能不起作用?

namespace DataBaseApp 
{ 
     class DB_Access 
     { 
      SqlConnection conn = new SqlConnection(); 

      public DB_Access()       
      {      
       conn = DB_Connection.GetConnection(); // Bağlantıyı sağlamak için DB_Connection classından metodu aldım değere atadım // 
      }    

      public void add_student(string RegNo, string FName, string LName, string Phone) // Burada programdan veritabanina nasil veri eklenir // 
      { 
       if (conn.State.ToString() == "Closed") // State durum bildirir.Eğer Database akışı kapalıysa açalım // 
       { 
        conn.Open();   
       } 
       try 
       { 
        SqlCommand newCmd = conn.CreateCommand(); 
        newCmd.Connection = conn; 

        newCmd.CommandType = CommandType.Text; 
        newCmd.CommandText = "INSERT INTO Student(RegNo,FName,LName,Phone) values(RegNo,FName,LName,Phone)"; 
        newCmd.ExecuteNonQuery(); 
       }   
       catch (Exception Ex) 
       { 
        Console.WriteLine("Errorr " + Ex);   
       }   
      }   
     } 

,這是連接代碼

namespace DataBaseApp 
{ 
    class DB_Connection 
    { 
     public static SqlConnection NewCon; // Yeni bir bağlantıo oluşturma // 
     public static string ConStr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString; //App.config dosyasıyla bağlantı oluşturma // 

     public static SqlConnection GetConnection()  //.config den gelen string file ile bağlantı kurulur // 
     { 
      NewCon = new SqlConnection(ConStr); 
      return NewCon;  
     }  
    } 

當我運行這個這個不能運行add_student方法?我完全改變app.config文件我認爲錯誤不在app.config

事實上,這是簡單的SQL集成到C#的Windows窗體應用程序,但是當我把添加新的學生方法的程序崩潰...

回答

1

在你插入,SqlCommand的,你不及格的值。

所以你應該修改你的代碼,以這樣的:

newCmd.CommandText = "INSERT INTO Student(RegNo,FName,LName,Phone) values(@RegNo,@FName,@LName, @Phone)"; 
newCmd.Parameters.AddWithValue("@RegNo", RegNo); 
newCmd.Parameters.AddWithValue("@FName", FName); 
newCmd.Parameters.AddWithValue("@LName", LName); 
newCmd.Parameters.AddWithValue("@Phone", Phone); 

旁註: 此外,編輯下面的代碼:

if (conn.State.ToString() == "Closed") 

要這樣:

if (conn.State == ConnectionState.Closed) 
+0

如何像包括add_student.RegNo ?? –

+0

@crazy_tr你是什麼意思?順便說一句。我更新了我的答案以匹配您的參數值。 –