2017-06-06 108 views
0

首先,我允许用户输入组合框,以在有很多项目时快速搜索。我想知道如果我可以停止插入查询,如果用户不小心按下另外一个字母,它会导致空,我有try catch块,但它只显示错误消息,但主键跳过一个数字。如何避免主键在插入查询时自动增加?

选择专案编号,以填补组合框

private void GetProjectID() 
{ 
    newConnection.ConnectionM(); 
    SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand(); 
    cmd.CommandText = "Select * from Project where ProjectName='" + comboBoxProjectTitle.Text + "' "; 
    try 
    { 
     SqlDataReader reader = cmd.ExecuteReader(); 
     while(reader.Read()) 
     { 
      ProjectID = reader.GetInt32(0); 

     } 
     reader.Close(); 
     SqlConnectionOLTP.cn.Close(); 
    } 
    catch(Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
} 

插入到数据库:

SqlCommand cmd = SqlConnectionOLTP.cn.CreateCommand(); 
cmd.CommandText = "Insert into Cost(ProjectID,PropertyID,CostCategoryID,EstimatedAmount) values ('" + ProjectID + "','" + PropertyID + "','" + CostCatID + "'," + "'" + textBoxAmount.Text + "') "; 
cmd.ExecuteNonQuery(); 
SqlConnectionOLTP.cn.Close(); 
MessageBox.Show("Saved"); 
+3

seriousl验证码y:永远不会连接输入以创建SQL;即“数据库101” - 或者至少“105”(永远是OWASP#1(“A1”)*)。请请使用参数。 –

+2

“但主键跳过一个数字” - 那......不是问题;你不应该期望*主键都是连续的,而IMO试图“修复”这是一个非常糟糕的主意 - 那就是解决错误的问题;这里的*实际问题*是什么? –

回答

0
SET IDENTITY_INSERT <TableName> ON 
-- Do the inserting in the table with name <TableName> 
SET IDENTITY_INSERT <TableName> OFF 
0

运行在SSMS即SQL Server Management Studio中

ALTER TABLE [Project] DROP ProjectID 
    SET IDENTITY_INSERT <Project> OFF 
+0

@拒绝错误的代码行..现在它会工作 –