I am trying to fetch data from the source and save into the Database but I am facing this issue even after declaring the scalar variable. find below the approach which I tried. The issue I am facing: System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#col_shipping_price".'
class Program
{
static void Main(string[] args)
{
XmlSerializer deserializer = new XmlSerializer(typeof(AmazonEnvelope));
TextReader reader = new StreamReader(#"C:\Users\*********\Desktop\16315550943018039.xml");
object obj = deserializer.Deserialize(reader);
AmazonEnvelope XmlData = (AmazonEnvelope)obj;
reader.Close();
SqlConnection cnn = new SqlConnection(#"Data Source=ABDUL-TPS\TPSSQLSERVER;Initial Catalog=Zoho_Amz_API;User ID=zohoapiservice;Password=**********");
cnn.Open();
for (int i = 0; i < XmlData.Message.Count; i++)
{
string sqlquery = "if not exists (select * from tbl_AMZ_API_sample where col_sku like '" + XmlData.Message[i].Order.OrderItem.SKU + "') insert into tbl_AMZ_API_sample(col_amazon_order_id, col_merchant_order_id, col_purchase_date, col_last_updated_date, col_order_status, col_fulfillment_channel, col_sales_channel, col_order_channel, col_url, col_ship_service_level, col_product_name, col_sku, col_asin, col_number_of_items, col_item_status, col_quantity, col_currency, col_item_price, col_item_tax, col_shipping_price, col_shipping_tax, col_gift_wrap_price, col_gift_wrap_tax, col_item_promotion_discount, col_ship_promotion_discount, col_ship_city, col_ship_state, col_ship_postal_code, col_ship_country, col_promotion_ids, col_is_business_order, col_purchase_order_number, col_price_designation, col_fulfilled_by, col_last_update_time) values(#col_amazon_order_id, #col_merchant_order_id, #col_purchase_date, #col_last_updated_date, #col_order_status, #col_fulfillment_channel, #col_sales_channel, #col_order_channel, #col_url, #col_ship_service_level, #col_product_name, #col_sku, #col_asin, #col_number_of_items, #col_item_status, #col_quantity, #col_currency, #col_item_price, #col_item_tax, #col_shipping_price, #col_shipping_tax, #col_gift_wrap_price, #col_gift_wrap_tax, #col_item_promotion_discount, #col_ship_promotion_discount, #col_ship_city, #col_ship_state, #col_ship_postal_code, #col_ship_country, #col_promotion_ids, #col_is_business_order, #col_purchase_order_number, #col_price_designation, #col_fulfilled_by, #col_last_update_time)";
SqlCommand cmd = new SqlCommand(sqlquery, cnn);
for (int j = 0; j < XmlData.Message[i].Order.OrderItem.ItemPrice.Component.Count; j++)
{
cmd.Parameters.AddWithValue("#col_amazon_order_id", XmlData.Message[i].Order.AmazonOrderID);
if (XmlData.Message[i].Order.MerchantOrderID == null)
{
cmd.Parameters.AddWithValue("#col_merchant_order_id", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#col_merchant_order_id", XmlData.Message[i].Order.MerchantOrderID);
}
cmd.Parameters.AddWithValue("#col_purchase_date", XmlData.Message[i].Order.PurchaseDate);
cmd.Parameters.AddWithValue("#col_last_updated_date", Global.unique.ToString());
cmd.Parameters.AddWithValue("#col_order_status", XmlData.Message[i].Order.OrderStatus);
cmd.Parameters.AddWithValue("#col_fulfillment_channel", XmlData.Message[i].Order.FulfillmentData.FulfillmentChannel);
cmd.Parameters.AddWithValue("#col_sales_channel", XmlData.Message[i].Order.SalesChannel);
cmd.Parameters.AddWithValue("#col_ship_service_level", XmlData.Message[i].Order.FulfillmentData.ShipServiceLevel);
cmd.Parameters.AddWithValue("#col_product_name", XmlData.Message[i].Order.OrderItem.ProductName);
cmd.Parameters.AddWithValue("#col_sku", XmlData.Message[i].Order.OrderItem.SKU);
cmd.Parameters.AddWithValue("#col_asin", XmlData.Message[i].Order.OrderItem.ASIN);
cmd.Parameters.AddWithValue("#col_number_of_items", XmlData.Message[i].Order.OrderItem.NumberOfItems);
cmd.Parameters.AddWithValue("#col_item_status", XmlData.Message[i].Order.OrderItem.ItemStatus);
cmd.Parameters.AddWithValue("#col_quantity", XmlData.Message[i].Order.OrderItem.Quantity);
cmd.Parameters.AddWithValue("#col_currency", XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Amount.Currency);
switch (XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Type)
{
case "Principal":
cmd.Parameters.AddWithValue("#col_item_price", XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Amount.Text);
cmd.Parameters.AddWithValue("#col_item_tax", XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Amount.Text);
break;
case "Shipping":
cmd.Parameters.AddWithValue("#col_shipping_price", XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Amount.Text);
break;
case "GiftWrap":
cmd.Parameters.AddWithValue("#col_gift_wrap_price", XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Amount.Text);
break;
case "Shipping-Tax":
cmd.Parameters.AddWithValue("#col_shipping_tax", XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Amount.Text);
break;
default:
cmd.Parameters.AddWithValue("#col_gift_wrap_tax", XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Amount.Text);
break;
}
if (XmlData.Message[i].Order.OrderItem.Promotion == null)
{
cmd.Parameters.AddWithValue("#col_item_promotion_discount", 0);
cmd.Parameters.AddWithValue("#col_ship_promotion_discount", 0);
cmd.Parameters.AddWithValue("#col_promotion_ids", 0);
}
else
{
cmd.Parameters.AddWithValue("#col_item_promotion_discount", XmlData.Message[i].Order.OrderItem.Promotion.ItemPromotionDiscount);
cmd.Parameters.AddWithValue("#col_ship_promotion_discount", XmlData.Message[i].Order.OrderItem.Promotion.ShipPromotionDiscount);
cmd.Parameters.AddWithValue("#col_promotion_ids", XmlData.Message[i].Order.OrderItem.Promotion.PromotionIDs);
}
cmd.Parameters.AddWithValue("#col_ship_city", XmlData.Message[i].Order.FulfillmentData.Address.City);
cmd.Parameters.AddWithValue("#col_ship_state", XmlData.Message[i].Order.FulfillmentData.Address.State);
cmd.Parameters.AddWithValue("#col_ship_postal_code", XmlData.Message[i].Order.FulfillmentData.Address.PostalCode);
cmd.Parameters.AddWithValue("#col_ship_country", XmlData.Message[i].Order.FulfillmentData.Address.Country);
cmd.Parameters.AddWithValue("#col_is_business_order", XmlData.Message[i].Order.IsBusinessOrder);
cmd.Parameters.AddWithValue("#col_purchase_order_number", XmlData.Message[i].Order.PurchaseOrderNumber);
cmd.Parameters.AddWithValue("#col_price_designation", XmlData.Message[i].Order.OrderItem.PriceDesignation);
cmd.Parameters.AddWithValue("#col_fulfilled_by", XmlData.Message[i].Order.FulfilledBy);
cmd.Parameters.AddWithValue("#col_Order_Channel", DBNull.Value);
cmd.Parameters.AddWithValue("#col_url", DBNull.Value);
Console.WriteLine(XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Type);
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Someone help please.
You obviously know in general how to use parameterized queries, so why don't you use it in the SELECT part of the query here:
... like '" + XmlData.Message[i].Order.OrderItem.SKU + "' ...
You should also use parameters there. And the LIKE could be changed to an = unless XmlData.Message[i].Order.OrderItem.SKU includes wildcards, which seems unlikely.
On your problem:
You have #col_shipping_price in the INSERT part of your query apparently meant as a parameter. Yet you only set this parameter if XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Type is Shipping in the switch(). That is, in all other cases #col_shipping_price stays as it is in the query and isn't replaced. SQL Server thinks it is a variable and rightfully complains that it wasn't declared. The same problem might occur with some of you other parameters it seems.
You have some options here.
Replace all the parameters all the time. Probably use DBNull if you have no actual value. Unless there are not null constraints on the columns that should work. If you do it like that there's also no need to rebuild the query in every iteration. Create it once, optionally Prepare() it and then just change the parameters' values in the iteration. Performance may benefit from that.
Build different queries depending on XmlData.Message[i].Order.OrderItem.ItemPrice.Component[j].Type. That way you can simply leave placeholders of unused parameters out.
And you should be careful when using AddWithValue(), even avoid using it completely. It needs to guess the data type of the columns on the database, sometimes miserably fails and produces funny errors. Better use the Add() overloads with explicit type arguments. Something to read on this topic: "AddWithValue is Evil"
I'm trying the following code but not working in mssql and not producing any error message in CakePHP, using version 2.6:
$product_id = $this->request->data['products']['product_id'];
$this->request->data['ProductTbl']['id'] = strtotime(date('Y-m-d H:i:s'));
$this->request->data['ProductTbl']['retailerId'] = $this->request->data['products']['retailer_id'];
$this->request->data['ProductTbl']['productCode'] = $product_id;
$this->request->data['ProductTbl']['productType'] = $this->request->data['products']['product_type'];
//$this->request->data['ProductTbl']['mmGroupId'] = $this->request->data['products']['merchandise_id'];
$this->request->data['ProductTbl']['name'] = $this->request->data['products']['product_name'];
$this->request->data['ProductTbl']['description'] = $this->request->data['products']['product_desp'];
$this->request->data['ProductTbl']['isLayawayable'] = $this->request->data['products']['product_layway'];
$this->request->data['ProductTbl']['isTaxExemptible'] = $this->request->data['products']['product_tax'];
$this->request->data['ProductTbl']['productURL'] = $this->request->data['products']['product_url'];
$this->request->data['ProductTbl']['status'] = 2;
$this->request->data['ProductTbl']['lastModified'] = date('Y-m-d H:i:s');
$this->request->data['ProductTbl']['isDeleted'] = 0;
if(!empty($this->request->data['pjosn'])){
$pjson_arr = $this->request->data['pjosn'];
$this->request->data['ProductTbl']['propertiesJson'] = json_encode($pjson_arr);
}
$this->ProductTbl->save($this->request->data['ProductTbl'],false);
$last_id = $this->ProductTbl->getLastInsertID();
Thanks.
why are u using second argument 'false' in save function ???
i thinks possible issue should be second argument. I am using cakePHP 2.7.5 and according to me your save query will be ::
$res = $this->ProductTbl->save($this->request->data);
if($res){
// do whatever you wants
}
Or the second issue may be in following code :
if(!empty($this->request->data['pjosn'])){
$pjson_arr = $this->request->data['pjosn'];
$this->request->data['ProductTbl'['propertiesJson']=json_encode($pjson_arr);
}
in json_encode your data will be in joson format ( like : {"key1":value1,"key2":value2,"key3":value3,"key4":value4,"key5":value5} ) which will not be accepted by cakePHP insert query.
i want to retrive some data from my database,if $end_time1 is null then will be update table ,otherwise will do nothing ,but when i run the code,i found the $end_time1 is null,then will be update the table ,but if not null ,it's will be return the error :
Use of uninitialized value $end_time1 in string eq ........
part of my code :
my $select_sth = $dbh->prepare("SELECT id ,H1, H2, addr1, addr2, time_1, time_2,
end_time_1,end_time_2,count1,count2 FROM service") or die "$dbh->errstr";
$select_sth->execute() or die "$dbh->errstr";
while (my #row_ref = $select_sth->fetchrow_array)
{
my $Rid = $row_ref[0];
my $addr1 = $row_ref[3];
my $addr2 = $row_ref[4];
my $end_time1 = "NULL" unless $row_ref[7];
my $end_time2 = "NULL" unless $row_ref[8];
my $count1 = $row_ref[9];
my $count2 = $row_ref[10];
if($end_time1 eq "NULL")
{
print "$end_time1 is null\n";
$dbh->do ("update service set end_time_1 = '$datetime_now' where id = $Rid");
}
}
please someone what's wrong with my code ?how to fix ?
Your current code only sets $endtime1 if $row_ref[7] is not defined. This means that $endtime1 is undefined if $row_ref[7] does have a value, so you get that Use of uninitialized value $end_time1 in string eq... error when you test it.
Change your code so that $endtime1 will either be set to $row_ref[7] (if it is defined) or to NULL:
my $end_time1 = $row_ref[7] || 'NULL';
Then you can use your existing code:
if ($end_time1 eq "NULL")
{
print "end_time1 is null\n";
$dbh->do ("update service set end_time_1 = '$datetime_now' where id = $Rid");
}
The same issue exists for $endtime2, so you may want to make a similar alteration.
Use defined:
if ( !defined $end_time1 ) {
print "end_time1 is null\n";
}
I am not able to get error details using the PQresultErrorField API after a query execution fails. Using PQerrorMessage on the connection gives the correct error (constraint violation xxx_pk etc etc) and PQresultStatus shows FATAL_ERROR.
However, when I use the API PQresultErrorField(result, PG_DIAG_SQLSTATE)), I get a NULL result. Other field-codes also gives me null results.
Does this API need to be compiled in ?
Postgres version is 9.2.1
Using libpq C library
It's supposed to return NULL only when it's not applicable.
That simple test works for me:
PGresult* res = PQexec(conn, "SELECT * FROM foobar");
if (res) {
if (PQresultStatus(res) == PGRES_FATAL_ERROR) {
char* p = PQresultErrorField(res, PG_DIAG_SQLSTATE);
if (p) {
printf("sqlstate=%s\n", p?p:"null");
}
}
}
Result:
sqlstate=42P01
I'd like to know if a record is present in a database, using a field different from the key field.
I've try the following code :
function start()
{
jlog("start db query")
myType d1 = {A:"rabbit", B:"poney"};
/myDataBase/data[A == d1.A] = d1
jlog("db write done")
option opt = ?/myDataBase/data[B == "rabit"]
jlog("db query done")
match(opt)
{
case {none} : <>Nothing in db</>
case {some:data} : <>{data} in database</>
}
}
Server.start(
{port:8092, netmask:0.0.0.0, encryption: {no_encryption}, name:"test"},
[
{page: start, title: "test" }
]
)
But the server hang up, and never get to the line jlog("db query done"). I mispell "rabit" willingly. What should I've done ?
Thanks
Indeed it fails with your example, I have a "Match failure 8859742" exception, don't you see it?
But do not use ?/myDataBase/data[B == "rabit"] (which should have been rejected at compile time - bug report sent) but /myDataBase/data[B == "rabit"] which is a DbSet. The reason is when you don't use a primary key, then you can have more than one value in return, ie a set of values.
You can convert a dbset to an iter with DbSet.iterator. Then manipulate it with Iter: http://doc.opalang.org/module/stdlib.core.iter/Iter