Issue with mdmysql.Parameters.AddWithValue for string value - c#

When I try to insert a string value using mdmysql.Parameters.AddWithValue it generates an input format string exception. Following is the code which produces the error:
cmdmysql.Parameters.AddWithValue("#p_mode", MySqlDbType.VarChar).Value = "ccc";
I tried with varchar, string, text but nothing is working. Also if I put null in place of "ccc" then the record gets inserted into the table. The variable type for p_mode in table is varchar. What is the reason for this exception?

The AddWithValue function takes only two inputs, 1. The parametername and 2. the value
cmdmysql.Parameters.AddWithValue("#p_mode", "ccc");
If you want to use the definition of types you must use the normal Add function:
cmdmysql.Parameters.Add("#p_mode", MySqlDbType.VarChar).Value = "ccc";
I would guess that the exception comes from your second input where you parse an MySqlDbType to the function and not the acutal value you want the returned mysqlparameter to have.

Try this
cmdmysql.Parameters.AddWithValue("#p_mode","ccc");

Related

OleDb Parameter Into OleDbCommand Not Passing into Query

I'm attempting to pass a string of numbers into a query that will run against our AS400 connection however it doesn't seem that my value is actually making it to the query. I am returning a result when I debug to the point of the parameter so I know I'm getting my number.
var command = new OleDbCommand("SELECT UMACT, UMCUS, UMNAM, UMAD1, UMAD2, UMAD3, UMZIP, UMOPH, UMSLC FROM CFFILES.UMST WHERE trim(UMEMT) = '?' ", connection);
//Test meter number: 59115796
connection.Open();
OleDbParameterCollection paramCollection = command.Parameters;
paramCollection.Add(meternumber.ToString(), OleDbType.LongVarChar);
When I pass a number directly into the query it returns a perfect result however when I try to pass a number from the parameter it returns null.
Here is the variable itself that I know is being passed to my parameter that I created above because I get a result when I debug to that line.
public IEnumerable<CustomerInfoModel> GetCustomerInfo()
{
int meternumber = 59115796;
getAS400Data(meternumber);
return customerList;
}
For my AS400 query to work I have to have the ticks around the ? in the query so I'm not sure if that is perhaps causing the issue.
You have the call to Add method wrong. The first parameter of Add is the Name of the parameter, the second is the DataType and finally you should set the value of the parameter in this way
OleDbParameterCollection paramCollection = command.Parameters;
paramCollection.Add("whatever", OleDbType.LongVarChar).Value = meternumber.ToString();
See OleDbParameterCollection.Add
And no, you shouldn't add ticks around the question mark placeholder. If you do you transform your placeholder in a literal string and obviously you don't have any row with a question mark as value.
A final note, in OleDb parameters doesn't have a name, but when you add them to your collection you should provide one so you are free to choose whatever you like for the name. Just remember to keep them in the same order in which the placeholders (?) appears in your query string

Error converting int to nvarchar

