将数据表结果与表单值进行比较

时间:2014-02-16 10:00:26

标签: c# winforms sqlite datatable

如何比较我的数据表返回的行与表单值的行,如果表单值不同,则MessageBox.Show("Would you like to update?");

这是我的代码:

DataTable dt = new DataTable();
SQLiteCommand command = m_dbConnection.CreateCommand();
command.CommandText = "select * from rdpdirectory where company = @company order by company asc";

command.Parameters.Add(new SQLiteParameter("@company", txtCompany.Text));
SQLiteDataAdapter db = new SQLiteDataAdapter(command);
db.Fill(dt);

DataColumn[] keyColumns = new DataColumn[1];
keyColumns[0] = dt.Columns["company"];
dt.PrimaryKey = keyColumns;

DataRow row = dt.Rows[0];

以下是我的文本框:

txtCompany.Text 
txtServer.Text 
txtUserName.Text 
txtPassword.Text 

编辑:我试过了: 我考虑过尝试:if (dt.Rows.Count > 0)但是当记录在数据库中时,它总会返回一行。我需要检查记录是否与表格值相比是相同还是差异。

1 个答案:

答案 0 :(得分:1)

您可以更改以下语句

select count(*) from rdpdirectory where company = @company and Server =@Server and UserName =@UserName and Password =@Password"

设置所有参数值,就像您为company

所做的那样

然后

int rowCount = Convert.ToInt32(cmd.ExecuteScalar());

如果rowCount等于1则表示您不需要更新记录

        using (SQLiteCommand command = m_dbConnection.CreateCommand())
        {
            command.CommandText = "select count(*) from rdpdirectory where company = @company and Server =@Server and UserName =@UserName and Password =@Password";
            command.Parameters.AddWithValue("@company", txtCompany.Text);
            command.Parameters.AddWithValue("@Server", txtServer.Text);
            command.Parameters.AddWithValue("@UserName", txtUserName.Text);
            command.Parameters.AddWithValue("@Password", txtPassword.Text);

            int rowCount = Convert.ToInt32(command.ExecuteScalar());
            if (rowCount <1)
            {
                MessageBox.Show("Would you like to update?");
            }
        }