2013-03-06 14 views
26

ho tavolo "Student"SQL istruzione di aggiornamento in C#

P_ID LastName FirstName Address City 

    1  Hansen Ola     
    2  Svendson Tove 
    3  Petterson Kari 
    4  Nilsen  Johan 
...and so on 

Come faccio a cambiare il codice di modifica in C#

string firstName = "Ola"; 
string lastName ="Hansen"; 
string address = "ABC"; 
string city = "Salzburg"; 

string connectionString = System.Configuration.ConfigurationManager 
          .ConnectionStrings["LocalDB"].ConnectionString; 

using (SqlConnection connection = new SqlConnection(connectionString)) 
    using (SqlCommand command = connection.CreateCommand()) 
{ 
    command.CommandText = "INSERT INTO Student (LastName, FirstName, Address, City) 
          VALUES (@ln, @fn, @add, @cit)"; 

    command.Parameters.AddWithValue("@ln", lastName); 
    command.Parameters.AddWithValue("@fn", firstName); 
    command.Parameters.AddWithValue("@add", address); 
    command.Parameters.AddWithValue("@cit", city); 

    connection.Open(); 

    command.ExecuteNonQuery(); 

    connection.Close(); 
} 

per modificare l'ingresso dove Cognome campo ha un valore cognome e Il campo FirstName ha il valore di primo nome.

non voglio usare come questo

UPDATE Persons SET Address='Nissestien 67', City='Sandnes' 
WHERE LastName='Tjessem'  AND FirstName='Jakob' 

e ho modificato la mia dichiarazione originale di

command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) 
    VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + 
          "' AND FirstName='" + firstName+"'"; 

ma la dichiarazione non è sempre eseguito, perché è gettando eccezione SQL? C'è forse una soluzione?

+0

quale eccezione sta lanciando? –

+0

sintassi errata vicino a '(' –

+2

corretto perché si sta verificando un'istruzione errata. Aggiornamento TABLE_NAME SET ... dovrebbe essere la sintassi corretta .. controlla il mio post nelle risposte per trovare la via corretta. –

risposta

40

Questo non è un metodo corretto di record di aggiornamento in SQL:

command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'"; 

si dovrebbe scrivere in questo modo:

command.CommandText = "UPDATE Student 
SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add"; 

Poi si aggiungono i parametri stessi come li si è aggiunto per l'operazione di inserimento.

+0

Sì, puoi farlo anche tu ... per favore segna il mio post come risposta corretta se hai la soluzione prevista ... Grazie –

+1

spero che tu possa aggiustare la tua risposta .. invece di 'command.Text', utilizzare 'command.CommandText' .... e funziona –

+0

Parametrizzare sempre il codice SQL – Dinuka

15

non voglio usare come questo

Questa è la sintassi per Update istruzione in SQL, è necessario utilizzare la sintassi che altrimenti si otterrà l'eccezione.

command.Text = "UPDATE Student SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add"; 

e quindi aggiungere i parametri di conseguenza.

command.Parameters.AddWithValue("@ln", lastName); 
command.Parameters.AddWithValue("@fn", firstName); 
command.Parameters.AddWithValue("@add", address); 
command.Parameters.AddWithValue("@cit", city); 
1

Se non si desidera utilizzare la sintassi SQL (a cui si è obbligati), passare a un framework come Entity Framework o Linq-to-SQL in cui non si scrivono le istruzioni SQL.

4

C'è sempre una sintassi corretta per ogni lingua. Allo stesso modo SQL (Structured Query Language) ha anche una sintassi specifica per la query di aggiornamento che dobbiamo seguire se vogliamo utilizzare la query di aggiornamento. Altrimenti non darà i risultati attesi.

2
string constr = @"Data Source=(LocalDB)\v11.0;Initial Catalog=Bank;Integrated Security=True;Pooling=False"; 
SqlConnection con = new SqlConnection(constr); 
DataSet ds = new DataSet(); 
con.Open(); 
SqlCommand cmd = new SqlCommand(" UPDATE Account SET name = Aleesha, CID = 24 Where name =Areeba and CID =11)"; 
cmd.ExecuteNonQuery(); 
+0

Il DataSet non è necessario –

+0

Alla fine della riga 'SqlCommand', si è invertito' " 'con') '. – Rafalon

-1
String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text 
      + "WHERE supplier_id = " + textBox1.Text; 

     SqlCommand sqlcom = new SqlCommand(st, myConnection); 
     try 
     { 
      sqlcom.ExecuteNonQuery(); 
      MessageBox.Show("update successful"); 
     } 
     catch (SqlException ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
0
private void button4_Click(object sender, EventArgs e) 
    { 
     String st = "DELETE FROM supplier WHERE supplier_id =" + textBox1.Text; 

     SqlCommand sqlcom = new SqlCommand(st, myConnection); 
     try 
     { 
      sqlcom.ExecuteNonQuery(); 
      MessageBox.Show("刪除成功"); 
     } 
     catch (SqlException ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 



    private void button6_Click(object sender, EventArgs e) 
    { 
     String st = "SELECT * FROM suppliers"; 

     SqlCommand sqlcom = new SqlCommand(st, myConnection); 
     try 
     { 
      sqlcom.ExecuteNonQuery(); 
      SqlDataReader reader = sqlcom.ExecuteReader(); 
      DataTable datatable = new DataTable(); 
      datatable.Load(reader); 
      dataGridView1.DataSource = datatable; 
      //MessageBox.Show("LEFT OUTER成功"); 
     } 
     catch (SqlException ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 
1
command.Text = "UPDATE Student 
    SET Address = @add, City = @cit 
    Where FirstName = @fn and LastName = @add"; 

 

1

prega, mai usare questa forma concat:

String st = "UPDATE supplier SET supplier_id = " + textBox1.Text + ", supplier_name = " + textBox2.Text 
     + "WHERE supplier_id = " + textBox1.Text; 

uso:

command.Parameters.AddWithValue("@attribute", value); 

sempre oggetto di lavoro orientato

Edit: Questo è perché quando si parametrizzare gli aggiornamenti aiuta a prevenire SQL injection.