How do I pass a GUID value into an SqlCommand object SQL INSERT statement?
I have an SQL Server database table created by deploying the following description in a .dbproj project:
CREATE TABLE [dbo].[Tasks]
(
TaskId uniqueidentifier primary key,
State int not null,
)
and I want to insert a row into that table with the following code:
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();
}
开发者_运维知识库}
when ExecuteNonQuery()
runs an exeption is thrown saying
The name [the string representation of the GUID I passed] is not permitted in this context.
What's up? I did the same to insert data into an SQLite table previously and it worked. How do I pass a GUID into an SQL INSERT statement?
Use a parameterized query, like so:
command.CommandText = "INSERT INTO Tasks VALUES( @id, 0)";
command.Parameters.Add( "@id", SqlDbType.UniqueIdentifier, 16 ).Value = value;
This way, the database driver formats the value for you. This is a good practice that will also help protect your database from SQL Injection attacks.
Alternatively, you could let the database generate the guid for you:
command.CommandText = "INSERT INTO Tasks VALUES( NEWID(), 0)";
精彩评论