1

我有一个表单,用户可以在其中插入、查看和更新​​数据。数据插入只进行一次,然后可以进行多次更新。默认情况下,如果数据存在于数据库中,用户将能够查看数据。

我试过了,但它没有插入数据库。然后假设数据库中存在数据,当用户想要更新记录时,它会抛出一个错误——DataReader 已打开。

   private void display_Emp()
    {
        try
        {
            using (sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
            {
                sqlCon.Open(); 

                SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Employee", sqlCon);
                DataSet ds = new DataSet("Employee");
                da.Fill(ds, "Employee");
                int x = 0;
                for (x = 0; x < ds.Tables[0].Rows.Count; x++)
                {
                    txtID.Text = ds.Tables[0].Rows[x][1].ToString();
                    txtEmpName.Text = ds.Tables[0].Rows[x][2].ToString();
                }
            }
        }
        catch(Exception exx) {
            MessageBox.Show(exx.Message);
        }
        finally {
            sqlCon.Close();
        }
    }

private void btnSave_Click(object sender, EventArgs e)
{
    try 
    {
        using (sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
        {
            sqlCon.Open();
            SqlCommand com = new SqlCommand("SELECT * FROM Employee", sqlCon);

            read = com.ExecuteReader(); 

            while (read.Read())
            {                     
                if (read.HasRows) 
                {
                    SqlCommand update = new SqlCommand("UPDATE Employee SET EmpID = '" + txtID.Text + "' , EmpName = '" + txtEmpName.Text + "', sqlCon);
                    update.ExecuteNonQuery();
                    MessageBox.Show("Employee details updated!", "Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    SqlCommand comm = new SqlCommand("INSERT INTO Employee(EmpID, EmpName) VALUES ('" + txtID.Text + "','" + txtEmpName.Text + "')", sqlCon);
                    comm.ExecuteNonQuery();
                    MessageBox.Show("Employee details saved!", "Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }
    catch(Exception ex) 
    {
       MessageBox.Show(ex.Message);
    }
    finally 
    {
        read.Close();
        sqlCon.Close();
    }                   
}

编辑:

表:- Deepz(ID int PK,Goodname varchar(50))

DECLARE @ID int 
DECLARE @Goodname varchar(50) 

    MERGE Deepz t
    USING (SELECT @ID[ID], @Goodname[Goodname]) s 
        ON (t.ID = s.ID)
    WHEN MATCHED THEN
        UPDATE
        SET t.Goodname = @Goodname
    WHEN NOT MATCHED THEN
        INSERT (ID, Goodname)
        VALUES (@ID, @Goodname);

错误:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 't'.
Msg 137, Level 15, State 2, Line 2
Must declare the scalar variable "@ID".
4

3 回答 3

3

您应该将保存功能更改为:

  • 如果您使用的是 SQL Server 2008 或更高版本,请使用SQL Merge语句根据记录是否存在来插入或更新
    DECLARE @nameField VarChar(50) = '一些数据'

    合并 dbo.MyTable t
    USING (SELECT @nameField [field])
        ON t.myData = s.field
    当匹配然后
        更新
        SET t.myData = @nameField
    当不匹配时
        插入(我的数据)
        值(@nameField);
  • 如果您使用的是 SQL Server 2005 或更早版本,则需要使用类似下面的内容,但您可能会遇到竞争条件(但恕我直言,您的原始设计仍然会比您的原始设计更好,因为原始设计也可能存在竞争条件)所以根据您的环境,您可能需要玩锁等
    如果存在(选择 * 从 Deepz WHERE [ID] = @ID)
    开始
        更新 Deepz
        设置好名字 = @好名字
        在哪里 [ID] = @ID
    结尾
    别的
    开始
        插入 Deepz(ID,Goodname)
        价值观(@ID,@Goodname);
    结尾
  • 使用 sql 参数而不是通过连接来构建语句,将使您免受SQL 注入攻击
    UPDATE Employee SET EmpID = @id, EmpName = @name

然后

    SqlCommand comm = new SqlCommand(...);
    // 注意下面有点简化,实际上你应该做 int.TryParse
    comm.Parameters.Add(@id, SqlDbType.Int).Value = int.Parse(txtID.Text);
于 2013-06-25T18:01:03.340 回答
0

这有点像在黑暗中拍摄,但是,试试这个:

private void btnSave_Click(object sender, EventArgs e)
{
   try 
   {
      using (sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
      {
         sqlCon.Open();
         SqlCommand com = new SqlCommand("SELECT * FROM Employee", sqlCon);
         com.Parameters.AddWithValue(@empID, SqlDbType.Int).Value = int.Parse(txtID.Text);  // Add this line
         com.Parameters.AddWithValue(@empName, SqlDbType.NVarChar).Value = txtEmpName.Text; // Add this line too
         SqlDataReader read = new SqlDataReader();  // You also need to 'new' up your SqlDataReader.
         read = com.ExecuteReader(); 

         while (read.Read())
         {                     
            if (read.HasRows) 
            {
            SqlCommand update = new SqlCommand("UPDATE Employee SET EmpID = @empID, EmpName = @empName", sqlCon);
            update.ExecuteNonQuery();
            MessageBox.Show("Employee details updated!", "Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }

             else
             {
                SqlCommand comm = new SqlCommand("INSERT INTO Employee(EmpID, EmpName) VALUES (@empID, @empName)", sqlCon);
                comm.ExecuteNonQuery();
                MessageBox.Show("Employee details saved!", "Employee", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
         }
    }

    catch(Exception ex) 
    {
        MessageBox.Show(ex.Message);
    }

    finally 
    {
        read.Close();
        sqlCon.Close();
    }
}
于 2013-06-25T18:24:21.110 回答
0

从示例中,我看到“If”条件和“While”条件看起来像是倒置的。

http://msdn.microsoft.com/en-us/library/haa3afyz%28v=vs.80%29.aspx

您首先检查是否有行,然后对其进行迭代

于 2013-06-25T18:31:11.033 回答