C#SqlCommands不起作用

C#SqlCommands不起作用,c#,asp.net,sql-server,ado.net,C#,Asp.net,Sql Server,Ado.net,我有一个问题,代码不起作用,我正在尝试填充保存在SQL Server上的localhost中的数据库,但代码没有执行任何操作:( 这段代码有多个问题,不幸的是,现有(现在已删除)的答案甚至都没有提到,更不用说帮助修复了 marc_警告过SQL注入风险 所有这些命令都必须位于事务内部 您正在使用like来获取学生id,但是您从列表框中获取姓名-那么为什么不将id作为ListBoxItem的值呢 在你可以借书之前,你必须先确保你至少还有一本书可以借 你在吞咽例外 您正在为SqlConnection

我有一个问题,代码不起作用,我正在尝试填充保存在SQL Server上的localhost中的数据库,但代码没有执行任何操作:(


这段代码有多个问题,不幸的是,现有(现在已删除)的答案甚至都没有提到,更不用说帮助修复了

  • marc_警告过SQL注入风险
  • 所有这些命令都必须位于事务内部
  • 您正在使用
    like
    来获取学生id,但是您从列表框中获取姓名-那么为什么不将id作为ListBoxItem的值呢
  • 在你可以借书之前,你必须先确保你至少还有一本书可以借
  • 你在吞咽例外
  • 您正在为
    SqlConnection
    使用类级变量,而
    SqlConnection
    最好用作using语句中的局部变量
  • 你把代码和显示混为一谈——这是不可能的,或者至少很难测试。可测试性是可维护性的一部分
  • 你的变量命名很糟糕。变量名应该是有意义的——这样当有人阅读代码时,他们可以通过读取变量名来了解变量的含义
  • try
    块中应该包含的唯一内容是实际的数据库访问。异常和
    try…catch
    块用于代码中无法测试或控制的内容
综上所述,这里有一个代码的改进版本,作为起点。请尝试进一步改进,以解决我上面列出的所有(或至少大部分)问题:

private void button2_Click(object sender, EventArgs e)
{
    if (dataGridView1.SelectedRows.Count != 0 && listBox1.SelectedIndex != -1)
    {            
        using(var con = new SqlConnection(connectionString))
        {
            var trn = con.BeginTransaction();
            var sqlGetStudentId = "select studentID from student where studentName = @studentName";   
            using(var cmd = new SqlCommand(sqlGetStudentId, conn))
            {
                cmd.Parameters.Add("@studentName", SqlDbType.VarChar).Value = listBox1.SelectedItem.ToString();
                try
                {
                    con.Open();
                    string studentId = cmd.ExecuteScalar()?.ToString();

                    if(!string.IsNullOrEmpty(studentId))
                    {
                        // Note: You must first check if there are books left to borrow!
                        cmd.CommandText = "update Book set quantity=quantity-1 where bookID = @BookId";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@BookId", SqlDbType.VarChar).Value = dataGridView1.CurrentRow.Cells[0].Value.ToString();
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = "insert into Borrow (/* Alwasy specify columns list! */) values (@IAmGuessingBookId, @StudentId, GETDATE(), NULL)";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@IAmGuessingBookId", SqlDbType.VarChar).Value = dataGridView1.CurrentRow.Cells[0].Value.ToString();
                        cmd.Parameters.Add("@StudentId", SqlDbType.VarChar).Value = studentId;
                        cmd.ExecuteNonQuery();

                        trn.Commit();
                    }
                }
                catch(Exception ex)
                {
                    // Do something with the exception!
                    // show an error description to the client,
                    // log for future analisys
                    trn.Rollback();
                }
            }
        }

    }
}

第一个
a.ExecuteNonQuery();
无需使用
reader.Read();
您不需要每次都使用新的命令。-您不应该将SQL语句串联在一起-使用参数化查询来避免SQL注入-签出定义“不工作”
private void button2_Click(object sender, EventArgs e)
{
    if (dataGridView1.SelectedRows.Count != 0 && listBox1.SelectedIndex != -1)
    {            
        using(var con = new SqlConnection(connectionString))
        {
            var trn = con.BeginTransaction();
            var sqlGetStudentId = "select studentID from student where studentName = @studentName";   
            using(var cmd = new SqlCommand(sqlGetStudentId, conn))
            {
                cmd.Parameters.Add("@studentName", SqlDbType.VarChar).Value = listBox1.SelectedItem.ToString();
                try
                {
                    con.Open();
                    string studentId = cmd.ExecuteScalar()?.ToString();

                    if(!string.IsNullOrEmpty(studentId))
                    {
                        // Note: You must first check if there are books left to borrow!
                        cmd.CommandText = "update Book set quantity=quantity-1 where bookID = @BookId";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@BookId", SqlDbType.VarChar).Value = dataGridView1.CurrentRow.Cells[0].Value.ToString();
                        cmd.ExecuteNonQuery();

                        cmd.CommandText = "insert into Borrow (/* Alwasy specify columns list! */) values (@IAmGuessingBookId, @StudentId, GETDATE(), NULL)";
                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@IAmGuessingBookId", SqlDbType.VarChar).Value = dataGridView1.CurrentRow.Cells[0].Value.ToString();
                        cmd.Parameters.Add("@StudentId", SqlDbType.VarChar).Value = studentId;
                        cmd.ExecuteNonQuery();

                        trn.Commit();
                    }
                }
                catch(Exception ex)
                {
                    // Do something with the exception!
                    // show an error description to the client,
                    // log for future analisys
                    trn.Rollback();
                }
            }
        }

    }
}