SQL命令执行成功,但数据未插入WPF表单

时间:2016-08-09 12:02:15

标签: c# sql wpf

我在以WPF格式插入数据时遇到问题。代码中没有错误,查询运行成功但是当我检查我的数据库时没有数据。以下是代码:

 bool insert()
    {
        try
        {
            Connection.Open();
            string query = "Insert into checkouts(cnic,medicine,next_trip) VALUES('@c','@m','@n')";
            SqlCommand command = new SqlCommand(query, Connection);
            command.Parameters.AddWithValue("@c", cnic_box.Text.Replace("-",""));
            command.Parameters.AddWithValue("@m", med_box.Text);
            command.Parameters.AddWithValue("@n",Convert.ToDateTime(date_box.Text).ToString("yyyy-MM-dd"));
            command.ExecuteNonQuery();
            Connection.Close();
            return true;
        }
        catch (Exception ex)
        {
            Connection.Close();
            return false;
        }
    }

2 个答案:

答案 0 :(得分:0)

参数周围的引号很可能让你感到悲伤。尝试下面的代码,看看它是否更好。

try {
    Connection.Open();
    string query = "Insert into checkouts(cnic,medicine,next_trip) VALUES(@c,@m,@n)";
    SqlCommand command = new SqlCommand(query, Connection);
    command.Parameters.AddWithValue("@c", cnic_box.Text.Replace("-",""));
    command.Parameters.AddWithValue("@m", med_box.Text);
    command.Parameters.AddWithValue("@n",Convert.ToDateTime(date_box.Text).ToString("yyyy-MM-dd"));
    Connection.Close();
    return (command.ExecuteNonQuery() > 0);
}
catch (Exception ex)
{
    Connection.Close();
    return false;
}

修改

要显式提交数据,请尝试使用以下代码替换您的查询:

string query = "BEGIN TRANSACTION Insert into checkouts(cnic,medicine,next_trip) VALUES(@c,@m,@n) COMMIT TRANSACTION";

答案 1 :(得分:0)

从查询

中删除查询的VALUES部分中的单引号
bool insert()
{
    try
    {
        Connection.Open();
        string query = "Insert into checkouts(cnic,medicine,next_trip) VALUES(@c, @m, @n)";
        SqlCommand command = new SqlCommand(query, Connection);
        command.Parameters.AddWithValue("@c", cnic_box.Text.Replace("-",""));
        command.Parameters.AddWithValue("@m", med_box.Text);
        command.Parameters.AddWithValue("@n",Convert.ToDateTime(date_box.Text).ToString("yyyy-MM-dd"));
        command.ExecuteNonQuery();
        Connection.Close();
        return true;
    }
    catch (Exception ex)
    {
        Connection.Close();
        return false;
    }
}