sqlcommand выполняет запрос, не обновляя удаление и вставку

Привет, я всегда использую SQlcommand для не запросов, но теперь что-то не так, я не знаю, что у меня есть 3 кнопки с операциями обновления, вставки и удаления, но я создал уникальный метод для всех 3 операций, проблема в том, что он не вставляет удаление или обновление:

private void operacao(String operacao) {
        String comando = "";
        con = new SqlConnection();
        WorksDataSet  dataset = new WorksDataSet();
        con.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Works.mdf;Integrated Security=True;User Instance=True;Asynchronous Processing=true";
        try
        {
            con.Open();

        }
        catch (SqlException cox) {
            MessageBox.Show(cox.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        switch (operacao) { 
            case "inserir":

                try
                {
                    comando = "Insert Into Estudante (Codigo,Nome,Apelido) values(" + txtID.Text + ",'" + txtNome.Text + "','" + txtapelido.Text + "')";
                    SqlCommand command = new SqlCommand(comando, con);
                    SqlDataAdapter sda=new SqlDataAdapter(command);
                    command.CommandType = CommandType.Text;
                    sda.Fill(dataset);
                    command.ExecuteNonQuery();
                    command.Dispose();
                    MessageBox.Show("Adicionado com Sucesso", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (SqlException sex) {
                    MessageBox.Show(sex.Message , this.Text,MessageBoxButtons.OK,MessageBoxIcon.Error );
                }

                break;

            case "apagar":
                comando = "delete from Estudante where Codigo=" + txtID;
                try
                {

                    SqlCommand command = new SqlCommand(comando, con);
                    command.BeginExecuteNonQuery();
                    MessageBox.Show("Removido com Sucesso", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (SqlException sex)
                {
                    MessageBox.Show(sex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                break;
            case "atualizar":
                comando = "update table Estudante set nome='" + txtNome + "'^ apelido='" + txtapelido + "'";
                try
                {

                    SqlCommand command = new SqlCommand(comando, con);
                    command.BeginExecuteNonQuery();
                    MessageBox.Show("Actualizado com Sucesso", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (SqlException sex)
                {
                    MessageBox.Show(sex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                break;
            default:
                break
                ;
        }
        con.Close();
    }

person Oldemiro Henry Williams Baloi    schedule 05.07.2012    source источник
comment
почему вы используете BeginExecuteNonQuery?   -  person emirc    schedule 05.07.2012
comment
вау.. поймать (SqlException секс) и MessageBox.Show(sex.Message... кажется интересным.. :)   -  person Dr. Rajesh Rolen    schedule 05.07.2012
comment
@Oldemiro: выдает ли он какое-либо исключение или не переходит в случай переключения, поскольку вы используете строку в случаях переключения. так пожалуйста, подтвердите..?   -  person Dr. Rajesh Rolen    schedule 05.07.2012
comment
Вы проверяли свои sql-выражения напрямую? (например, в студии управления sql)   -  person Tomtom    schedule 05.07.2012


Ответы (3)


Вы должны использовать параметризованный запрос. ВСЕГДА.....

это для вставки op.

comando = "Insert Into Estudante (Codigo,Nome,Apelido) values(@id, @nome, @apelido");
SqlCommand command = new SqlCommand(comando, con);                     
command.Parameters.AddWithValue("@id", txtID.Text);
command.Parameters.AddWithValue("@nome", txtNome.Text);
command.Parameters.AddWithValue("@apelido", txtapelido.Text);
command.CommandType = CommandType.Text;                     
command.ExecuteNonQuery(); 

Здесь нет необходимости использовать набор данных или адаптер данных. просто ExecuteNonQuery

это для удаления op.

comando = "delete from Estudante where Codigo=@id";
SqlCommand command = new SqlCommand(comando, con);
command.Parameters.AddWithValue("@id", txtID.Text);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();                     

Обратите внимание, что вы должны передавать свойство Text, а не весь TextBox

это для операции обновления

comando = "update table Estudante set nome=@nome, apelido=@apelido where codigo=@id";
SqlCommand command = new SqlCommand(comando, con);
command.Parameters.AddWithValue("@id", txtID.Text);
command.Parameters.AddWithValue("@nome", txtNome.Text);
command.Parameters.AddWithValue("@apelido", txtapelido.Text);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();                     

Здесь также используйте свойство Text, а не объект TextBox.

Таким образом, вам не нужно беспокоиться о кавычках в ваших строковых параметрах, и вы закроете дверь для
атак Sql Injection.

person Steve    schedule 05.07.2012
comment
Это правильно, но я не думаю, что это решает проблему :) - person Tomtom; 05.07.2012

Чтобы выполнить оператор insert/delete/update, вам просто нужно создать объекты SqlCommand и SqlConnection. DataSet и DataAdapter бесполезны.

Чтобы вставить строку:

string cnstr=@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Works.mdf;Integrated Security=True;User Instance=True;Asynchronous Processing=true";

using(SqlConnection con = new SqlConnection(cnstr))
 {
  string sql = "Insert Into Estudante (Codigo,Nome,Apelido) values(@Codigo,@Nome,@Apelido)";
  using(SqlCommand command= new SqlCommand(sql,con))
   {
     command.Parameters.Add("@Codigo",SqlDbType.Int).Value=txtID.Text;
     command.Parameters.Add("@Nome",SqlDbType.VarChar,30).Value=txtNome.Text;
     command.Parameters.Add("@Apelido",SqlDbType.VarChar,30).Value=txtapelido.Text;
     con.Open();
     cmd.ExecuteNonQuery();
     con.Close();
    }
 }
person kv-prajapati    schedule 05.07.2012
comment
ничего не происходит, когда я пытаюсь повторить запись, она генерирует sqlException, но когда я захожу в таблицу с проводником, ничего не изменяется; - person Oldemiro Henry Williams Baloi; 05.07.2012
comment
Выберите файл .mdf из обозревателя решений + откройте окна свойств, чтобы установить Copy To Output Directory=Copy if newer - person kv-prajapati; 06.07.2012
comment
try { comando = Insert Into Estudante (Codigo, Nome, Apelido) values(@ID, @Nome, @Apelido); Команда SqlCommand = новая SqlCommand (comando, con); command.Parameters.AddWithValue(@ID,txtID.Text); command.Parameters.AddWithValue(@Номер, txtNome.Text); command.Parameters.AddWithValue(@Apelido, txtapelido.Text); кон.Открыть(); command.CommandType = CommandType.Text; команда.ВыполнитьНеЗапрос(); кон.Закрыть(); MessageBox.Show(Дополнительно с успехом, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information); } - person Oldemiro Henry Williams Baloi; 06.07.2012

Вы вызываете метод Fill sqlDataAtapter для заполнения базы данных, которая не нужна. удалите это утверждение и посмотрите. Это должно сработать.

person 24x7Programmer    schedule 06.07.2012