How to insert data into SQL Server

前端 未结 3 1570
闹比i
闹比i 2020-12-01 05:23

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...

name = tbName.Text;
userId = tbStaffId.         


        
相关标签:
3条回答
  • 2020-12-01 06:07

    I think you lack to pass Connection object to your command object. and it is much better if you will use command and parameters for that.

    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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 06:08

    You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid 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();
           }
         }
    
    0 讨论(0)
  • 2020-12-01 06:08
    string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
    cmd = new SqlCommand(saveStaff,con);
    cmd.ExecuteNonQuery();
    
    0 讨论(0)
提交回复
热议问题