我有一个通过在 .dbproj 项目中部署以下描述创建的 SQL Server 数据库表:
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()
运行时抛出异常
The name [the string representation of the GUID I passed] is not permitted in this context.
怎么了?我之前做了同样的操作,将数据插入到 SQLite 表中,并且成功了。如何将 GUID 传递到 SQL INSERT 语句?
最佳答案
使用参数化查询,如下所示:
command.CommandText = "INSERT INTO Tasks VALUES( @id, 0)";
command.Parameters.Add( "@id", SqlDbType.UniqueIdentifier, 16 ).Value = value;
这样,数据库驱动程序就会为您格式化值。这是一个很好的做法,也有助于保护您的数据库免受 SQL 注入(inject)攻击。
或者,您可以让数据库为您生成 guid:
command.CommandText = "INSERT INTO Tasks VALUES( NEWID(), 0)";
关于c# - 如何将 GUID 值传递到 SqlCommand 对象 SQL INSERT 语句中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5338038/