我想创建一个可以为特定人员计算的命令

时间:2013-09-08 14:07:08

标签: c# sql-server

我有一个可以计算逾期书籍的命令,但我只想在特定人员中使用它。 我的命令是在表Borrowbook中插入罚款。我还将代码放在datagridview将显示数据的按钮中。 我的代码是这样的:

SqlConnection con = new SqlConnection(constring);
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT  [Student ID], ISBN, Title, Date, [Due Date], Penalty FROM    Borrowbook;", con);


        try
        {
            SqlDataAdapter sda = new SqlDataAdapter();
            sda.SelectCommand = cmd;
            DataTable Records = new DataTable();
            sda.Fill(Records);
            BindingSource bsource = new BindingSource();

            bsource.DataSource = Records;
            dataGridView1.DataSource = bsource;
            sda.Update(Records);


        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message);
        }
        if (dateTimePicker2.Value < DateTime.Now)
        {
            cmd.CommandText = "INSERT INTO Borrowbook (Penalty) VALUES  (@Penalty)";
            SqlParameter p1 = new SqlParameter("@Penalty", SqlDbType.Int);
            p1.Value = 50;
            cmd.Parameters.Add(p1);
            cmd.ExecuteNonQuery();

1 个答案:

答案 0 :(得分:0)

您的更新借记记录(已经存在于表格中)的命令应该包含学生证和逾期退还书籍的ISBN

  cmd.CommandText = "UPDATE Borrowbook SET Penalty = @Penalty " + 
                    "WHERE [Student ID] = @stuid AND ISBN = @isbn";
  cmd.Parameters.AddWithValue("@Penalty", 50);
  cmd.Parameters.AddWithValue("@stuid", GetStudentID());
  cmd.Parameters.AddWithValue("@isbn", GetISBN());
  cmd.ExecuteNonQuery();

当然,您需要从网格中提取参数学生ID和ISBN的值(我想从当前选定的行中提取)

例如

 public int GetStudentID()
 {
     // The Student ID is the first cell of the current row
     int Row = dataGridView1.CurrentRow.Index;
     return Convert.ToInt32(dataGridView1[0,Row].Value);
 }

 public string GetISBN()
 {
     // The ISBN is the second cell of the current row
     int Row = dataGridView1.CurrentRow.Index;
     return dataGridView1[1,Row].Value.ToString();
 }

在上面的示例中,我使用AddWithValue方法将参数及其值添加到命令对象中。此方法很方便,因为您可以使用一行代码执行所有操作,但请注意AddWithValue通过查看传入的值的数据类型来确定参数的数据类型。如果您的数据库字段和参数不匹配,则可以得到错误或错误的转换。此外,AddWithValue的性能低于参数及其数据类型的显式声明。 Look at this very detailed article更深入地了解参数传递

相关问题