繁体   English   中英

在SQL Server中插入smalldatetime

[英]Insert a smalldatetime into 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数据类型的转换导致值超出范围。 该语句已终止。

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

// 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();
}    

您目前根本没有对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();
    }
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM