Left Join Mysql query resulting wrong - c#

I have a mysql left join query . This query runs ok . But the left joined table not getting values . Please go through below query . I am working in C#
void getstuinfo()
{
try
{
MySqlCommand com = new MySqlCommand("select stumaster.stuname,"+
"stumaster.lname,"+
"stumaster.fname,"+
"stumaster.mname,"+
"stumaster.fa_calty,"+
"stumaster.sex,"+
"castmaster.castdisp,"+
"stumaster.castcode,"+
"stumaster.nwscs "+
"from stumaster "+
" left join castmaster on stumaster.castcode = castmaster.castcode "+
" where grno = " + Convert.ToInt32(textBox1.Text).ToString(), con_db.con);
MySqlDataReader dr1 = com.ExecuteReader();
if (dr1.HasRows)
{
while (dr1.Read())
{
textBox2.Text = (dr1[("stuname")].ToString());
textBox4.Text = (dr1["lname"]).ToString();
textBox5.Text = (dr1["fname"]).ToString();
textBox6.Text = (dr1["mname"]).ToString();
comboBox5.Text = (dr1["fa_calty"]).ToString();
comboBox1.Text = (dr1["castdisp"]).ToString();
textBox7.Text = (dr1["castcode"]).ToString();
textBox9.Text = (dr1["nwscs"]).ToString();
string wsex = (dr1["sex"]).ToString();
if (wsex == "M")
{
radioButton1.Checked = true;
}
else
{
radioButton2.Checked = true;
}
}
dr1.Close();
}
else
{
MessageBox.Show("Not a Valid G.R.No.", " Student Information ");
dr1.Close();
textBox1.Focus();
return;
}
}
catch (FormatException)
{
MessageBox.Show("Date is Invalid ");
}
}

you have to give the table name with grno
ie
stumaster.grno = conditiion

Related

Connection error after update mysql value C#

