我有代码可以在用户更新ID字段时检查唯一值,但是我太新了,我想知道是否有更好的方法。
private void tbPrinterID_Validating(object sender, CancelEventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.LazerMaintenance_Conn))
{
try
{
string query = "SELECT COUNT(*) as Count FROM Printers WHERE PrinterID = '" + tbPrinterID.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
DataTable dt = new DataTable();
da.Fill(dt);
if ((Int32)dt.Rows[0]["Count"] > 0)
{
MessageBox.Show("There is already a printer with ID = " + tbPrinterID.Text);
}
}
catch (Exception ex)
{
MessageBox.Show("Error occured! : " + ex);
}
}
}
答案 0 :(得分:1)
您的示例容易受到SQL注入的攻击,我建议阅读此What are good ways to prevent SQL injection?。
您可以使查询更加惯用:
create table if not exists tblNumbers
location 'hdfs_location' as
select 1 as num
union all
select 2 as num
....