【问题标题】:How to insert data into SQL Server如何将数据插入 SQL Server
【发布时间】:2012-09-03 01:34:24
【问题描述】:

我的编码有什么问题?我无法向 ms sql 插入数据。我使用 C# 作为前端,使用 MS SQL 作为数据库...

name = tbName.Text;
userId = tbStaffId.Text;
idDepart = int.Parse(cbDepart.SelectedValue.ToString());

string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) " +
                   " VALUES ('" + name + "', '" + userId +"', '" + idDepart + "');";

SqlCommand querySaveStaff = new SqlCommand(saveStaff);

try
{
querySaveStaff.ExecuteNonQuery();
}
catch
{
//Error when save data

MessageBox.Show("Error to save on database");
openCon.Close();
Cursor = Cursors.Arrow;
}

【问题讨论】:

  • 您在tbStaffId 文本框中输入的22', 1); DELETE FROM tbl_staff; -- 没有完全正确。完成此操作后,请阅读 SQL 注入。
  • 感谢您的帮助..当我运行程序时,我得到了这个错误..“ExecuteNonQuery: Connection property has not been initialized.”
  • 拜托,请参数化这个!
  • 对不起......我是 C# 的新手......谁能解释一下,参数的功能是什么?

标签: c# sql sql-server


【解决方案1】:

您必须设置 Command 对象的 Connection 属性并使用参数化查询而不是硬编码 SQL 以避免SQL Injection

 using(SqlConnection openCon=new SqlConnection("your_connection_String"))
    {
      string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";

      using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))
       {
         querySaveStaff.Connection=openCon;
         querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;
         .....
         openCon.Open();

         querySaveStaff.ExecuteNonQuery();
       }
     }

【讨论】:

  • 谢谢我的朋友们...完成了!对不起,我是 C# 的新手...:)
  • 对不起......我是 C# 的新手......参数有什么功能?
  • @Chuki2:请注意,这个正确答案没有 try/catch 块,并且 确实using 块。你应该遵循这个例子。
  • 在 using 子句中的连接对象上不需要显式 Close()
  • .AddWithValue() 推荐。
【解决方案2】:

我认为您缺少将 Connection 对象传递给您的 command 对象。如果您为此使用commandparameters,那就更好了。

using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            // <== lacking
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
        command.Parameters.AddWithValue("@staffName", name);
        command.Parameters.AddWithValue("@userID", userId);
        command.Parameters.AddWithValue("@idDepart", idDepart);

        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // error here
        }
        finally
        {
            connection.Close();
        }
    }
}

【讨论】:

  • 对不起......我是 C# 的新手......参数有什么功能?
  • 我认为 finally 不是必需的,using 语句的目的是即使在出现异常msdn.microsoft.com/en-us/library/yh598w02.aspx 的情况下也能处理连接,我错过了什么吗?
【解决方案3】:
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();

【讨论】:

  • 这个是开放的SQL注入攻击。您应该使用 Command.Parameters 作为参数。
  • 避免这个例子。正如 S.L.Barth 提到的,这种做法对 SQL 注入开放
猜你喜欢
  • 1970-01-01
  • 2018-01-10
  • 2016-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
相关资源
最近更新 更多