I have this piece of code:
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = connection;
cmd.CommandText = "UPDATE S " +
"SET S.WebId = S.WebId + 1 " +
"OUTPUT DELETED.WebId " +
"FROM jcdSetting S";
SqlParameter parameter = cmd.Parameters.Add("#id", SqlDbType.Int);
parameter.Direction = ParameterDirection.Output;
int i = cmd.ExecuteNonQuery();
webId = Convert.ToInt32(cmd.Parameters["#id"].Value);
}
For some reason, the last line fails, the parameter I'm trying to access is always DbNull. I've tried the query in Management Studio and it returns the value just fine.
I've checked the return value of ExecureNonQuery and that as well returns 1 as expected. I'm totally lost here.
Any help would be appreciated.
Using the output within a update statement, is equivalent to a select, whereas from the code you've posted you're expecting it to come out in an output parameter named #id.
Where does #id come from? you haven't defined it anywhere.
output in the method that you've used it would return a rowset, not a scalar value.
Related
I have a simple query with a where clause that has no results when it is run from code.
This query works fine if it is ran from the SQL Server Management studio, but when i pass some variables that are taken from GET parameters this query will show no results.Request.QueryString["q"] is not NULL.Command.ExecuteReader(); executes fine.
Connection = new SqlConnection(ConnectionString);
Connection.Open();
Command = new SqlCommand("", Connection);
if (Request.QueryString["q"] != null)
{
Query = Request.QueryString["q"].ToString();
Command.CommandText = "SELECT * FROM [device] WHERE [display_name] LIKE N'%#query%' OR [address] LIKE N'%#query%' ";
Command.Parameters.AddWithValue("#query", Query);
Reader = Command.ExecuteReader();
while (Reader.Read())//Here Reader.HasRows=False
{
//Do Stuff
}
There is a single row in the table that has its [display_name] is equal to KHR and its [address] is equal to تست.
passing ?q=kh to the page, i get no result form this query where it actually should return a single row.
[display_name] LIKE N'%#query%' will search for a row where display_name contains the text '#query' not the value of the variable #query. C# doesn't inject the value of a parameter.
You need to do something like this:
Command.CommandText = "SELECT * FROM [device] WHERE [display_name] LIKE N'%' + #query + N'%' OR [address] LIKE N'%' + #query + N'%';";
Command.Parameters.Add("#query", SqlDbType.NVarChar, 50);
Command.Parameters["#query"].Value = Query;
Note I have also removed AddWithValue (Can we stop using AddWithValue Already?)
My application was working well but customer wanted me to add some features to it.
Now when I run the app any thing is working but by clicking a button that executes an insert query an exception occurs with this message:
The parameterized query '(#ID int,#Subj nvarchar(50),#Pic varbinary(8000),#LetDate date,#' expects the parameter '#Pic', which was not supplied.
what are those silly parentheses?
the code of this part of program:
conn.Open();
string sqlcmd = "Insert into Pictures (ID, Subj, Pic, LetDate, LetTitle) Values (#ID, #Subj, #Pic, #LetDate, #LetTitle)";
insertCommand = new SqlCommand(sqlcmd, conn);
// For image data, we save the bytes into the database. We save the image to the JPG format bytes.
insertCommand.Parameters.Add("ID", SqlDbType.Int).Value = (++lastID);
insertCommand.Parameters.Add("Subj", SqlDbType.NVarChar, 50).Value = textBox1.Text;
insertCommand.Parameters.Add("Pic", SqlDbType.VarBinary).Value = dynamicDotNetTwain1.SaveImageToBytes(lastIndex, Dynamsoft.DotNet.TWAIN.Enums.DWTImageFileFormat.WEBTW_JPG);
insertCommand.Parameters.Add("LetDate", SqlDbType.Date).Value = dateTimeSelector1.Value.Value.Date;
insertCommand.Parameters.Add("LetTitle", SqlDbType.NText).Value = titleTextBox1.Text;
index++;
int queryResult = insertCommand.ExecuteNonQuery();
if (queryResult == 1)
MessageBox.Show("تصویر با موفقیت در پایگاه داده ذخیره شد", "پیغام", MessageBoxButtons.OK, MessageBoxIcon.Information);
conn.Close();
This is an error occuring elsewhere in your program, and is unrelated to your stored procedure execution code.
The SQL error message "expects the parameter '#VariableName', which was not supplied." usually indicates that you are setting a parameter value to null. If you actually intend to pass NULL to the query, you have to use the DBNull.Value value. However, it looks like you are trying to pass an actual value. Thus, the source of your issue is this line:
insertCommand.Parameters.Add("Pic", SqlDbType.VarBinary).Value = dynamicDotNetTwain1.SaveImageToBytes(lastIndex, Dynamsoft.DotNet.TWAIN.Enums.DWTImageFileFormat.WEBTW_JPG);
If you can figure out why the dynamicDotNetTwain1.SaveImageToBytes() function is returning null and get that function working as expected, then you're stored procedure will work as expected.
I think you have forgot to put # infront of the variable names...
insertCommand.Parameters.Add("#ID", SqlDbType.Int).Value = (++lastID);
insertCommand.Parameters.Add("#Subj", SqlDbType.NVarChar, 50).Value = textBox1.Text;
insertCommand.Parameters.Add("#Pic", SqlDbType.VarBinary).Value = dynamicDotNetTwain1.SaveImageToBytes(lastIndex, Dynamsoft.DotNet.TWAIN.Enums.DWTImageFileFormat.WEBTW_JPG);
insertCommand.Parameters.Add("#LetDate", SqlDbType.Date).Value = dateTimeSelector1.Value.Value.Date;
insertCommand.Parameters.Add("#LetTitle", SqlDbType.NText).Value = titleTextBox1.Text;
I am a newbie in DB2 world and am using:
- DB2 Data Provider for .NET (IBM.Data.DB2.dll version 9.7.4.4)
- C# VS2010 with .NET Framework 4.0
I have problem with query that uses parameter.
My code snippet:
DB2Command cmd = new DB2Command();
cmd.CommandText = "SELECT COUNT(*) FROM CUSTOMERS t0 WHERE (t0.\"CITY\" < :p0)";
cmd.Connection = Db2Connection;
DB2Parameter param = cmd.CreateParameter();
param.DB2Type = DB2Type.VarChar;
param.ParameterName = ":p0";
param.Value = "Seattle";
var p = cmd.Parameters.Add(param);
var execResult = cmd.ExecuteScalar();
I get following error on cmd.ExecuteScalar():
The number of variables in the EXECUTE statement, the number of
variables in the OPEN statement, or the number of arguments in an OPEN
statement for a parameterized cursor is not equal to the number of
values required. SQLSTATE=07004
Please help how to fix the problem. Thank you in advance.
Additional information:
1. I just tried to use IBM Data Studio to verify the DB2 command using query editor. It doesn't recognize the prefix "#" for parameter. So I use oracle-liked prefix ":" for it. It works. But my C# code still raises the error [07004] SQL0313N
2. If I don't use any prefix for parameter on my C# code, I get ERROR [42703] [IBM][DB2/NT64] SQL0206N \"P0\" is not valid in this context.
Finally I find out 2 ways to fix the problem.
Using unnamed parameter "?" instead of parameter name ":p0".
DB2Command cmd = new DB2Command();
cmd.CommandText = "SELECT COUNT(*) FROM CUSTOMERS t0 WHERE (t0.\"CITY\" < ?)";
cmd.Connection = Db2Connection;
DB2Parameter param = cmd.CreateParameter();
param.DB2Type = DB2Type.VarChar;
param.ParameterName = "param1";
param.Value = "Seattle";
var p = cmd.Parameters.Add(param);
var execResult = cmd.ExecuteScalar();
Activate HostVarParameters property of class DB2ConnectionStringBuilder and the original code remains unchanged (keeping using named parameters).
My 2 cents,
Mag
I know how to use Text Box value in Access query for string fields, but i am unable to understand how to use it for int fields.
I am writing the following query and receiving error messages.
ERROR MESSAGE: No value given for one or more required parameters.
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " +textBox2.Text , conn);
conn.Open();
cmd.ExecuteNonQuery();
I also tried to convert textBox2 into int, but its also given me an error message.
Input string was not in a correct format.
int Id= Convert.ToInt16(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " + Id , conn);
conn.Open();
cmd.ExecuteNonQuery();
This answer corrects your problem
First, the TextBox for Name is not the same Textbox used for ID
Second, do not concatenate strings to build sql commands. It is very error prone and open to a well know sql vulnerability called Sql Injection
string queryText = Update Table1 Set Name= ? where ID= ?";
OleDbCommand cmd = new OleDbCommand(queryText, conn);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", Convert.ToInt32(TextBox2.Text));
conn.Open();
cmd.ExecuteNonQuery();
Here I have removed the string concatenation and inserted two parameters placeholders (?),
then I have added to the OleDbCommand two parameters and their values.
When executing the query the OleDb code will replace the placeholders with the actual values checking for invalid characters and invalid sql statements
How to use OdbcParameter for MySQL?
This is my current attempt:
command.Parameters.Add(new OdbcParameter("#username", username.Text));
command.Parameters.Add(new OdbcParameter("#password", password.Text));
command.CommandText = "INSERT INTO test.test (`user`,`password`) VALUES (#username,#password);";
command.ExecuteNonQuery();
but it seems to be not working. The database does create a new row, but it's values are NULL.
This works: (but I really need the parameters for other stuff)
command.CommandText = "INSERT INTO test.test (`user`,`password`) VALUES (`" + username.Text + "`,`" + password.Text + "`);";
command.ExecuteNonQuery();
What am I doing wrong?
Change your CommandText to be a valid one for OdbcCommand:
command.CommandText = "INSERT INTO test.test (`user`,`password`) VALUES (? , ?);";
Instead of the parameter name as #paramname, it takes a ? in the CommandText - leave the name in the actual parameters.
See this blog post for an example.