2015-04-21 89 views
0

對不起,問這個問題我知道還有很多其他問題,並試圖使用提供的解決方案,但我無法讓我的代碼工作。感謝您的期待!如在屬性所示連接與視覺工作室中的localdb不兼容

連接字符串:

數據 源=(的LocalDB)\ V11.0; AttachDbFilename =「C:\用戶\雅各布\文檔\ Visual Studio中 \項目\ WindowsFormsApplication2 \ WindowsFormsApplication2 \ ChatDB.mdf「;在app.config中集成 安全=真

連接字符串:

數據 源=(的LocalDB)\ 11.0; AttachDbFilename = | DataDirectory目錄| \ ChatDB.mdf;集成 安全=真

Error: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll 
Additional information: Incorrect syntax near the keyword 'User'. 

代碼:

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
//NC-1 More namespaces. 
using System.Data.SqlClient; 
using System.Configuration; 

namespace WindowsFormsApplication2 
{ 
    public partial class SignUp : Form 
    { 
     string connstr = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.ChatDBConnectionString"].ToString(); 

     public SignUp() 
     { 
      InitializeComponent(); 
     } 

     private void label1_Click(object sender, EventArgs e) 
     { 

     } 

     private void SubmitBtn_Click(object sender, EventArgs e) 
     { 
      string Name = NameText.Text; 
      string Pwd = PwdText.Text; 
      //make sure they have entered text 
      if (Name.Length > 0 && Pwd.Length > 0) 
      { 
       SqlConnection conn = new SqlConnection(connstr); 

       //NC-10 try-catch-finally 
       try 
       { 
        //NC-11 Open the connection. 
        conn.Open(); 

        SqlCommand insert = new SqlCommand(); 
        insert.Connection = conn; 
        insert.CommandText = "INSERT INTO [User] (Name,Password) VALUES ('" + Name + "','" + Pwd + "')"; 

        insert.ExecuteNonQuery(); 
        MessageBox.Show("Congrats!!!"); 

       } 
       catch 
       { 
        //NC-14 A simple catch. 

        MessageBox.Show("User was not returned. Account could not be created."); 
       } 
       finally 
       { 
        //NC-15 Close the connection. 
        conn.Close(); 
       } 
      } 
      //if no text make them enter 
      else 
      { 
       MessageBox.Show("Please enter Text in both fields."); 
      } 
     } 
    } 
} 

再次感謝你尋找。

+0

檢查你的SQL查詢。 –

+0

如果你在保留關鍵字「User」的周圍沒有方括號,我會期待這個錯誤。你的查詢看起來對我有效。仔細檢查異常和堆棧跟蹤 - 確保它指向上面發佈的代碼(而不是其他查詢)。 –

+0

格蘭特溫尼很不幸,這是解決方案中唯一的查詢,我剛開始使用visual studio和c#。 – tnyN

回答

1

的問題是你的SQL查詢,因爲您使用Reserved Keywords

試圖將表名稱更改爲tblUser

我也建議使用參數化查詢,以防止未來的SQL注入:(例如)

@"INSERT INTO [User] (Name,Password) VALUES (@Name, @Password);" 
+0

[應該沒關係。方括號否定保留關鍵字。](http://stackoverflow.com/questions/52898/what-is-the-use-of-the-square-brackets-in-sql-statements) –

+0

我正要嘗試那實際上,改變我的意思,我到底該怎麼做?對不起,無知。 – tnyN

+0

@GrantWinney是的,我知道,但我知道這會導致錯誤的唯一原因是保留關鍵字。 –