I have created a parameterized SQL insert query and I have made a mistake somewhere. I kept getting a message that values would be truncated, so, during troubleshooting I reduced the query to only fields that required values (NULLs not allowed), and the insert statement completed.
I check the table, and I see my parameter names inserted, not the values they should be pulling from the form's textboxes.
Obviously I am calling my parameters incorrectly but I just can't figure out where I have gone wrong. I am hoping you all can help me.
Thanks in advance!
NOTE: Yes, I know there are more parameters than what I am using in the INSERT string. I have intentionally cut down the values used for troubleshooting.
Thanks again!
try {
string InsertString = #"INSERT INTO Item.Itemtable
(ItemNumber, ItemDesc, RatioToOriginalItemNumber, OriginalItemNumber, EntreeCount, ItemType, ProteinBeverage)
Values(#ItemNumberValue, '#ItemDescValue', #RatioToOriginalItemNumberValue, #OriginalItemNumberValue, #EntreeCountValue, '#ItemTypeValue', #ProteinBeverageValue)";
SqlCommand InsertNewItem = new SqlCommand(InsertString, PmixWriter);
//Define Insert Parameters
SqlParameter #ItemNumberValue = InsertNewItem.Parameters.Add("#ItemNumberValue", System.Data.SqlDbType.Int);
SqlParameter #ItemDescValue = InsertNewItem.Parameters.Add("#ItemDescValue", System.Data.SqlDbType.VarChar, 100);
SqlParameter #ItemTypeValue = InsertNewItem.Parameters.Add("#ItemTypeValue", System.Data.SqlDbType.VarChar, 100);
SqlParameter #ProteinBeverageValue = InsertNewItem.Parameters.Add("#ProteinBeverageValue", System.Data.SqlDbType.VarChar, 100);
SqlParameter #IsCouponValue = InsertNewItem.Parameters.Add("#IsCouponValue", System.Data.SqlDbType.Char, 3);
SqlParameter #EntreeCountValue = InsertNewItem.Parameters.Add("#EntreeCountValue", System.Data.SqlDbType.Real);
SqlParameter #BevCountValue = InsertNewItem.Parameters.Add("#BevCountValue", System.Data.SqlDbType.TinyInt);
SqlParameter #OriginalItemNumberValue = InsertNewItem.Parameters.Add("#OriginalItemNumberValue", System.Data.SqlDbType.Int);
SqlParameter #RatioToOriginalItemNumberValue = InsertNewItem.Parameters.Add("#RatioToOriginalItemNumberValue", System.Data.SqlDbType.TinyInt);
SqlParameter #FPBeverageCountValue = InsertNewItem.Parameters.Add("#FPBeverageCountValue", System.Data.SqlDbType.Int);
SqlParameter #FPBeverageEntreeCountValue = InsertNewItem.Parameters.Add("#FPBeverageEntreeCountValue", System.Data.SqlDbType.Int);
SqlParameter #FoodCostValue = InsertNewItem.Parameters.Add("#FoodCostValue", System.Data.SqlDbType.Money);
//Assign and covert values to the stated SQL parameters.
#ItemNumberValue.Value = Convert.ToInt32(ItemNumberBox.Text);
#ItemDescValue.Value = ItemDescBox.Text;
#ItemTypeValue.Value = ItemTypeBox.Text;
#ProteinBeverageValue.Value = ProteinBevBox.Text;
#IsCouponValue.Value = IsCouponBox.Text;
#EntreeCountValue.Value = Convert.ToInt32(EntreeCountBox.Text);
#BevCountValue.Value = Convert.ToInt32(BevCountBox.Text);
#OriginalItemNumberValue.Value = Convert.ToInt32(OriginalItemNumBox.Text);
#RatioToOriginalItemNumberValue.Value = Convert.ToInt32(RatioBox.Text);
#FPBeverageCountValue.Value = Convert.ToInt32(FPBevBox.Text);
#FPBeverageEntreeCountValue.Value = Convert.ToInt32(FPBevEntreeBox.Text);
#FoodCostValue.Value = Convert.ToDecimal(0.00);
InsertNewItem.ExecuteNonQuery();
} catch (SqlException) {
throw;
}
In your INSERT statement, remove the single quotes from #ItemDescValue and #ItemTypeValue parameters. They are currently being inserted as literal values otherwise.
Related
I am trying to call a stored procedure from my code using oledb but I can't figure out how to do this. This is the code I wrote but it's not working
OleDbCommand sp = connectionDB.CreateCommand();
sp.CommandText = "CALL NASVARWG.§SP001('?','?','?','?','?','?')";
sp.CommandType = CommandType.StoredProcedure;
sp.Parameters.Add("P1", System.Data.OleDb.OleDbType.Char).Value = "ESANASTRIS";
sp.Parameters["P1"].Size = 10;
sp.Parameters["P1"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P2", System.Data.OleDb.OleDbType.Char).Value = "SAMNAS";
sp.Parameters["P2"].Size = 10;
sp.Parameters["P2"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P3", System.Data.OleDb.OleDbType.Char).Value = "blah";
sp.Parameters["P3"].Size = 10;
sp.Parameters["P3"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P4", System.Data.OleDb.OleDbType.Char);
sp.Parameters["P4"].Size = 2;
sp.Parameters["P4"].Direction = ParameterDirection.Output;
sp.Parameters.Add("P5", System.Data.OleDb.OleDbType.Char);
sp.Parameters["P5"].Size = 256;
sp.Parameters["P5"].Direction = ParameterDirection.Output;
sp.Parameters.Add("P6", System.Data.OleDb.OleDbType.Char).Value = textBox_Reparto.Text;
sp.Parameters["P6"].Size = 6;
sp.Parameters["P6"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P7", System.Data.OleDb.OleDbType.Char).Value = "we can do this";
sp.Parameters["P7"].Size = 60;
sp.Parameters["P7"].Direction = ParameterDirection.Input;
sp.Parameters.Add("P8", System.Data.OleDb.OleDbType.Char).Value = "help";
sp.Parameters["P8"].Size = 256;
sp.Parameters["P8"].Direction = ParameterDirection.Input;
sp.Prepare();
sp.ExecuteNonQuery();
I get an exception at "sp.Prepare();" telling me that the syntax of the command is wrong.
If you can, use the IBM i Access ADO.NET drivers and place the program call in a stored procedure. They can convert the data from i to PC.
As #Syafiqur__ mentioned the ADO.NET drivers are a better choice.
And as always there is an IBM redbook about it. In my solutions I use the IBMDA400 version.
For your case it should look like this:
var command = new iDB2Command(cmdText: "§SP001", cmdType: CommandType.StoredProcedure, connection: masterSystemConnection);
var p1 = new iDB2Parameter(parameterName: "#P1", type: iDB2DbType.iDB2Char, size: 10);
p1.Direction = ParameterDirection.Input;
p1.Value = "ESANASTRIS";
command.Parameters.Add(p1);
// ... all your other parameters, no call to Prepare
command.ExecuteNonQuery();
Regarding your SQL0469:
Either change the attribute of the parameter on the DECLARE PROCEDURE, CREATE PROCEDURE, or ALTER PROCEDURE statement or change the parameter.
For additional details please have a look at the IBM documentation.
Bernd
I think your problem is most likely that you have NO parameter markers in your SQL statement.
sp.CommandText = "CALL NASVARWG.§SP001('?','?','?','?','?','?')";
The '?' are string constants, not parameter markers ? which should appear without apostrophes. So the statement should really look like this:
sp.CommandText = "CALL NASVARWG.§SP001(?, ?, ?, ?, ?, ?)";
I am trying to execute a dynamic SQL from C# and I want to use sp_executesql because I want to pass a list of strings to be used for an IN statement in the dynamic SQL passed to sp_executesql.
The thing is that I don't know exactly how to do this.
So far I did it like this:
using (var dbCommand = databaseConnection.CreateCommand())
{
dbCommand.CommandType = CommandType.StoredProcedure;
dbCommand.CommandText = "sp_executesql";
var sqlParam = dbCommand.CreateParameter();
sqlParam.DbType = DbType.String;
sqlParam.ParameterName = "stmt";
sqlParam.Value = sql.SQL;
dbCommand.Parameters.Add(sqlParam);
var incidentIdParam = dbCommand.CreateParameter();
incidentIdParam.ParameterName = "incidentId";
incidentIdParam.DbType = DbType.Int32;
incidentIdParam.Value = arguments.filterAttributes.incidentId;
dbCommand.Parameters.Add(incidentIdParam);
dbCommand.ExecuteReader();
}
Is it possible like this?
As an option, you can format your SQL on the client side and pass to the stored procedure ready string. For example:
sql.SQL = "UPDATE ORDERS SET STATUS = 1 WHERE ID = %param%";
then
sqlParam.Value = sql.SQL.Replace("%param%", arguments.filterAttributes.incidentId.ToString());
I know that this problem is to much mentioned but problem is wasting my time, and in my stored procedure the parameters are the same, I don't know why this happens. I hope you can help me
protected void Button1_Click(object sender, EventArgs e)
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_InfoPacient";
cmd.Connection = cn;
SqlParameter pd = new SqlParameter("#PacientId",SqlDbType.Int);
pd.Value = DropDownList1.Text;
cmd.Parameters.Add(pd);
SqlParameter pname = new SqlParameter("#EmriPacientit",SqlDbType.VarChar,20);
pname.Value = TextBox12.Text;
cmd.Parameters.Add(pname);
SqlParameter age = new SqlParameter("#Mosha",SqlDbType.Int);
age.Value = TextBox13.Text;
cmd.Parameters.Add(age);
SqlParameter dep = new SqlParameter("#Departamenti", SqlDbType.VarChar, 20);
dep.Value = TextBox14.Text;
cmd.Parameters.Add(dep);
SqlParameter doct = new SqlParameter("#DrPersonal", SqlDbType.VarChar, 20);
doct.Value = TextBox15.Text;
cmd.Parameters.Add(doct);
cmd.ExecuteNonQuery();
}
To me it looks like it boils down to these two lines:
> SqlParameter pd = new SqlParameter("#PacientId",SqlDbType.Int);
> pd.Value = DropDownList1.Text;
In the first line you're telling the command that parameter "PacientId" is of type int.
In the second line you're assigning the parameter the value of DropDownList1.Text, which will be of type string.
To solve this you probably need to Convert.ToInt32(DropDownList1.Text) to make sure the parameter value you set is an integer.
As Hogan points out, there is a potential issue if the Text value is not an integer - e.g. if you have values "1", "2", "3" and "Potato". You cannot parse "Panini" to an Int.
Use Int.TryParse when you're not absolutely certain your inputs will convert. The MSDN documentation describes this well.
I'm just trying to return a list of columns and their attributes through a system stored procedure. What documentation I have seems to say the below code should work, but I get "Pervasive.Data.SqlClient.Lna.k: [LNA][Pervasive][ODBC Engine Interface]Invalid or missing argument." on the execute. This is PSQL v11, .NET 4.5.
using (PsqlConnection conn = new PsqlConnection(cs))
{
PsqlCommand locationCmd = new PsqlCommand();
PsqlParameter tableParam = new PsqlParameter();
PsqlParameter returnParam = new PsqlParameter();
returnParam.Direction = ParameterDirection.ReturnValue;
locationCmd.CommandText = "psp_columns";
locationCmd.Connection = conn;
locationCmd.CommandType = CommandType.StoredProcedure;
locationCmd.Parameters.Add(tableParam).Value = table;
locationCmd.Parameters.Add(returnParam);
conn.Open();
locationCmd.ExecuteNonQuery();
}
I would think the problem is this line:
locationCmd.Parameters.Add(tableParam).Value = table;
You should set the value before adding the parameter, not afterwards.
tableParam.Value = table;
locationCmd.Parameters.Add(tableParam);
I don't know about Psql but for MSSQL normally you also need to define the parameter name as its found in the stored procedure, or at least that's what I do.
SqlParameter param = new SqlParameter("#tableParam", value);
The psp_Columns system stored procedure is defined as call psp_columns(['database_qualifier'],'table_name', ['column_name']). I know that it says the database qualifier is optional, but I think it's required. You could try passing an empty string for the qualifier. Something like:
using (PsqlConnection conn = new PsqlConnection(cs))
{
PsqlCommand locationCmd = new PsqlCommand();
PsqlParameter dbParam = new PsqlParameter();
PsqlParameter tableParam = new PsqlParameter();
PsqlParameter returnParam = new PsqlParameter();
returnParam.Direction = ParameterDirection.ReturnValue;
locationCmd.CommandText = "psp_columns";
locationCmd.Connection = conn;
locationCmd.CommandType = CommandType.StoredProcedure;
locationCmd.Parameters.Add(dbParam).Value = ""; //might need two single quotes ('')
locationCmd.Parameters.Add(tableParam).Value = table;
locationCmd.Parameters.Add(returnParam);
conn.Open();
locationCmd.ExecuteNonQuery();
}
You should try to get the information of the table SCHEMA using the provided GetSchema method from the Psqlconnection. I have searched a bit on their support site and it seems that this method is supported although I haven't find a direct example using the Tables collection.
This is just an example adapted from a test on mine on SqlServer, I don't have Pervasive install, but you could try if the results are the same
using(PsqlConnection cn = new PsqlConnection("your connection string here"))
{
cn.Open();
string[] selection = new string[] { null, null, table };
DataTable tbl = cn.GetSchema("Columns", selection);
foreach (DataRow row in tbl.Rows)
{
Console.WriteLine(row["COLUMN_NAME"].ToString() + " " +
row["IS_NULLABLE"].ToString() + " " +
row["DATA_TYPE"].ToString()
);
}
}
i was trying to figure this out as well, but with the tables procedure. even though the database and table names are optional, you still have to provide values. for optional parameters, pass in DBNull.Value
this worked for me:
PsqlCommand cm = new PsqlCommand();
cm.CommandText = "psp_tables";
cm.CommandType = CommandType.StoredProcedure;
cm.Connection = new PsqlConnection();
cm.Connection.ConnectionString = <your connection string>;
cm.Parameters.Add(":database_qualifier", DBNull.Value);
cm.Parameters.Add(":table_name", DBNull.Value);
cm.Parameters.Add(":table_type", "User table");
I know that this question has been asked many times, And I have read many many answers, yet I can't figure out what is wrong. It's been hours. Any help would be soo appreciated. I am just trying to call a stored procedure in an ASP page, and I am unable to add the parameter properly, getting the exception that it is not in the collection.
I have modified my proc as follows to try to make it simple and isolate the issue.
ALTER PROCEDURE [dbo].[up_validateUserWithClinicCount]
#HTID INT = 0,
#ValidUserID INT OUTPUT,
#MultiClinicFlag INT OUTPUT
AS
DECLARE #vClinicCount INT = null
DECLARE #vUserValid INT = null
BEGIN
SET #ValidUserID = 2
SET #MultiClinicFlag = 1
END;
AND the C# code
String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["PC3PaymentConnection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("up_validateUserWithClinicCount", connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#HTID", htId);
SqlParameter uidOut = new SqlParameter("#ValidUserID", SqlDbType.Int);
uidOut.Size = 4;
uidOut.Direction = ParameterDirection.Output;
cmd.Parameters.Add(uidOut);
SqlParameter pMultiClinics = new SqlParameter();
pMultiClinics.ParameterName = "#MultiClinicFlag";
pMultiClinics.SqlDbType = SqlDbType.Int;
pMultiClinics.Direction = ParameterDirection.Output;
cmd.Parameters.Add(pMultiClinics);
try
{
cmd.ExecuteNonQuery();
//--> Error points to the next line, and I have tried to use int.parse rather than convert also, with the same error -- parameter not in collection
MultiClinics = Convert.ToInt16(cmd.Parameters["pMultiClinics"].Value);
PC3User = Convert.ToInt16(uidOut.Value.ToString());
}
catch (SqlException sqlEx)
{
LbMsg.ForeColor = System.Drawing.Color.Red;
LbMsg.Text = sqlEx.Message;
}
}
}
Thanks if you can see what I am missing.
You have an object reference for the parameter already, you don't need to grab it from the parameters collection. Also, sql ints are 32-bit.
MultiClinics = (int)pMultiClinics.Value;
To retrieve from the parameter collection, use the ParameterName you gave it:
MultiClinics = (int)cmd.Parameters["#MultiClinicFlag"].Value;