2014年7月13日 星期日

[RESOLVED] Sql insert/update using parameters


Hi


I am trying to use the insert/update commande through using @parameters


Can anyone please guide me through how or refer me to a good tutorial?


Regards




In ADO.NET, any SQL query, regardless of whether it is an INSERT, UPDATE, SELECT or whatever else uses named parameters the same way:


String myQuery = "WHATEVER SQL QUERY USING @parameter1 AND @parameter2";
SqlCommand command = new SqlCommand(myQuery, myConnection);
command.Parameters.Add("@parameter1", someValue1);
command.Parameters.Add("@parameter2", someValue2);

Parameters is a collection of the Command class, so you can add as many as you need.  The only difference is how you execute:


//For SELECTS, you can create a DataReader
DataReader dr = command.ExecuteReader();

//For INSERT/UPDATE you can use ExecuteScalar
command.ExecuteScalar();

That should get you started.







AceCorban



Any SQL query, regardless of whether it is an INSERT, UPDATE, SELECT or whatever else uses named parameters the same:
String myQuery = "WHATEVER SQL QUERY USING @parameter1 AND @parameter2";
SqlCommand command = new SqlCommand(myQuery, myConnection);
command.Parameters.Add("@parameter1", someValue1);
command.Parameters.Add("@parameter2", someValue2);

Parameters is a collection of the Command class, so you can add as many as you need.  The only difference in ADO.NET is how you execute:


//For SELECTS, you can create a DataReader DataReader dr = command.ExecuteReader(); //For INSERT/UPDATE you can use ExecuteScalar command.ExecuteScalar();

That should get you started.




Thanks for the answer


So assuming a table (Customers) and two columns in the table names CustomerName and ContactName


would this commande be right to insert the values in two textboxes to the table?


String SqlQuery= "INSERT INTO Customers USING @CustomerName, @ContactName";

SqlCommand cmd= new SqlCommand(SqlQuery, CS);

cmd.Parameters.Add("@ConsumerName", TextBox1.text);

cmd.Parameters.Add("@ContactName", TextBox2.text);

cmd.ExecuteScalar();









I believe the query itself is


INSERT INTO Customers (CustomerName, ContactName) VALUES(@customerName, @contactName)

But yeah, the rest of the code looks right.


沒有留言:

張貼留言