I try to Migrate the data for list of employees from informix db to sqlserver2012 db ,so firstly i select
-The data from the tables in informix like this :
string cmdText = "select * from permission where emp_num in( " + emplyeeRange + " ) and perm_date>=? and perm_date <=?";
DataTable permissionDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
cmdText = "select * from holid where emp_num in( " + emplyeeRange + " ) and end_date>=? and start_date<=? ";
DataTable vacationDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
cmdText = "select * from empmission where emp_num in( " + emplyeeRange + " ) and date(to_date)>=? and date(from_date)<=? ";
DataTable missionDT = ifx_conn.Return_DataTable(cmdText, CommandType.Text, paramList1);
-Then i delete the data from sqlserver in the same range date like this :
cmdText = "delete from permission where emp_num in( " + emplyeeRange + " ) and perm_date>=#from_date and perm_date <=#to_date";
sql_command.CommandType = CommandType.Text;
sql_command.Parameters.AddWithValue("#from_date", from_date.ToShortDateString());
sql_command.Parameters.AddWithValue("#to_date", to_date.ToShortDateString());
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "delete from holid where emp_num in( " + emplyeeRange + " ) and end_date>=#from_date and start_date<=#to_date ";
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "delete from empmission where emp_num in( " + emplyeeRange + " ) and to_date>=#from_date and from_date<=#to_date";
sql_command.CommandText = cmdText;
result = sql_command.ExecuteNonQuery();
}
}
-Then Insert the updated data in sqlserver like this :
cmdText = "insert into permission select * from #permissionDT ";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#permissionDT", permissionDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.permissionType";
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "insert into holid select * from #vacationDT";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#vacationDT", vacationDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.holidType";
result = sql_command.ExecuteNonQuery();
if (result >= 0)
{
cmdText = "insert into empmission select * from #missionDT";
sql_command.CommandText = cmdText;
sql_command.Parameters.Clear();
sql_param = sql_command.Parameters.AddWithValue("#missionDT", missionDT);
sql_param.SqlDbType = SqlDbType.Structured;
sql_param.TypeName = "dbo.empmissionType";
result = sql_command.ExecuteNonQuery();
}
}
My Main problem is :
This process takes so long time and decrease the performance of sqlserver ,How to optimize this code and the queries concerning the db operations ?
Replace your SQLCommand ("insert into holid select * from #vacationDT") by SQLBulkCopy it will write you your server a lot faster.
e.g.:
using (var sbc = new SqlBulkCopy(myCOnnection)
{
sbc.DestinationTableName = "holid";
sbc.WriteToServer(vacationDT);
}
You may have to set ColumnMappings and/or set identity insert/on-off before and after this. More on SQLBulkCopy: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy(v=vs.110).aspx
Also, check if your DB has all the right indexes especially on start_date and end_date
Related
I've got an little issue with SQL query for an MySQL db.
Here is my query :
SELECT *
FROM myTable.requests
WHERE (myAccount= 'test')
AND MONTH(Date) = MONTH(CURRENT_DATE())
AND YEAR(Date) = YEAR(current_date())
AND (State = 'Closed')
group by Date;
This SQL return 3 rows in Workbench.
With y C# code the result is 16050 (!!)
What am I missing ?
'''
MySqlConnection mySqlConnection = mySQLEngineObj.GetConnectionObject();
int myRecordsCount = 0;
if (mySqlConnection == null)
return -1;
else {
myCommand.CommandText = "SELECT * FROM myTable.requests " +
"WHERE ((myAccount= #account) " +
"AND MONTH(requests.Date) = MONTH(NOW()) " +
"AND YEAR(requests.Date) = YEAR(NOW()) ) " +
"AND requests.State = #state " +
"GROUP BY requests.Date";
myCommand.Parameters.AddWithValue("#state", "Closed");
myCommand.Parameters.AddWithValue("#account", user.name);
MySqlDataReader test = myCommand.ExecuteReader();
if (test.HasRows)
{
test.Read();
}
}
'''
Code test.GetInt32(0) return an wrong result.
Any idea?
Regards
I have a problem with importing items from an MS Access .mdb database file into SQL Server. I wrote a C# application in practice database that extrapolates the data in a .mdb database and places them in a table in a SQL Server database.
My problem is that the .mdb database contains about 300,000 articles which are to be inserted with all of the controls inside the SQL Server database. The .mdb file is selected by the user.
How can I speed up the import of the articles?
This is my C# code:
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
// SqlConnection conn2 = db.apriconnessione();
try
{
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
string querycontalinee = "SELECT count(*) from ARTICOLI";
OleDbCommand command = new OleDbCommand(query, dbConn);
OleDbCommand commandcontalinee = new OleDbCommand(querycontalinee, dbConn);
dbConn.Open();
int linee = (int)commandcontalinee.ExecuteScalar();
OleDbDataReader reader = command.ExecuteReader();
Articolo a;
labelstatoaggiornamento.Show();
progressBarstatoaggiornamento.Show();
progressBarstatoaggiornamento.Style = ProgressBarStyle.Continuous;
progressBarstatoaggiornamento.Minimum = 0;
progressBarstatoaggiornamento.Maximum = linee;
progressBarstatoaggiornamento.Step = 1;
SqlConnection conn = db.apriconnessione();
while (reader.Read())
{
String CodMarca = "" + reader.GetValue(0).ToString();
String CodArt = "" + reader.GetValue(1).ToString().Replace("'", ""); ;
String Fornitore = "COMET";
String Descrizione = "" + reader.GetValue(2).ToString();
String UM = "" + reader.GetValue(3).ToString();
String PrezzoNetto = "" + reader.GetValue(4).ToString();
String PrezzoCasa = "" + reader.GetValue(5).ToString();
DateTime DataAggiornamento = DateTime.Now;
decimal Prezzo = Decimal.Parse(PrezzoNetto, System.Globalization.NumberStyles.Any);
decimal PrezzoListino = Decimal.Parse(PrezzoCasa, System.Globalization.NumberStyles.Any);
a = new Articolo(CodArt, CodMarca);
a.db = db;
if (a.ControlloDisponibilitàCOMET() == true)
{
string queryAggiornamento = "Update Articolo Set Descrizione='" + Descrizione + "', UM='" + UM + "', Prezzo='" + Prezzo + "',PrezzoListino='" + PrezzoListino + "',DataAggiornamento='" + DataAggiornamento + "',Stato='Aggiornamentoincorso' Where CodMarca = '" + CodMarca + "' AND CodArt = '" + CodArt + "' AND Importato = 'COMET' and Fornitore='COMET' ";
SqlCommand commaggiorna = new SqlCommand(queryAggiornamento, conn);
try
{
commaggiorna.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(" " + ex);
}
}
else
{
string query2 = "INSERT INTO Articolo (CodMarca, CodArt, Fornitore, Importato, Descrizione, UM, Prezzo, PrezzoListino, Stato) VALUES (#CodMarca, #CodArt, #Fornitore, #Importato, #Descrizione, #UM, #Prezzo, #PrezzoListino, #Stato)";
SqlCommand myCommand = new SqlCommand(query2, conn);
myCommand.Parameters.AddWithValue("#CodMarca", CodMarca);
myCommand.Parameters.AddWithValue("#CodArt", CodArt);
myCommand.Parameters.AddWithValue("#Fornitore", Fornitore);
myCommand.Parameters.AddWithValue("#Importato", Fornitore);
myCommand.Parameters.AddWithValue("#Descrizione", Descrizione);
myCommand.Parameters.AddWithValue("#UM", UM);
decimal PrezzoNetto2 = Decimal.Parse(PrezzoNetto, System.Globalization.NumberStyles.Any);
myCommand.Parameters.AddWithValue("#Prezzo", PrezzoNetto2);
decimal PrezzoCasa2 = Decimal.Parse(PrezzoCasa, System.Globalization.NumberStyles.Any);
myCommand.Parameters.AddWithValue("#PrezzoListino", PrezzoCasa2);
DateTime dt = Convert.ToDateTime(DataAggiornamento);
myCommand.Parameters.AddWithValue("#Stato", "Aggiornamentoincorso");
myCommand.ExecuteNonQuery();
}
progressBarstatoaggiornamento.PerformStep();
int percent = (int)(((double)progressBarstatoaggiornamento.Value / (double)progressBarstatoaggiornamento.Maximum) * 100);
progressBarstatoaggiornamento.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBarstatoaggiornamento.Width / 2 - 10, progressBarstatoaggiornamento.Height / 2 - 7));
}
string queryNonDisponibili = "Update Articolo Set Stato='Nondisponibile' where Stato!='Aggiornamentoincorso' AND Fornitore='COMET' AND Importato='COMET'";
string queryNonDisponibili2 = "Update Articolo Set Stato='Disponibile' where Stato='Aggiornamentoincorso' AND Fornitore='COMET' AND Importato='COMET'";
SqlCommand comm = new SqlCommand(queryNonDisponibili, conn);
SqlCommand comm2 = new SqlCommand(queryNonDisponibili2, conn);
comm.ExecuteNonQuery();
comm2.ExecuteNonQuery();
Console.WriteLine("\n Passaggio Completato");
conn.Close();
db.chiudiconnessione();
dbConn.Close();
}
catch (Exception ex)
{
MessageBox.Show("La password è errata oppure " + ex);
}
Consider using SqlBulkCopy. Since you are running sql queries I would suggest you'd work server side as much as possible. Create a temp table in Sql Server, add all records to a datatable or array of datarows and use SqlBulkCopy to import. I think that is the fastest way to move all records to Sql Server.
From there you can synchronize the two tables in Sql Server with only a few queries.
I would use SqlBulkCopy ...
dbConn = new OleDbConnection(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" + dialog.FileName + "; Persist Security Info = False; Jet OLEDB:Database Password = " + textBoxPwdComet.Text + "; Mode = Share Deny None");
SqlConnection conn2 = db.apriconnessione();
string query = "SELECT CODMARCA,CODART,DESCR,UM,PRZNETTO,PRZCASA,DATAAGG FROM ARTICOLI";
OleDbDataAdapter da = new OleDbDataAdapter(query,dbConn);
DataTable dt = new DataTable();
da.Fill(dt);
conn2.Open();
SqlBulkCopy bulk = new SqlBulkCopy(conn2);
bulk.DestinationTableName = "ARTICOLI";
bulk.WriteToServer(dt);
conn2.close();
Im creating columns using mysql dynamically if column doesnt exist.. I got the code which works in mysql console but when it comes to c# its giving me "Fatal encountered during command execution"
SET #preparedStatement = (SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'tableName'
AND table_schema = DATABASE()
AND column_name = 'colName'
) > 0,
"SELECT 1",
"ALTER TABLE `tableName` ADD `colName` TINYINT(1) NULL DEFAULT '0';"
));
PREPARE alterIfNotExists FROM #preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
above code i converted into c# string as
string qry = "SET #preparedStatement = ( SELECT IF( (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME = '" + tname + "' AND COLUMN_NAME = '" + code + "_C' ) > 0, \"SELECT 1', \"ALTER TABLE " + tname + " ADD " + code + "_C int(3) NOT NULL default '0'; \" )); PREPARE alterIfNotExists FROM #preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists;";
what's the error getting?
Execution Code:
private void columnCreate_Load(object sender, EventArgs e)
{
string tname = "bca_i"; //for temprory
string code = "BCAXX";//for temprory
string qry = #"SET #preparedStatement = ( SELECT IF( (SELECT count(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME = '" + tname + "' AND COLUMN_NAME = '" + code + "_C' ) > 0, \"SELECT 1', \"ALTER TABLE " + tname + " ADD " + code + "_C int(3) NOT NULL default '0'; \" )); PREPARE alterIfNotExists FROM #preparedStatement; EXECUTE alterIfNotExists; DEALLOCATE PREPARE alterIfNotExists;";
try
{
using (MySqlConnection conn = new MySqlConnection(ConStr))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(qry, conn))
{
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The part
\"SELECT 1', \"A
does not match your original query at
"SELECT 1",
"A
Do you spot it? You replaced the " after 1 by an '.
I just figured other way for checking column exist.. Just used below query and checked if the column exists iterating through the loop of columns
string last_col = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'attendance' AND TABLE_NAME ='" + subCodeText.Text + "'";
where attendance is database and subCodeText.Text is my table name.
I am trying to select rows which are inbetween a startdate and an enddate in c# with sqlite.
my dates are formatted like this:
2015-05-16T17:22:04.920+02:00
which should be a valid format for sqlite (ref: http://www.sqlite.org/lang_datefunc.html)
i am trying to select the row like this:
string CmdString = "SELECT * FROM " + tablename + "WHERE DATETIME(timekey) >= DATETIME('2015-05-16T17:22:04.920+02:00') AND DATETIME(timekey) <= DATETIME('2015-05-16T17:24:04.920+02:00')";
SQLiteCommand cmd = new SQLiteCommand(CmdString, con);
SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
DataTable MatchDt = new DataTable();
sda.Fill(MatchDt);
The Error i get is:
SQLiteException: SQL logic error or missing database
What am I doing wrong?
You are missing a space char before the where:
string CmdString = "SELECT * FROM " + tablename + " WHERE DATETIME(timekey) >= DATETIME('2015-05-16T17:22:04.920+02:00') AND DATETIME(timekey) <= DATETIME('2015-05-16T17:24:04.920+02:00')";
And I would reccomend using the BETWEEN operator:
string CmdString = "SELECT * FROM " + tablename + " WHERE DATETIME(timekey) BETWEEN DATETIME('2015-05-16T17:22:04.920+02:00') AND DATETIME('2015-05-16T17:24:04.920+02:00')";
I am having a problem where my application works fine on the development enviroment, but when deployed to a customer just hangs without tripping any exceptions.
In order to deploy I have to change the login details (removed) and sql statements to those shown, which I suppose might be the issue but I'd expect any sql syntex errors to throw an exception. I have excluded infinite loops as a possibility (I think).
The only possibility I'm aware of is to use multithreading and hope the problem is solved, but I don't have that kind of time unless I can be certain that is the solution.
Frankly I'm at a loss and any tips / advice for extracting any kind of lead on the problem is appricated.
Here is the code:
but_exit.Enabled = false;
but_manual.Enabled = false;
//switch off gui timer to allow process messages
guiTimer.Enabled = false;
lbl_dyn_status.Text = "Finding records...";
/*create connection resources*/
/*MYSQl*/
//connect to mysql
/*
*/
var db_name = "";
var db_host = "";
var db_user = "";
var db_password = "";
var connectionString = "SERVER=" + db_host + ";" + "DATABASE=" +
db_name + ";" + "UID=" + db_user + ";" + "PASSWORD=" + db_password + ";";
MySqlConnection mysql_con = new MySqlConnection(connectionString);
//Create a list to store the result
List<string>[] mysql_idlist = new List<string>[1];
mysql_idlist[0] = new List<string>();
/*MSSQL*/
//connect to mssyql
db_user = "";
db_password = "";
db_name = "";
db_host = "";
System.Data.SqlClient.SqlConnection mssql_con = new System.Data.SqlClient.SqlConnection();
mssql_con.ConnectionString = "SERVER=" + db_host + ";" + "DATABASE=" +
db_name + ";" + "UID=" + db_user + ";" + "PASSWORD=" + db_password + ";";
//Create a list to store the result
List<string>[] mssql_idlist = new List<string>[2];
mssql_idlist[0] = new List<string>();
mssql_idlist[1] = new List<string>();
/*Processing logic*/
//first pass on mysql
try
{
mysql_con.Open();
//get id list
string mysql_idlist_query = "SELECT product_code FROM cscart_products";
MySqlCommand cmd = new MySqlCommand(mysql_idlist_query, mysql_con);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
mysql_idlist[0].Add(dataReader["product_code"] + "");
}
//close Data Reader
dataReader.Close();
//test content
/*foreach (var id in mysql_idlist[0]) {
lbl_dev.Text = lbl_dev.Text + id + " - ";
}*/
//close mysql connection
mysql_con.Close();
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
lbl_dev.Text = "(mysql) Cannot connect to server. Contact administrator";
break;
case 1045:
lbl_dev.Text = "(mysql) Invalid username/password, please try again";
break;
default:
lbl_dev.Text = "Unknown mysql error.";
break;
}
}
catch
{
lbl_dev.Text = "first mysql error";
}
//first pass on mssql
try
{
mssql_con.Open();
//get id list
//protect for duplicate skus
string mssql_idlist_query = "SELECT substring (RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10) as SKU, ID FROM Denton_multi.dbo.JH_TblFurniture6Colour WHERE substring (RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10) IN (SELECT substring(RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10))";
SqlCommand cmd = new SqlCommand(mssql_idlist_query, mssql_con);
//Create a data reader and Execute the command
SqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
mssql_idlist[0].Add(dataReader["SKU"] + "");
mssql_idlist[1].Add(dataReader["ID"] + "");
}
//close Data Reader
dataReader.Close();
mssql_con.Close();
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 0:
lbl_dev.Text = "(mssql) Cannot connect to server. Contact administrator";
break;
case 1045:
lbl_dev.Text = "(mssql) Invalid username/password, please try again";
break;
default:
lbl_dev.Text = "Unknown mssql error. " + ex.Number; ;
break;
}
}
catch
{
lbl_dev.Text = "first mssql error";
}
//compare lists and get ids that need inserting in mysql
List<string>[] insert_idlist = new List<string>[10];
insert_idlist[0] = new List<string>();//product code
insert_idlist[1] = new List<string>();//short description
insert_idlist[2] = new List<string>();//full description
insert_idlist[3] = new List<string>();//product id
insert_idlist[4] = new List<string>();//weight
insert_idlist[5] = new List<string>();//rrp price
insert_idlist[6] = new List<string>();//our price
insert_idlist[7] = new List<string>();//categories
insert_idlist[8] = new List<string>();//denton side id
insert_idlist[9] = new List<string>();//insert / update tag
List<string> dup_list = new List<string>();
var about_to_insert = 0;
foreach (var id in mssql_idlist[0])
{
if (mysql_idlist[0].Contains(id) == false)
{
//insert list
insert_idlist[0].Add(id);
insert_idlist[9].Add("i");
}
else
{
//update_list
insert_idlist[0].Add(id);
insert_idlist[9].Add("u");
}
}
//construct full mssql dataset for insert items
//final pass on mssql
try
{
mssql_con.Open();
foreach (var id in insert_idlist[0])
{
//top 1 for duplicate removal
var mssql_select = "SELECT Denton_Multi.dbo.tblproductcategorys.*, Denton_Multi.dbo.JH_TblFurniture6Colour.*, substring(RIGHT('00'+ CAST (Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10) as SKU, suppliers.[supplier name], (select top 1 [item description] from Denton_Multi.dbo.JH_TblFurniture4item where [supplier code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[supplier code] and [item code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[item code] And [Delete] = 0) as [item description], (select top 1 [model description] from Denton_Multi.dbo.JH_TblFurniture3Range where [supplier code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[supplier code] and [model code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[model code]) as [range description] FROM Denton_Multi.dbo.JH_TblFurniture6Colour join Denton_Multi.dbo.tblproductcategorys on Denton_Multi.dbo.tblproductcategorys.CategoryID = Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] join Denton_Multi.dbo.Suppliers on Denton_Multi.dbo.Suppliers.[supplier code] = Denton_Multi.dbo.JH_TblFurniture6Colour.[supplier code] WHERE ExportWeb = 1 AND substring(RIGHT('00'+ CAST (Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar ), patindex('%[^0]%',RIGHT('00'+ CAST (Denton_Multi.dbo.JH_TblFurniture6Colour.[product group] AS varchar), 2) + CAST( ID AS Varchar )), 10) = '"+id+"'";
SqlCommand cmd = new SqlCommand(mssql_select, mssql_con);
//Create a data reader and Execute the command
SqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
insert_idlist[1].Add(dataReader["Supplier Name"] + " " + dataReader["Range Description"] + " " + dataReader["Item Description"]);
insert_idlist[3].Add(dataReader["Sale Price"] + "");
insert_idlist[2].Add(dataReader["WebDesc"] + "");
//insert_idlist[3].Add(dataReader["id"] + "");removed
insert_idlist[4].Add(dataReader["WebDimensions"] + "");
insert_idlist[5].Add(dataReader["RRP"] + "");
insert_idlist[6].Add(dataReader["Normal Price"] + "");
insert_idlist[7].Add("482"); //add me
insert_idlist[8].Add(dataReader["ID"] + "");
about_to_insert = about_to_insert + 1;
}
lbl_dyn_status.Text = "Record 0 of " + about_to_insert + "updated.";
dataReader.Close();
}
//close mysql connection
mssql_con.Close();
}
catch (SqlException ex)
{
switch (ex.Number)
{
case 0:
lbl_dev.Text = "(mssql) Cannot connect to server. Contact administrator";
break;
case 1045:
lbl_dev.Text = "(mssql) Invalid username/password, please try again";
break;
default:
lbl_dev.Text = "Unknown mssql error. "+ex.Number;
break;
}
}
catch
{
lbl_dev.Text = "second mssql error";
}
//insert data in mysql db
try
{
//final mysql pass
var inc = insert_idlist[0].Count() - 1;
if (about_to_insert > 0 && insert_idlist[0][0].Count() > 0)
{
mysql_con.Open();
for (int x = 0; x <= inc; x++)
{
int pid = 0;
if (insert_idlist[9][x] == "u")
{
//get web side product_id for updates
var sku = insert_idlist[0][x];
var get_id = "SELECT product_id FROM cscart_products WHERE product_code = '" + sku + "' LIMIT 1";
MySqlCommand do_get_id = new MySqlCommand(get_id, mysql_con);
MySqlDataReader rpid = do_get_id.ExecuteReader();
//get id
while (rpid.Read())
{
pid = Convert.ToInt32(rpid["product_id"]);
}
rpid.Close();
}
/*main record*/
var mysql_product = "";
if (insert_idlist[9][x] == "u")
{
mysql_product = "UPDATE cscart_products SET product_code = #product_code, list_price = #rrp, status='D' WHERE product_id = '" + pid + "'";
}
else
{
mysql_product = "INSERT INTO cscart_products (product_code, list_price, status) VALUES (#product_code, #rrp, 'D')";
}
MySqlCommand product_insert = new MySqlCommand(mysql_product, mysql_con);
product_insert.Parameters.Add(new MySqlParameter("#product_code", insert_idlist[0][x]));
product_insert.Parameters.Add(new MySqlParameter("#rrp", insert_idlist[5][x]));
product_insert.ExecuteNonQuery();
var insertid = product_insert.LastInsertedId;
//get mssql id records
var sql_ID = insert_idlist[8][x];
var stock_sql = "SELECT * FROM dbo.TblSupplierDelivery INNER JOIN dbo.TblManagerStockListings ON dbo.TblSupplierDelivery.ID = dbo.TblManagerStockListings.ID WHERE dbo.TblSupplierDelivery.ID = '" + sql_ID + "'";
mssql_con.Open();
SqlCommand cmd = new SqlCommand(stock_sql, mssql_con);
//Create a data reader and Execute the command
SqlDataReader dataReader = cmd.ExecuteReader();
//insert extended data fields
while (dataReader.Read())
{
var delivery_time = dataReader["Delivery Weeks"];
var stock_quant = Convert.ToInt16(dataReader["WHTotal"]) - Convert.ToInt16(dataReader["TotalAv"]);
var sale_price = insert_idlist[3][x];
var prod_ex = "";
if (insert_idlist[9][x] == "u")
{
prod_ex = "UPDATE cscart_oo_product_extend SET product_id = '" + pid + "', transfer_date = now(), sale_price = '" + sale_price + "', stock_due_date = '" + delivery_time + "' WHERE product_id = '" + pid + "'";
}
else
{
prod_ex = "INSERT INTO cscart_oo_product_extend (product_id, transfer_date, sale_price, stock_due_date) VALUES ('" + insertid + "', now(), '" + sale_price + "', '" + delivery_time + "')";
}
MySqlCommand product_ex_insert = new MySqlCommand(prod_ex, mysql_con);
product_ex_insert.ExecuteNonQuery();
//this is always an update
if (Convert.ToString(insertid) == "0")
{
insertid = pid;
}
var stock_insert = "UPDATE cscart_products SET amount = '" + stock_quant + "' WHERE product_id = '" + insertid + "'";
MySqlCommand product_stock_insert = new MySqlCommand(stock_insert, mysql_con);
product_stock_insert.ExecuteNonQuery();
}
//close Data Reader
dataReader.Close();
mssql_con.Close();
/*description*/
var mysql_desc = "";
if (insert_idlist[9][x] == "u")
{
mysql_desc = "UPDATE cscart_product_descriptions SET product_id = #id, product = #product_name, full_description = #product_desc WHERE product_id = #id";
}
else
{
mysql_desc = "INSERT INTO cscart_product_descriptions (product_id, product, full_description) VALUES (#id, #product_name, #product_desc)";
}
MySqlCommand product_desc = new MySqlCommand(mysql_desc, mysql_con);
product_desc.Parameters.Add(new MySqlParameter("#id", insertid));
product_desc.Parameters.Add(new MySqlParameter("#product_name", insert_idlist[1][x]));
product_desc.Parameters.Add(new MySqlParameter("#product_desc", insert_idlist[2][x]));
product_desc.ExecuteNonQuery();
//category
var mysql_cat = "";
if (insert_idlist[9][x] == "i")
{
mysql_cat = "INSERT INTO cscart_products_categories (product_id, category_id) VALUES (#id, #cat_id)";
MySqlCommand product_cat = new MySqlCommand(mysql_cat, mysql_con);
product_cat.Parameters.Add(new MySqlParameter("#id", insertid));
product_cat.Parameters.Add(new MySqlParameter("#cat_id", insert_idlist[7][x]));
product_cat.ExecuteNonQuery();
}
//price
var mysql_price = "";
if (insert_idlist[9][x] == "u")
{
mysql_price = "UPDATE cscart_product_prices SET product_id = #id, price = #our_price, lower_limit = '1' WHERE product_id = #id";
}
else
{
mysql_price = "INSERT INTO cscart_product_prices (product_id, price, lower_limit) VALUES (#id, #our_price, '1')";
}
MySqlCommand product_price = new MySqlCommand(mysql_price, mysql_con);
product_price.Parameters.Add(new MySqlParameter("#id", insertid));
product_price.Parameters.Add(new MySqlParameter("#our_price", insert_idlist[6][x]));
product_price.ExecuteNonQuery();
lbl_dyn_status.Text = "Record " + x + " of " + about_to_insert + "updated.";
}
mysql_con.Close();
}
}
catch
{
lbl_dev.Text = "upload error";
}
//reset gui timer for next idle period
minutes_left = 10;
lbl_dyn_status.Text = "Time until next automatic update: " + minutes_left + " minutes.";
guiTimer.Start();
but_exit.Enabled = true;
but_manual.Enabled = true;
}
OK. I have determined the issue is with slow response from an sql statement