将smalldatetime插入SQL Server

时间:2014-09-28 07:52:13

标签: c# sql-server

我正在尝试将日期插入SQL Server中的smalldatetime

我尝试这样的事情:

DateTime  transfer_date;
transfer_date = DateTime.Now;

SQL = "insert into MyTbl (DateT) values (transfer_date)";

SqlCommand Cmd_SQL = new SqlCommand(SQL, Conn_SQL);
Cmd_SQL.CommandText = SQL;
Cmd_SQL.ExecuteNonQuery();

但是我收到了这个错误:

  

将varchar数据类型转换为smalldatetime数据类型会导致超出范围的值。声明已经终止。

2 个答案:

答案 0 :(得分:5)

您需要定义参数化查询,然后设置参数值 - 如下所示:

// define SQL statement to use, with a parameter
string sqlStmt = "insert into dbo.MyTbl (DateT) values (@transferDate)";

// define connection and command objects
using (SqlConnection conn = new SqlConnection(your-connection-string-here))
using (SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
    // add parameter and set value
    cmd.Parameters.Add("@transferDate", SqlDbType.SmallDateTime).Value = DateTime.Now;

    // open connection, execute SQL query, close connection
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}    

答案 1 :(得分:0)

您目前根本没有对transfer_date变量做任何事情。您的SQL语句包含文本 transfer_date,但它不会自动从数据库中获取值。你想要这样的东西:

// @transfer_date is now a *parameter*.
string sql = "insert into MyTbl (DateT) values (@transfer_date)";

// Avoid using a shared connection - it'll cause problems. Let the connection
// pooling do its job. But use using statements to ensure that both the connection
// and the statement are disposed.
using (var connection = new SqlConnection(...))
{
    connection.Open();
    using (var command = new SqlCommand(sql, connection))
    {
        // No need to set the CommandText value now - it's already set up above.
        // But we need to set the value of the parameter.
        command.Parameters.Add("@transfer_date", SqlDbType.SmallDateTime).Value
             = DateTime.Now;
        command.ExecuteNonQuery();
    }
}