This error has me very confused. I have a stored procedure with two output parameters as defined below
#agentNumber int OUTPUT,
#currentAgentNum int OUTPUT,
They are then populated using the SELECT statements below
SELECT #agentNumber = AgentNumber
FROM AgentIdentification
WHERE AgentTaxId = #ssn
SELECT #currentAgentNum = AgentNumber
FROM UniqueAgentIdToAgentId
WHERE AgentId = #agentId
In the database, AgentNumber is defined in both tables, as an int. However, when I call this stored procedure in my C# code, I get a SQL exception stating:
Error converting data type int to nvarchar.
If I change the data types of the output parameters to nvarchar, the code will execute, however it will only return nothing more than the first digit of the whole number. Below is how the variables are defined in the C# code
SqlParameter outNewAgentNumber = new SqlParameter("#agentNumber", "");//Output parameter - leave blank
SqlParameter outCurrentAgentNumber = new SqlParameter("#currentAgentNum", "");//Output parameter - leave blank
outNewAgentNumber.Direction = ParameterDirection.Output;
outCurrentAgentNumber.Direction = ParameterDirection.Output;
I add these parameters to a SqlCommand object, specify the appropriate database and commandType, then use .ExecuteNonQuery() to call the procedure. Again, what has me really confused is the error message stating that I'm using nvarchar as a data type, which could only (to the best of my knowledge) be referring to something on the database side. However, as I said I've double/triple checked and both AgentNumber columns are of type int.
EDIT
Changing the sqlParameter declarations to a starting value of 0 has solved this issue. I'm now running into the same problem with two other parameters.
SqlParameter outOperator = new SqlParameter("#operator", "");//Output parameter - leave blank
SqlParameter outDate = new SqlParameter("#date", "");//Output parameter - leave blank
Change
SqlParameter outNewAgentNumber = new SqlParameter("#agentNumber", "");//Output parameter - leave blank
SqlParameter outCurrentAgentNumber = new SqlParameter("#currentAgentNum", "");//Output parameter - leave blank
to
SqlParameter outNewAgentNumber = new SqlParameter("#agentNumber", 0);//Output parameter - leave blank
SqlParameter outCurrentAgentNumber = new SqlParameter("#currentAgentNum", 0);//Output parameter - leave blank
In your code, you're initially specifying the value as a string because you are passing it a string, which maps to a varchar when going from the CLR type to the SQL Data Type.
Once the runtime sees it as a string, it retains the same type throughout code, so if you assign a numeric (int) value, it still sees it as a string. The trick is to assign it the correct data type in the first place.
These two lines are the culprits:
SqlParameter outNewAgentNumber = new SqlParameter("#agentNumber", "");
SqlParameter outCurrentAgentNumber = new SqlParameter("#currentAgentNum", "");
By specifying an empty string ("") as the second parameter, the ADO.NET runtime assumes it's a string paramter. And since you didn't specify any lengths - it probably defaults to just one character length (that's why it's returning only the first digit).
So, my recommendation would be to always explicitly define the datatype (and if it's a string - also define a length!) for your SQL parameters:
SqlParameter outNewAgentNumber = new SqlParameter("#agentNumber", SqlDbType.Int);
outNewAgentNumber.Direction = ParameterDirection.Output;
outNewAgentNumber.Value = 0;
or
SqlParameter outNewAgentNumber = new SqlParameter("#agentNumber", SqlDbType.NVarChar, 50);
outNewAgentNumber.Direction = ParameterDirection.Output;
outNewAgentNumber.Value = "";

Problems with Data type in Npgsql query

I'm trying to insert a row in a PostgreSQL table with a date column. On the UI, I got a DateTimePicker where the user selectes the proper date. So far I got this:
On the UI:
objPresupuesto.date = this.dtpFechaPres.Value.ToString("yyyy-MM-dd");
On the method who inserts the row:
NpgsqlCommand query = new NpgsqlCommand("insert into presupuesto(presupuesto, codigo, descripcion, fecha, cliente, proyecto, total) values(nextval('presupuesto_presupuesto_seq'), #codigo, #descripcion, #fecha, #cliente, #proyecto, #total);Select lastval();", conn);
...
query.Parameters.Add(new NpgsqlParameter("fecha", NpgsqlDbType.Date, 0, "fecha"));
...
query.Parameters[2].Value = obj.date.toString;//without the toString it also fails
It throws this exception:
Specified cast is not valid.
The obj.date value is 2011-04-29. tryied putting single quotes around, but It also fails.
The database column type is date.
Anyone has done this before? Any ideas?
I checked this link searching for and aswer but it doesn't helped.
Thanks
The first thing I noticed is that when you are adding your parameter it is missing the "#" from the beginning where your command references the value with the "#".
Are you sure that the Parameters[2] is your "fecha" parameter?
try use:
npgsqlCommand.Parameters.Add("fecha", NpgsqlDbType.Date).Value = DateTime.Now;
For more readable code.
Type of obj.date is DateTime struct?
Add to connection string parameter Convert Infinity DateTime
For more info check: http://www.npgsql.org/doc/connection-string-parameters.html
query.Parameters[2].Value = CDate(obj.date)

ADO.NET parameters from TextBox

I'm trying to call a parameterized stored procedure from SQL Server 2005 in my C# Winforms app. I add the parameters from TextBoxeslike so (there are 88 of them):
cmd.Parameters.Add("#CustomerName", SqlDbType.VarChar, 100).Value = CustomerName.Text;
I get the following exception:
"System.InvalidCastException: Failed to convert parameter value
from a TextBox to a String. ---> System.InvalidCastException:
Object must implement IConvertible."
The line throwing the error is when I call the query:
cmd.ExecuteNonQuery();
I also tried using the .ToString() method on the TextBoxes, which seemed pointless anyway, and threw the same error. Am I passing the parameters incorrectly?
It's probable that you forgot to specify the Text property when assigning one of your parameter values.
For example, instead of:
CustomerName.Text
You may have done just:
CustomerName
This would be an easy thing to miss if there are 88 of them.
I suspect you have missed a .Text somewhere, but you say you did a ToString on all the parameter values so that seems strange. Anyway, you can use the following piece of code to dump the parameter names and the type name of the value, this might help spot the problematic parameter.
foreach (SqlParameter param in cmd.Parameters)
{
System.Diagnostics.Debug.WriteLine(string.Format("{0}:{1}", param.ParameterName, param.Value == null ? "NULL" : param.Value.GetType().Name));
}
You should get something like the following in the debug window, in this case CustomerSurname is the parameter that has a Textbox and not a string as an example.
#CustomerName:String
#CustomerSurname:TextBox
...
try something like this:
SqlParameter sqlParam= new SqlParameter();
sqlParam.ParameterName = "#customerName";
sqlParam.Direction = ParameterDirection.Input;
sqlParam.SqlDbType = SqlDbType.VarChar;
sqlParam.Size = 100;
sqlParam.Value = customername.Text;
cmd.Parameters.Add(sqlParam);

C# - ODP.NET and ora-01475 must reparse cursor to change bind variable datatype

I'm getting ora-01475 whenever I try to insert a null value in a column (of type DateTime) after some records have already been inserted that have real date values.
I'm using the OracleParameter constructor that takes the name and the value as an object (I assume the data type is then implied from the datatype of the object), but since sometimes the value of my parameter is null, it's being set as a String, therefore throwing this error.
I don't want to use the constructor that takes the datatype explicitly because I use reflection heavily to build the OracleCommand object and its parameters.
How can I reparse the cursor (as the error suggests) if I find this situation?
Has anyone else run into this and has a solution?
Have you tried to use nullable types?
DateTime? myDate;
//Code to set myDate value...
string sql = "[your SQL]"
using (OracleCommand command = new SqlCommand(sql, cn))
{
OracleParameter param = new OracleParameter(":Name",myDate);
command.Paerameters.add(param);
command.ExecuteNonQuery();
}

Categories