so my idea was once user will be loged in it will add +1 to the other table and online value in my mysql. I have done code like it's bellow. Once I have debug. I have inserted username and password but once I have press login button it says Error Connection. I am sure I have did something wrong in code but cant get it sort. So am trying to get help from you guys. Thanks
private void loginBtn_Click(object sender, EventArgs e)
{
try
{
if (txtUsername.Text != "" && txtPassword.Text != "")
{
con.Open();
string query = "SELECT id,username,password,email,fullname,company,uploads,avatar,account_type FROM users WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlDataReader row;
row = con.ExecuteReader(query);
if (row.HasRows)
{
while (row.Read())
{
Properties.Settings.Default.username = row["username"].ToString();
Properties.Settings.Default.email = row["email"].ToString();
Properties.Settings.Default.fullname = row["fullname"].ToString();
Properties.Settings.Default.company = row["company"].ToString();
Properties.Settings.Default.uploads = row["uploads"].ToString();
Properties.Settings.Default.user_avatar = row["avatar"].ToString();
MySqlCommand newcmd = new MySqlCommand("UPDATE company SET online = online + 1 WHERE name = '" + row["company"].ToString() + "'");
try
{
newcmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
con.Close();
MessageBox.Show(ex.Number.ToString() + " -> " + ex.Message.ToString());
return;
}
}
this.Hide();
dashboard dash = new dashboard();
dash.Show();
}
else
{
MessageBox.Show("Nie znaleziono użytkownika", "Information");
}
}
else
{
MessageBox.Show("Nazwa użytkownika lub hasło jest nie poprawne", "Information");
}
}
catch
{
MessageBox.Show("Błąd połączenia", "Information");
}
For your question, you have connection error when you log in.
The error may be that there is already an open data reader associated with this connection
which must be closed, so close the data reader connection.
You could try the following code to get it.
private void btn_Submit_Click(object sender, EventArgs e)
{
conn.Open();
try
{
if (txtUsername.Text != "" && txtPassword.Text != "")
{
string query = "SELECT id,username,password,email,fullname,company,uploads,avatar,account_type FROM users WHERE username ='" + txtUsername.Text + "' AND password ='" + txtPassword.Text + "'";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.ExecuteScalar();
MySqlDataReader row;
row = cmd.ExecuteReader();
string company=null;
if (row.HasRows)
{
while (row.Read())
{
Properties.Settings.Default.username = row["username"].ToString();
Properties.Settings.Default.email = row["email"].ToString();
Properties.Settings.Default.fullname = row["fullname"].ToString();
Properties.Settings.Default.company = row["company"].ToString();
Properties.Settings.Default.uploads = row["uploads"].ToString();
Properties.Settings.Default.user_avatar = row["avatar"].ToString();
company = row["company"].ToString();
MessageBox.Show(row["company"].ToString(), "Note", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
row.Close();
cmd.CommandText = "UPDATE company SET online = online + 1 WHERE name = '" + company + "'";
try
{
cmd.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Number.ToString() + " -> " + ex.Message.ToString());
}
this.Hide();
dashboard dash = new dashboard();
dash.Show();
}
else
{
MessageBox.Show("Nie znaleziono użytkownika", "Information");
}
}
else
{
MessageBox.Show("Nazwa użytkownika lub hasło jest nie poprawne", "Information");
}
}
catch
{
MessageBox.Show("Błąd połączenia", "Information");
}
finally
{
conn.Close();
}
}
Result:

How to search over whole cities in combobox

I inserted about 18 cities in government field and I can search over each city I want by ID, but now I want to search over all of the cities by ID when I do not select any thing in combobox.
string c = "%";
c = comboBox1.Text;
int a;
a = Convert.ToInt32(textBox1.Text);
a = int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand("select * from Person where ( PER_ID = '" + a + "' and GOV_NAME_AR = '" + c + "') ", con);
cmd.CommandTimeout = 600;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
// MessageBox.Show("Successfully found Data");
// SqlDataReader DR = cmd.ExecuteReader();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
}
else
{
MessageBox.Show("data not found");
}
con.Close();
You could change the statement in case of "nothing selected"
if (ComboBox.Text == string.Empty)
{
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
Remarks:
use variable names like string sCity = "%"; instead of string c = "%";
use parameters for your sql statements where ( PER_ID = #Person) and cmd.Parameters.Add("#Person", SqlDbType.Int32).Value = int.Parse(textBox1.Text);
If I get you correctly, you don't want where clause on GOV_NAME_AR when combobox1 is not selected.
if( ComboBox.SelectedItem == null ) {
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
You could do a check on the ComboBox.SelectedText like this:
if (comboBox1.SelectedText=="")
{
//SQL statement should not restrict on the c value
}
else
{
//Use your regular SQL query here.
}

C# IF statement for a checkbox Value Points wont register into DB

I need help for my If Statement, at first it registers into the DB but only the value of 8, even if multiple values are tick. I know my if statements are wrong, but i have no idea what else to do. So should I remove the use another way if it's possible or I just messed a code up? I'm really bad at If's statement.
String points = null;
String ServiceCarWash = "Not Booked";
String ServiceCarPolish = "Not Booked";
String ServiceCarWax = "Not Booked";
int CustomerID = 0;
private void btnBook_Click_1(object sender, EventArgs e)
{
try
{
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
if (CbCarwash.Checked)
{
ServiceCarWash = "Booked";
}
if (CbCarPolish.Checked)
{
ServiceCarPolish = "Booked";
}
if (CbCarWax.Checked)
{
ServiceCarWax = "Booked";
}
{
if (txtMember.Text.Equals("VIP"))
{
if (ServiceCarPolish == "Booked")
{
points = "20";
}
if (ServiceCarWash == "Booked")
{
points = "2";
}
if (ServiceCarWax == "Booked")
{
points = "8";
}
}
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points = "0";
}
if (ServiceCarWash == "Booked")
{
points = "0";
}
if (ServiceCarWax == "Booked")
{
points = "0";
}
}
string query1 = "UPDATE *Customer set Points='" + points + "'";
OleDbCommand command1 = new OleDbCommand(query1);
command1.Connection = connection;
command1.ExecuteNonQuery();
MessageBox.Show("Your time has been booked.");
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
How to accumulate points in code as per comments on previous question. See comments in the below and look out for the += signs.
//String points = null;
int points = 0;
String ServiceCarWash = "Not Booked";
String ServiceCarPolish = "Not Booked";
String ServiceCarWax = "Not Booked";
int CustomerID = 0;
private void btnBook_Click_1(object sender, EventArgs e)
{
try
{
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
if (CbCarwash.Checked)
{
ServiceCarWash = "Booked";
}
if (CbCarPolish.Checked)
{
ServiceCarPolish = "Booked";
}
if (CbCarWax.Checked)
{
ServiceCarWax = "Booked";
}
{
if (txtMember.Text.Equals("VIP"))
{
if (ServiceCarPolish == "Booked")
{
points += 20;
}
if (ServiceCarWash == "Booked")
{
points += 2;
}
if (ServiceCarWax == "Booked")
{
points += 8;
}
}
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points += 0;
}
if (ServiceCarWash == "Booked")
{
points += 0;
}
if (ServiceCarWax == "Booked")
{
points += 0;
}
}
//string query1 = "UPDATE *Customer set Points='" + points + "'";
string query1 = "UPDATE *Customer set Points='" + points.ToString() + "'";
OleDbCommand command1 = new OleDbCommand(query1);
command1.Connection = connection;
command1.ExecuteNonQuery();
MessageBox.Show("Your time has been booked.");
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
Set your fields before inserting in to the database.
Move this code to the end of the method (or to just before the Customer update):
connection.Open();
String query = "INSERT into Booking ([Time],[Date],[CID],[VehicleNumber],[CarWash],[CarPolish],[CarWax]) VALUES('" + cmbTime.Text + "','" + dateTimePicker1.Text + "','" + CustomerID + "','" + txtVn.Text + "','" + ServiceCarWash + "','" + ServiceCarPolish + "','" + ServiceCarWax + "')";
OleDbCommand command = new OleDbCommand(query);
command.Connection = connection;
command.ExecuteNonQuery();
Also, is *Customer the right table name, should it not just be Customer?
Check the value of your checkboxes to see if they are coming through correctly, then step through your IF's to make sure they calculate correctly. Refactoring in to smaller methods may help you break down the problem so that it is less complex and easier to work with.
Also check your brackets - you have some crazy stuff going on. See the second to last bracket below and you also have something weird going on a bit higher up with a bracket the wrong way around.
else if (txtMember.Text.Equals("Walk-In"))
{
if (ServiceCarPolish == "Booked")
{
points = "0";
}
if (ServiceCarWash == "Booked")
{
points = "0";
}
if (ServiceCarWax == "Booked")
{
points = "0";
}
**{**
}
Also make sure txtMember.Text always has a value so that points are set. Depending on your input, you can make your code a bit more robust by comparing tolower() in strings, e.g.: txtMember.Text.ToLower().Equals("walk-in").
And step through with the debugger! :)

Program stops responding when deployed

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

Data gets Truncated from database

I am designing a Window based application in C# using VS2010 and SqlServer2008-r2. I am
using a service Based Database(.mdf),in it there is a table having four fields, if i Store
data in the table and close the application and re-run the application the data gets Lost.
Why so and how to get rid of it.
I am Using Following routine for saving
private void Save(object sender, EventArgs e)
{
Program.connection.Close();
bool k = srchpreventry();
try
{
if (k)
{
string query = " update orderform set Enrolment_Expected = " + textBox2.Text + ", Stock_on_Hand=" + textBox3.Text + ", Number_Required = "+ textBox4.Text + " where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
else
{
// Program.connection.Open();
string query = "insert into orderform(Name,Enrolment_Expected,Stock_on_Hand,Number_Required) values('" + textBox1.Text + "', '" + textBox2.Text + "', ' " + textBox3.Text + "',' " + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
}
catch (Exception ae)
{
string str = ae.ToString();
MessageBox.Show(str);
}
finally
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
Program.connection.Close();
}
}
public bool srchpreventry()
{
Program.connection.Open();
string query = " Select name from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
dtr.Close();
return true;
}
else
{
dtr.Close();
return false;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Program.connection.Close();
Program.connection.Open();
string query = " Select * from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
textBox2.Text = dtr[1].ToString();
textBox3.Text = dtr[2].ToString();//GetString(2);
textBox4.Text = dtr[3].ToString();
}
else
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
public static SqlConnection connection = null;
static string appath = Library_Records.Program.app_path;
string connectionstring = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath);
static string dbfiles = null;
internal static string app_path
{
get { return dbfiles = "|Datadirectory|\\records.mdf"; }
}
/*******************datagrid code********************/
Program.connection.Open();
string query = "select * from orderform";
SqlDataAdapter MyDA = new SqlDataAdapter();
MyDA.SelectCommand = new SqlCommand(query, Program.connection);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
Check to see if you can increase the characters allowed in the column for example nvarchar(max) cause now it could be nvarchar(200) - this is just an example
In Visual Studio?
You are not by chane having VIsual Studio load the same empty database again every time you start debug?
and close the application and re-run the application the data gets Lost.
Either someone ignores errors that get thrown on insert, does not commit a transaction or tvisal studio just ocpies the same rdatabase template into the directory every time you start.
I strongly (emphasis on strongly) suggest that you start using stored procedures (either in code or in the database), but besides that.. you don't start a transaction or something similar?
Or post the Program.Connection class code into the question.

Categories

Resources