2014-07-08 70 views
0

我想創建通過C# 表我使用下面的代碼出錯創建表

private void Login_Load(object sender, EventArgs e) 
    { 
     string connectionstring = "server=.;database=Student;Integrated Security=True"; 
     SqlConnection conn = new SqlConnection(connectionstring); 
     string fee_table = @" 
    IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'fees') AND type in (N'U')) CREATE TABLE user (user_name char(50),password char(50));"; 

     conn.Open(); 
     SqlCommand cmd = new SqlCommand(fee_table, conn); 
     cmd.ExecuteNonQuery(); 
    } 

但IAM獲得運行時錯誤語法錯誤附近用戶

+0

嗨,你有什麼錯誤? – Haris

+1

谷歌第一個「ms-sql語法錯誤附近的用戶」的結果是[this SO Q&A](http://stackoverflow.com/questions/20543395/c-sharp-syntax-error-near-table-name),它作爲[在MS SQL Server中創建保留字/關鍵字的表名]的副本關閉(http://stackoverflow.com/questions/695578​​/creating-table-names-that-are-reserved-words-keywords-在MS-SQL服務器)。請嘗試先搜索。 – CodeCaster

+0

「user1」附近的語法不正確。 – Aman

回答

4

user是許多數據庫的關鍵字。您需要更改表格的名稱或引用它。例如,在SQL Server中做到這一點:

CREATE TABLE [user] (user_name char(50),password char(50)) 

在其他數據庫系統中您可以使用:

CREATE TABLE "user" (user_name char(50),password char(50)) 

或者:

CREATE TABLE 'user' (user_name char(50),password char(50)) 
+0

我絞死了表的名字,但仍然是相同的錯誤 – Aman

+1

相同的錯誤?我對此表示懷疑。 – DavidG

1

USER是在T-SQL一個reserved keyword。你應該使用它與方括號[]。但是,最好的解決方案是將名稱更改爲非保留字。

同樣使用using statement來處置您的SqlConnectionSqlCommand

string connectionstring = "server=.;database=Student;Integrated Security=True"; 
using(SqlConnection con = new SqlConnection(connectionstring)) 
using(SqlCommand cmd = con.CreateCommand()) 
{ 
    ... 
    con.Open(); 
    cmd.ExecuteNonQuery(); 
} 
+0

如果我更改表名,那麼我也必須把[]放在表名中 – Aman