2011-03-17 81 views
2

我有一个.dbproj项目部署下面的描述中创建的SQL Server数据库表:如何将GUID值传递给SqlCommand对象SQL INSERT语句?

CREATE TABLE [dbo].[Tasks] 
(
TaskId uniqueidentifier primary key, 
State int not null, 
) 

,我想行插入该表与下面的代码:

using(SqlTransaction transaction = connection.BeginTransaction()) { 
    using(SqlCommand command = connection.CreateCommand()) { 
     command.CommandText = "INSERT INTO Tasks VALUES(\"" + 
      Guid.NewGuid().ToString() + "\", 0)"; 
     command.Transaction = transaction; 
     command.ExecuteNonQuery(); 
     transaction.Commit(); 
    } 
} 

ExecuteNonQuery()运行一个豁免被抛出说

在此上下文中不允许名称[我通过的GUID的字符串表示形式]。

这是怎么回事?我也是这样做的,以前将数据插入到SQLite表中并且工作正常。如何将GUID传递到SQL INSERT语句中?

+2

单引号(''')。 – 2011-03-17 10:57:31

+0

请勿使用单引号 - 请改用**参数化查询**!更安全....你可以拼写[SQL注入攻击?](http://xkcd.com/327/) – 2011-03-17 11:03:54

回答

10

使用参数化查询,像这样:

command.CommandText = "INSERT INTO Tasks VALUES(@id, 0)"; 
command.Parameters.Add("@id", SqlDbType.UniqueIdentifier, 16).Value = value; 

通过这种方式,数据库驱动程序格式,让您的值。这是一个很好的做法,它也有助于保护数据库免受SQL注入攻击。

或者,你可以让数据库生成的GUID为您提供:

command.CommandText = "INSERT INTO Tasks VALUES(NEWID(), 0)";
+0

+1不能说更好! – 2011-03-17 11:16:38