我有一个用于在同一个ExecuteScalar命令中一起检查2条记录的problam。
我想在我的本地数据库的不同列中同时搜索同一行中的2条记录,我试着在下面的代码中执行,但只有当我在1条件下执行它就可以了,但我想在2个条件同时,在同一行。
这是我的代码,当我在一个循环中,每次检查我的DataGridView中的每一行,如果它等于我的本地数据库:
private void button3_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\john\Documents\Visual Studio 2015\Projects\Project\Project\DB.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) from ResultsTable where TagNumber=@TagNumber AND Date=@Date", con))
{
con.Open();
string smdt1 = row.Cells["Exposure Date"].Value.ToString();
string format1 = "dd.MM.yyyy";
DateTime dt1 = DateTime.ParseExact(smdt1, format1, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
sqlCommand.Parameters.AddWithValue("@Date", dt1);
sqlCommand.Parameters.AddWithValue("@TagNumber", row.Cells["Device #"].Value);
int userCount = (int)sqlCommand.ExecuteScalar();
if (userCount > 0)
{
MessageBox.Show("found!");
}
else
{
MessageBox.Show("not found!");
}
}
}
}
日期广播只是为了获得像23.05.2015这样的日期,我想把它转换为数据库的日期类型,如23/05/2015。 我只想检查同一行中2条记录的副本
(同一个表中的2个主键) 在插入它们之前。
答案 0 :(得分:0)
在sqlcommand之后添加此
IDataReader reader = cm.ExecuteReader();
while (reader.Read())
{
if (reader.GetValue(0) != 0)
// your Code
}