将varchar数据类型转换为日期时间数据类型导致asp.net c#中的超出范围值

时间:2022-12-22 16:44:46

I want to insert DateTime variable from ASP.Net C# into an SQL Server database. I get this error for some reason.

我想将ASP.Net C#中的DateTime变量插入到SQL Server数据库中。我出于某种原因得到了这个错误。

DateTime date = DateTime.Now; 

string sql2 = @"INSERT INTO registerTable (username,password,email,firstname,gw2user,typeofplay)
                VALUES ('" + user + "','" + pass + "','" + email + "','" + firstname + "','" + gw2user + "','" + type + "','" + date + "')";

the date column is a datetime date type.

日期列是日期时间日期类型。

3 个解决方案

#1


3  

You are missing the date column in your query. Change it to this to get rid of the error:

您缺少查询中的日期列。将其更改为此以消除错误:

INSERT INTO registerTable (username,password,email,firstname,gw2user,typeofplay, date) VALUES ('" + user + "','" + pass + "','" + email + "','" + firstname + "','" + gw2user + "','" + type + "','"+date+"')

Also, avoid using concatenation and use parametrised queries instead.

此外,请避免使用串联并使用参数化查询。

#2


2  

don't concatenate parameter values, you better use parameters

不要连接参数值,最好使用参数

string sql2 = @"INSERT INTO registerTable (username,password,email,firstname,gw2user,typeofplay, dateColumnName) VALUES (@username,@password,@email,@firstname,@gw2user,@typeofplay, @date)";

Read Working with Parameters

阅读使用参数

then you can set date parameter value as below

然后你可以设置日期参数值如下

cmd.Parameters.AddWithValue("@date", date);

do the same for other parameters as well.

对其他参数也这样做。

#3


0  

string sql2 = @"INSERT INTO registerTable (username,password,email,firstname,gw2user,typeofplay, dateColumnName) VALUES (@username,@password,@email,@firstname,@gw2user,@typeofplay, @date)";

#1


3  

You are missing the date column in your query. Change it to this to get rid of the error:

您缺少查询中的日期列。将其更改为此以消除错误:

INSERT INTO registerTable (username,password,email,firstname,gw2user,typeofplay, date) VALUES ('" + user + "','" + pass + "','" + email + "','" + firstname + "','" + gw2user + "','" + type + "','"+date+"')

Also, avoid using concatenation and use parametrised queries instead.

此外,请避免使用串联并使用参数化查询。

#2


2  

don't concatenate parameter values, you better use parameters

不要连接参数值,最好使用参数

string sql2 = @"INSERT INTO registerTable (username,password,email,firstname,gw2user,typeofplay, dateColumnName) VALUES (@username,@password,@email,@firstname,@gw2user,@typeofplay, @date)";

Read Working with Parameters

阅读使用参数

then you can set date parameter value as below

然后你可以设置日期参数值如下

cmd.Parameters.AddWithValue("@date", date);

do the same for other parameters as well.

对其他参数也这样做。

#3


0  

string sql2 = @"INSERT INTO registerTable (username,password,email,firstname,gw2user,typeofplay, dateColumnName) VALUES (@username,@password,@email,@firstname,@gw2user,@typeofplay, @date)";