nVarchar and SqlParameter

我的梦境 提交于 2019-12-01 11:03:15

Add(string, object) has been deprecated for this reason (from Pablo Castro of the SQL Server team):

The problem is that both the C# and the VB.NET compilers will expose very weird behavior for this code:

command.Parameters.Add(“@p”, 0);

you may expect this to use the overload that takes an object and assign the value 0 to it, but instead it will pick the overload that takes a SqlDbType as the second parameter! In order to avoid this (and potentially others) ambiguity between the Add(string, sqldbtype) and Add(string, object), we deprecated Add(string, object) and introduced AddWithValue(string, object). In general, having multiple overloads where the distinguishing parameter type is “object” in one of them is a dangerous thing to do.

You should parametrize your inserts with SqlParameters which allow you to specify the datatype explicitly. (Also it saves you the headache of figuring out the SQL server injection attack your query caused).

Example:

SqlCommand cmd  = new SqlCommand("insert into tbl_text (text) values(@MYTEXT)", myConnection);
cmd.Parameters.Add(new SqlParameter("@MYTEXT", SqlDbType.NVarChar)).Value = "Chci tančit v";
cmd.ExecuteNonQuery();

Don't put "N" before the parameter name, it is only used when using string constant to indicate it is a unicode string. So your query should be:

insert into tbl_text(text) values (@text)
Amirshk

Use SQLParameters.

Here is a simple example:

var cmd = _dbCon.CreateCommand();
cmd.CommandText =
    "insert into tbl_text (textfield) values(@textfield)";
cmd.Parameters.Add(new SQLParameter("@textfield", "Chci tančit v oblasti"));
cmd.ExecuteScalar();
Metin Atalay

Here is Simple Example

String filePath = @"D:\" + FileName;
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = 
    @"DECLARE @TraceId INT = (SELECT MAX(id) FROM sys.traces WITH (NOLOCK))
    SET @TraceId=@TraceId+1

    DECLARE @File NVARCHAR(256);
    Set @File= (@filePath)

    SET @TraceId=@TraceId+1 --Var olandan bir fazla

    DECLARE @MaxFileSize BIGINT = 1 /* max size of file as MegaByte*/
    DECLARE @FileCount INT = 1024 /* max file count for write*/

    exec sp_trace_create @traceid = @TraceId OUTPUT,
                                    @options = 2,
                                    @tracefile = @File,
                                    @maxfilesize = @MaxFileSize, 
                                    @stoptime = NULL,
                                    @filecount = @FileCount

    SELECT @TraceId";

command.Parameters.Add(new SqlParameter("@filePath", SqlDbType.NVarChar)).Value = filePath;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!