我有一个数据库,用户可以跟踪进入商店的新模型,但是它们只保留每个模型中的一个,所以我不确定如何阻止用户重复相同的模型。我已经在该站点上看到一些以前的答案,但是当我自己使用代码时遇到错误。
private void check_Click(object sender, EventArgs e)
{
string query = "INSERT INTO tbl_phones(model) VALUES(@model)";
using (SqlConnection sqlconn = new SqlConnection(@""))
using (SqlCommand comm = new SqlCommand(query, sqlconn))
{
sqlconn.Open();
comm.Parameters.Add("@model, SqlDbType.NVarChar).Value = phoneinput.Text;
comm.ExecuteNonQuery();
答案 0 :(得分:1)
这应该可以工作(获取输入型号的电话的数量,如果少于一个,则插入)。
private void check_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO tbl_phones(model) VALUES(@model)";
string checkQuery = "SELECT COUNT(*) FROM tbl_phones WHERE model = @model";
using (SqlConnection sqlconn = new SqlConnection(@""))
{
sqlconn.Open();
SqlCommand checkCommand = new SqlCommand(checkQuery, sqlconn);
checkCommand.Parameters.AddWithValue("@model", phoneinput.Text);
if((int)checkCommand.ExecuteScalar() < 1)
{
SqlCommand insertCommand = new SqlCommand(insertQuery, sqlconn);
insertCommand.Parameters.AddWithValue("@model", phoneinput.Text);
insertCommand.ExecuteNonQuery();
}
}
}
编辑-如果您决定将模型设置为主键,则可以像这样捕获异常-
private void check_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO tbl_phones(model) VALUES(@model)";
using (SqlConnection sqlconn = new SqlConnection(connectionString))
{
sqlconn.Open();
SqlCommand insertCommand = new SqlCommand(insertQuery, sqlconn);
insertCommand.Parameters.AddWithValue("@model", "test");
try
{
insertCommand.ExecuteNonQuery();
}
catch(SqlException ex)
{
if (ex.Number == 2627)
{
// Phone already exists, do some stuff
}
else throw;
}
}
}