简体   繁体   English

如何将数据插入到 SQL Server

[英]How to insert data into SQL Server

What the problem on my coding?我的编码有什么问题? I cannot insert data to ms sql.. I'm using C# as front end and MS SQL as databases...我无法将数据插入 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;
}

You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid SQL Injection .您必须设置 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();
       }
     }

I think you lack to pass Connection object to your command object.我认为您缺乏将Connection对象传递给您的command对象。 and it is much better if you will use command and parameters for that.如果您为此使用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();
        }
    }
}
string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM