473,406 Members | 2,956 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

SQL Parameters Not Affecting SqlCommand (C#)

42
Assume an SqlCommand object with a valid connexion and SQL command of:
Expand|Select|Wrap|Line Numbers
  1. UPDATE Company
  2. SET Web = @website
  3. WHERE ID = @companyID
There exists a button on a form page that acts as a 'Submit': when clicked, the SQL update is executed and the user is sent back to a profile to view changes:
Expand|Select|Wrap|Line Numbers
  1. sqlCommand1.Parameters["@website"].Value = website.Text; // a TextBox value
  2. sqlCommand1.Parameters["@companyID"].Value = companyID;
  3.  
  4. sqlCommand1.Connection.Open();
  5. sqlCommand1.ExecuteNonQuery();
  6.  
  7. Response.Redirect("details.aspx?id=" + companyID);
  8.  
These parameters are listed in the collection menu of sqlCommand1. When this code is tried, though, no changes occur in the database. I'm out of ideas what could be wrong; I've always had bad relations with SqlParameter.

Thanks!
Nov 12 '07 #1
20 7383
Plater
7,872 Expert 4TB
What does your stored procedure look like?
It seems like you should be getting an exception if something was very wrong.
BUT it's also possible if something goes wrong with the WHERE clause it will fail without an error.
Nov 12 '07 #2
nateraaaa
663 Expert 512MB
Where are you setting the query to be executed by your sqlcommand?

Expand|Select|Wrap|Line Numbers
  1. SqlConnection conn = new SqlConnection("dbconnectionstring");
  2. conn.Open();
  3.  
  4. SqlCommand cmd = new SqlCommand();
  5. cmd.Connection = "your database connection";
  6. cmd.CommandType = CommandType.StoredProcedure;
  7. cmd.CommandText = "your update query or stored proc name";
  8.  
  9. cmd.Parameters.Add("@website", SqlDbType.VarChar, 50);
  10. cmd.Parameters.Add("@CompanyID", SqlDbType.Int);
  11.  
  12. cmd.ExecuteNonQuery();
Give this a try.

Nathan
Nov 12 '07 #3
spamguy
42
What does your stored procedure look like?
It seems like you should be getting an exception if something was very wrong.
BUT it's also possible if something goes wrong with the WHERE clause it will fail without an error.
Not sure I understand what you mean about the stored procedure. Isn't that what I supplied? (And as it applies to SQL, of course, there isn't one, being a simple query.)

It's unlikely something's wrong with the WHERE clause. Note that Response.Redirect() depends on the same variable @companyID does to be forwarded properly.
Nov 12 '07 #4
nateraaaa
663 Expert 512MB
You can create a stored procedure that executes the simple update query above.
Nov 12 '07 #5
spamguy
42
You can create a stored procedure that executes the simple update query above.
In SQL? Sure, I could, but why? Queries don't much simpler than this. I tend to reserve stored procedures for the heavy-hitting processes.

Perhaps you all are being confused by the fact I'm using SqlConnection and SqlCommand objects in VS' Design pane instead of establishing the connexion programmatically?
Nov 12 '07 #6
Plater
7,872 Expert 4TB
What I am thinking is your executing this literally
"UPDATE Company SET Web = @website WHERE ID = @companyID"
And your parameters aren't being added in because they are not being added correctly?

I've only used parameters on stored procedures, but I'm pretty sure they CAN be used on inline commands, just more like this maybe?
"UPDATE Company SET Web = %1 WHERE ID = %2"
Nov 12 '07 #7
spamguy
42
Where are you setting the query to be executed by your sqlcommand?

Expand|Select|Wrap|Line Numbers
  1. SqlConnection conn = new SqlConnection("dbconnectionstring");
  2. conn.Open();
  3.  
  4. SqlCommand cmd = new SqlCommand();
  5. cmd.Connection = "your database connection";
  6. cmd.CommandType = CommandType.StoredProcedure;
  7. cmd.CommandText = "your update query or stored proc name";
  8.  
  9. cmd.Parameters.Add("@website", SqlDbType.VarChar, 50);
  10. cmd.Parameters.Add("@CompanyID", SqlDbType.Int);
  11.  
  12. cmd.ExecuteNonQuery();
Give this a try.

Nathan
Tried this, but no difference. I had to tweak the code because the parameters remained undefined, so both parameter lines became '...).Value = *value*;'
Nov 12 '07 #8
nateraaaa
663 Expert 512MB
Tried this, but no difference. I had to tweak the code because the parameters remained undefined, so both parameter lines became '...).Value = *value*;'
Try wrapping the code that I sent you into a try catch finally block.

Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3. //sqlcode that I posted
  4. }
  5. catch(Exception ex)
  6. {
  7. string message = ex.Message.ToString();
  8. }
  9. finally
  10. {
  11. cmd.Dispose();
  12. conn.Dispose();
  13. }
Run the debugger. If there is a problem executing the sql code the code will fall into the catch block. You can hover over ex or hover over message to see what error occurred.
Nov 12 '07 #9
spamguy
42
Try wrapping the code that I sent you into a try catch finally block.

Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3. //sqlcode that I posted
  4. }
  5. catch(Exception ex)
  6. {
  7. string message = ex.Message.ToString();
  8. }
  9. finally
  10. {
  11. cmd.Dispose();
  12. conn.Dispose();
  13. }
Run the debugger. If there is a problem executing the sql code the code will fall into the catch block. You can hover over ex or hover over message to see what error occurred.
I'll certainly give that a shot, though I can't run the debugger...it's a component of the development server no one bothered to set up. X-/ Plus I'd have get my computer added to Debugger Users. I'll have to pull a Response.Write or alert().

-----

