简体   繁体   English

从字符串C#转换日期和/或时间时转换失败

[英]Conversion failed when converting date and/or time from character string C#

I would like a help please. 请给我一个帮助。 When I want insert datetimepicker value into my table but he doesn't can insert and he show me a message 当我想将datetimepicker值插入到我的表中但他无法插入时,他向我显示一条消息

Conversion failed when converting date and/or time from character string 从字符串转换日期和/或时间时转换失败

You can help me please ! 你可以帮我!

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void add_Click(object sender, EventArgs e)
    {
        cmd.CommandText = "Insert into clients values (" + cintxt.Text + ", '" + nomtxt.Text + "', '" + prntxt.Text + "', '" + datenaiss.Value + "', '" + addtxt.Text + "', '" + teltxt.Text + "')";
        cnx.Open();
        cmd.ExecuteNonQuery();
        cnx.Close();
    }

Your code that tries to insert the record should be changed to use a parameterized approach. 您尝试插入记录的代码应更改为使用参数化方法。

This could be an example 这可能是一个例子

private void add_Click(object sender, EventArgs e)
{
    string commandText = @"Insert into clients values 
                           (@id, @name, @prn, @datan, @addr, @tel)";

    using(SqlConnection cnx = new SqlConnection(connectionString))
    using(SqlCommand cmd = new SqlCommand(commandText, cnx)
    {
        cmd.Parameters.AddWithValue("@id", Convert.ToInt32(cintxt.Text));
        cmd.Parameters.AddWithValue("@name", nomtxt.Text);
        cmd.Parameters.AddWithValue("@prn", prntxt.Text);
        cmd.Parameters.AddWithValue("@datan", datenaiss.Value);
        cmd.Parameters.AddWithValue("@addr", addtxt.Text);
        cmd.Parameters.AddWithValue("@tel", teltxt.Text );
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

In this code I have changed something. 在这段代码中,我做了一些更改。 First, the connection and the command are no more global variables but just local and are enclosed in a using statement that ensure a proper closing and disposing also if, for any reason, the code throws an exception. 首先,连接和命令不再是全局变量,而只是局部变量,并包含在using语句中,该语句确保即使由于某种原因代码引发异常也可以正确关闭和处置。

Second the command text is no more a concatenation of strings, but it is only a single string with parameters placeholders. 其次,命令文本不再是字符串的串联,而只是带有参数占位符的单个字符串。 Concatenating string to build command texts is really a bad practice. 串联字符串以构建命令文本确实是一个坏习惯。 Sql Injection hackers wait for commands built in this way to hit your database and, as you have already seen, more often than not, the underlying datatable doesn't understand a string that represent a date to be a valid date. Sql Injection黑客等待以这种方式构建的命令来命中您的数据库,并且正如您已经看到的那样,底层数据表通常不理解表示日期为有效日期的字符串。

Finally the command parameters collection is filled with a parameter for every field expected by the command text placeholders. 最后,在命令参数集合中为命令文本占位符期望的每个字段填充一个参数。 Notice that in this way you build parameters that are of the datatype of the value passed not simply strings that are not expected by the datatable fields. 请注意,通过这种方式,您可以构建传递的值的数据类型的参数,而不仅仅是数据表字段不期望的字符串。 Of course in your actual situation it is possible that some of these parameters should be changed to match exactly your datatable field (for example I don't know id the first field is an integer or not) 当然,在您的实际情况下,可能需要更改其中一些参数以使其与您的datatable字段完全匹配(例如,我不知道id第一个字段是否为整数)

EDIT As requested by comments below I add also some considerations on the method AddWithValue . 编辑根据下面的评论要求,我还对方法AddWithValue添加了一些注意AddWithValue

While it is convenient and expressive it could be a problem if your program call this code with frequency or if your database is under heavy use. 虽然方便且富有表现力,但是如果您的程序频繁调用此代码或数据库使用量过多,则可能会出现问题。 The preferred method to use is 首选使用的方法是

 cmd.Parameters.Add("@name", SqlDbType.NVarChar, 50).Value = nomtxt.Text;
 .....

See MSDN SqlParameterCollection.Add 请参见MSDN SqlParameterCollection.Add
and more info about the difference between Add and AddWithValue are explained here 有关Add和AddWithValue之间差异的更多信息,请参见此处
How Data Access Code Affects Database Performance 数据访问代码如何影响数据库性能

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将C#datetime发送到SQL Server-错误“从字符串转换日期和/或时间时转换失败” - Send C# datetime to SQL Server - error “Conversion failed when converting date and/or time from character string” 从字符串转换日期和/或时间时,C#转换失败 - C# Conversion failed when converting date and/or time from character string 从C#中的字符串SQL转换日期和/或时间时转换失败 - Conversion failed when converting date and/or time from character string SQL in c# 从C#中的字符串转换日期和/或时间时转换失败 - Conversion failed when converting date and/or time from character string in C# 从字符串 SQL (c#) 转换日期或时间时,日期时间转换失败 - datetime conversion failed when converting date or time from character string SQL (c#) 使用日期时间选择器从字符转换日期和/或时间时,C# 转换失败 - C# Conversion failed when converting date and/or time from character with a date time picker C#“从字符串转换日期/时间时转换失败”但查询在服务器上运行时效果很好 - C# "Conversion failed when converting date/time from character string" But query works well when run on server 从字符串转换日期和/或时间时转换失败 - Conversion failed when converting date and /or time from character string 从字符串转换日期和/或时间时转换失败 - Conversion failed when converting date and /or time from character string 从字符串错误4转换日期和/或时间时转换失败 - Conversion failed when converting date and/or time from character string error 4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM