2014-04-26 25 views
1

我在將數據保存到我的程序的本地數據庫時遇到問題。它不會將用戶輸入的值存儲在用戶表中。可能是什麼問題,下面是一些代碼和圖片。將數據寫入數據庫不起作用


public void addInformationToDatabase() 
    { 
     string Sex = ddlGender.Text; 
     string Name = tbxName.Text; 
     string DOB = tbxDOB.Text; 

     string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; 

     SqlConnection Con = new SqlConnection(connectionString); 

     SqlCommand command = new SqlCommand(); 
     command.Connection = Con; 
     command.CommandType = CommandType.Text; 
     command.CommandText = "INSERT INTO User (Gender,Name,DOB) VALUES(@Sex,@Name,@DOB)"; 

     command.Parameters.AddWithValue("@Sex", Sex); 
     command.Parameters.AddWithValue("@FirstName", Name); 
     command.Parameters.AddWithValue("@DOB", DOB); 

     try 
     { 
      Con.Open(); 
      command.ExecuteNonQuery(); 

     } 
     catch (Exception ex) 
     { 
      Response.Write(ex.Message); 
     } 
     finally 
     { 
      Con.Close(); 
     } 
    } 

protected void btnNext_Click(object sender, EventArgs e) 
    { 
     addInformationToDatabase(); 
    } 

ERROR

Were I want to store user information

User table

任何幫助非常讚賞

回答

3

USER是Sql Server的reserved keyword。要使用它,你需要把它們放在方括號

command.CommandText = "INSERT INTO [User] (Gender,Name,DOB) VALUES(@Sex,@Name,@DOB)"; 

如果你仍然能夠改變這個名字,我建議要儘快做到這一點,因爲你將在每次工作時都記住了這個問題與該表

+0

Awh,我的壞。謝謝你的協助! – crsMC

+0

是的,抱歉,剛剛意識到。現在改變它,它的工作,感謝您的幫助! – crsMC

+1

DOB是表中的一個日期,您使用AddWithValue傳遞一個字符串來創建一個參數。所以,參數類型是NVarWChar不是日期。你可以用AddWithValue(「@ DOB」,Convert.ToDateTime(DOB))來解決 – Steve