UPDATE: I tacked on a Label and sent 'message' to that in lieu of a debugger. Result: No exceptions.
Nov 12 '07 #10
Plater
7,872 Expert 4TB
What if you just tried:
"UPDATE Company SET Web = 'http://www.google.com' WHERE ID = 2"
(Replace 2 with some number you're going to fudge with that you know exists)
And see if it works?
Nov 12 '07 #11
nateraaaa
663 Expert 512MB
Are you attaching to a development database where you could look at the values change in your table? First run your update query and make sure that the table will update with your query. Next run your sql command in your code and then check your table.
Nov 12 '07 #12
spamguy
42
What if you just tried:
"UPDATE Company SET Web = 'http://www.google.com' WHERE ID = 2"
(Replace 2 with some number you're going to fudge with that you know exists)
And see if it works?
That works. Since data was being pulled from the database using a static query to fill in TextBox fields, it's not unreasonable that it should work in reverse.
Nov 12 '07 #13
Plater
7,872 Expert 4TB
it's not unreasonable that it should work in reverse.
But that doesn't mean it does, are you remembering the single quote ' around the string data for the website?
Nov 12 '07 #14
spamguy
42
Are you attaching to a development database where you could look at the values change in your table? First run your update query and make sure that the table will update with your query. Next run your sql command in your code and then check your table.
Quite sure the table is updating properly. One of my first attempts was done whilst I was half-awake, so the query turned out SET Web = '@website', which set the cell to '@website'. It's been there ever since (minus the change to google.com, re: above post).

Urg, I wish there could be some intermediate way of printing the full query a la PHP...then it would be a snap to debug.
Nov 12 '07 #15
spamguy
42
Now this is interesting. If I assemble the query in a n00bish, asking-for-injection-attack way, it also does not update the Web field.

Expand|Select|Wrap|Line Numbers
  1. cmd.CommandText = "UPDATE Company SET Web = '" + website.Text + "' WHERE ID = " + companyID; // same response with website.Text.ToString()
  2. cmd.Connection.Open();
  3. cmd.ExecuteNonQuery();
  4.  
-----

UPDATE: I see what is happening now. If I dump website.Text to Label1, it shows website.Text contains the old contents of TextBox, not whatever was typed in over it. How odd. So, new question: how to circumvent this?
Nov 12 '07 #16
i appear to be having a similar problem:

Expand|Select|Wrap|Line Numbers
  1.             SqlCommand sqlComm;
  2.  
  3.             sqlComm = new SqlCommand("update T_Script_Master set sm_sql = @foo where sm_id = @bar", ConnPool.instance().getConn());
  4.  
  5.             sqlComm.Parameters.Add( new SqlParameter("@foo",SqlDbType.Text ));
  6.             sqlComm.Parameters.Add(new SqlParameter("@bar",SqlDbType.VarChar));
  7.  
  8.             sqlComm.Parameters["@foo"].Value = this.mSQL;            
  9.             sqlComm.Parameters["@bar"].Value = this.Guid;            
  10.  
  11.             sqlComm.ExecuteNonQuery();
  12.  
this code does Nothing. No exceptions, no data saved. In fact, with SQL Profiler running in the background, it appears that no statement is being executed at all.

note that doing it the dodgy way works fine, but im storing SQL statements in this database so i want to be able to escape the quotes etc. Irk, i cannot work this one out.
Nov 13 '07 #17
Plater
7,872 Expert 4TB
Why not just switch to stored procedures?

Then you could go:
Expand|Select|Wrap|Line Numbers
  1. SqlCommand sqlComm;
  2.  
  3. sqlComm = new SqlCommand("myUpdateProc", ConnPool.instance().getConn());
  4. sqlComm.CommandType=CommandType.StoredProcedure;//need to check on spelling for this, I wing'ed it
  5.  
  6. sqlComm.Parameters.Add( new SqlParameter("@foo",SqlDbType.Text ));
  7. sqlComm.Parameters.Add(new SqlParameter("@bar",SqlDbType.VarChar));
  8.  
  9. sqlComm.Parameters["@foo"].Value = this.mSQL;            
  10. sqlComm.Parameters["@bar"].Value = this.Guid;            
  11.  
  12. sqlComm.ExecuteNonQuery();
  13.  
Nov 13 '07 #18
spamguy
42
Why not just switch to stored procedures?

Then you could go:
Expand|Select|Wrap|Line Numbers
  1. SqlCommand sqlComm;
  2.  
  3. sqlComm = new SqlCommand("myUpdateProc", ConnPool.instance().getConn());
  4. sqlComm.CommandType=CommandType.StoredProcedure;//need to check on spelling for this, I wing'ed it
  5.  
  6. sqlComm.Parameters.Add( new SqlParameter("@foo",SqlDbType.Text ));
  7. sqlComm.Parameters.Add(new SqlParameter("@bar",SqlDbType.VarChar));
  8.  
  9. sqlComm.Parameters["@foo"].Value = this.mSQL;            
  10. sqlComm.Parameters["@bar"].Value = this.Guid;            
  11.  
  12. sqlComm.ExecuteNonQuery();
  13.  
That's worth trying later, but as I said, parameters are no longer the problem. See my last post.
Nov 13 '07 #19
spamguy
42
Another source helped me with the TextBox.Text issue. And I quote:

Take a look at your Page_Load event. This always fires *before* the
Click event. If you are reloading the textbox from the database inside
Page_Load, it will overwrite whatever the user typed before you can pick it
up in the update_Click event. If this is what is happening, you can use an
"if (!Page.IsPostBack)" inside Page_Load to avoid executing that part of the
code during the postback.
Nov 13 '07 #20
Plater
7,872 Expert 4TB
didn't even see that question.
Yeah, it's a pretty common trip-up to forget the isPostback deal.
Nov 13 '07 #21

Sign in to post your reply or Sign up for a free account.

Similar topics

6
by: simon | last post by:
Always when I need data reader in my programs, I simply have functions, which creates it for me: Dim rdr As SqlDataReader dim sql as string sql="myStoredProcedure" rdr =...
2
by: Grant Stanley | last post by:
I'm writing a database client program in C#, and it accesses a MS SQL V7 database. In one part of my program I am using a SqlCommand class to run a SQL Statement, the command text uses parameters,...
3
by: sck10 | last post by:
Hello, I have a stored procedure that requires 3 parameters. How do you add multiple parameters for a SqlConnection? Thanks, Steven Public strConn = "Data Source=MyServer;Initial...
1
by: Tom | last post by:
Hello guys Please have a look on following paragraph from ".NET Data Access Architecture Guide". ''''''''''' Although you can repeatedly use the same SqlCommand object to execute the same...
10
by: John Bailo | last post by:
I want to pass a SqlCommand object as a input parameter to a method. I want to pass the SqlCommand "by value" so that any updates to the original object are *not* reflected in the object within...
6
by: Nuzzi | last post by:
Hello All, I have two pages that are very similar. One is working, one is not. Here is the code for both: Page 1 (Working): protected void btn_update_Click(object sender, EventArgs e)...
4
by: =?Utf-8?B?Sm9uIEphY29icw==?= | last post by:
For MS SQL Server... I am used to declaring local variables in my SQL queries... Declare @MyInt int, @MyChar varchar(33) Parameters were idenfitied with a colon... Where ModDate :MyDate But,...
5
by: mnarewec | last post by:
Hi folks, I want to create a procedure where by it will take a sqlcommand, a string, and property. I want to use this procedure to add parameters to my sql command of type stored procedures since I...
2
by: DaveL | last post by:
Hello I want to build Dynamic Paramers for a Sql Insert below is what i have so far but...determinthe column type and length im having Problems with Tks dave string sInsert = "Insert into...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.