2014-07-08 69 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