发生此错误:“操作数类型冲突:位与日期不兼容”-我该如何解决?

问题描述 投票:0回答:1
SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\R.mdf;Integrated Security=True");

protected void Button1_Click(object sender, EventArgs e)
{
    // Open the database connection
    con.Open();

    // Create a SQL query string with parameters for the data to insert
    string query = "INSERT INTO drugs2 (ID, Science_name, Trade_name, Trade_name2, Trade_name3, End_date, Quantity, Price) VALUES (@Value1, @Value2, @Value3, @Value4, @Value5, @Value6, @Value7, @Value8)";

    // Create a new SqlCommand object using the query string and the SqlConnection object
    using (SqlCommand command = new SqlCommand(query, con))
    {
        DateTime datetime;

        // Add parameters to the SqlCommand object for the data to insert
        //DateTime mydatetime;
        command.Parameters.AddWithValue("@Value1", Convert.ToInt32( TextBox1.Text));
        command.Parameters.AddWithValue("@Value2", TextBox2.Text);
        command.Parameters.AddWithValue("@Value3", TextBox3.Text);
        command.Parameters.AddWithValue("@Value4", TextBox4.Text);
        command.Parameters.AddWithValue("@Value5", TextBox5.Text);
        command.Parameters.AddWithValue("@Value6", DateTime.TryParse(TextBox6.Text,out datetime));
        command.Parameters.AddWithValue("@Value7", Convert.ToInt32(TextBox7.Text));
        command.Parameters.AddWithValue("@Value8", Convert.ToInt32((TextBox8.Text)));

        // Execute the SQL query
        int rowsAffected = command.ExecuteNonQuery();

        // Check the number of rows affected by the query to ensure the insert was successful
        if (rowsAffected > 0)
        {
            // Insert was successful
            Response.Write("<script>alert('Add was successful')</script>");
        }
        else
        {
            // Insert failed
            Response.Write("<script>alert('Add failed')</script>");
        }
    }

    // Close the database connection
    con.Close();
}

我尝试将日期插入我的数据库,但发生了这个错误。

这是完整的错误:

操作数类型冲突:位与日期不兼容

第 46 行://command.ExecuteNonQuery();
第 47 行:// 执行 SQL 查询
第 48 行:int rowsAffected = command.ExecuteNonQuery();
第 49 行:

c# sql-server ado.net sqlclient
1个回答
0
投票

你将一个

bool
传递给一个
datetime
参数,因为
DateTime.TryParse
返回一个表示解析是否成功的
bool

command.Parameters.AddWithValue("@Value6", DateTime.TryParse(TextBox6.Text,out datetime));

相反,您应该在添加参数之前验证输入:

bool validEndDate = DateTime.TryParse(TextBox6.Text,out datetime);
if(!validEndDate)
{
    // show a message to the user and then ...
    return;
}

// here you can use datetime for the parameter
© www.soinside.com 2019 - 2024. All rights reserved.