connection status using Mysql database - c#

i'm using MySQL Database with my c# application , and the database in server in locally.
In Each function in the application (Button click, etc.) i open the connection and in the end i close it, like this:
private void btn_addAccount_Click(object sender, EventArgs e)
{
try
{
**objConn.Open();**
//
MySqlCommand cmd;
if(from == "bill_Details")
cmd = new MySqlCommand("insert into accounts (acc_Name,acc_Person,acc_Number,acc_Place,acc_Date,cus_Sup) values ('" + txbName.Text + "','" + txbPerson.Text + "','" + txbNumber.Text + "','" + txbPlace.Text + "','" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "',"+ Bill_Details.cus_Sup +")", objConn);
else
cmd = new MySqlCommand("insert into accounts (acc_Name,acc_Person,acc_Number,acc_Place,acc_Date,cus_Sup) values ('" + txbName.Text + "','" + txbPerson.Text + "','" + txbNumber.Text + "','" + txbPlace.Text + "','" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "'," + Suppliers.cus_Sup + ")", objConn);
cmd.ExecuteNonQuery();
**objConn.Close();**
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I felt in this way that the application need more time to open and close the connection !
is't right like that or i have to open the connection in the starting of application and close it when it close !?

Related

Problem with inserting unique value into SQL Server in C#

My code doesn't catch the exception when I try to add the same user to the database and I don't really know how to change it.
try
{
SqlConnection.Open();
string sqlZapytanie = "INSERT INTO Host Values('" + host.Name + "','" +
host.Surname + "'," + host.PESEL + ",'" + host.City + "','" + host.Street + "', '" + host.House_number + "','" + host.Apartament_number + "','" + host.e_mail + "'," + host.Phone_number + ",'"+host.Login+"')";
try
{
SqlCommand.Connection = SqlConnection;
SqlCommand.CommandText = sqlZapytanie;
SqlCommand.ExecuteNonQuery();
}
catch(SqlException sqlex)
{
MessageBox.Show(sqlex.Message, "Zduplikowany użytkownik.", MessageBoxButton.OK);
}
Perhaps the error to be returned is not type SqlException but type Exception.

how to solve error Number of query values and destination fields are not the same. in c# windows application

how to solve error Number of query values and destination fields are not the same. in c# windows application
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
cmd.CommandText = "Insert into purchase(Bill_No,Tax_Invoice_No,Date,Supplier_ID,Supplier_Name,Supplier_GST_No,Product_ID,Product_Name,Product_Type,Product_Price,Product_Qty,Amount,Gross_Total,CGST,SGST,Total,Round_Off,Final_Total,Bill_Detail) values('" + Bill_No.Text + "','" + Tax_Invoice_No.Text + "','" + Date.Text + "','" + Supplier_ID.Text + "','" + Supplier_Name.Text + "','" + Supplier_GST_No.Text + "','" + dataGridView3.Rows[i].Cells["Product_ID"].Value + "','" + dataGridView3.Rows[i].Cells["Product_Name"].Value +"','" + dataGridView3.Rows[i].Cells["Product_Type"].Value + "','" + dataGridView3.Rows[i].Cells["Product_Price"].Value + "','" + dataGridView3.Rows[i].Cells["Product_Qty"].Value + "','" + dataGridView3.Rows[i].Cells["Amount"].Value + "','" + Gross_Total.Text + "','" + CGST.Text + "','" + SGST.Text + "','" + Total.Text + "','" + Round_Off.Text + "','" + Final_Total.Text + "','" + Bill_Detail.Text + "')";
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
database table
Click Here to View Dataabase
make sure that the Database table(purchase) value are the same with your array.
afterthought:
Query should be : Insert into purchase(table columns) values();

Insert Query in C# with MS access Database

When I am inserting data in MS access database .it is not giving any error but data not inserted in database
code:
private void btnsubmit_Click(object sender, EventArgs e)
{
int row = dataGridView1.RowCount;
for (int i = 0; i < row - 1; i++)
{
String str = "insert into JDS_Data(job_no,order_no,Revision,DesignSpec,Engine_Type,date,LE_IN_Designer,CPH_Designer,Exp_Del_Week,Action_code,Rev_Description,Ref_pattern,Name_of_mock_up,EPC_Drawing,Turbocharger_no_Type,Engine_Specific_Requirement,Draft_sketch_with_details,Air_cooler_type,Description_of_Job,SF_No,Standard,Prority_Sequence,Remark,Part_family,Modified_Date,User) values('" + txtjobno.Text + "','" + txtorderno.Text + "','" + txtrevison.Text + "','" + txtds.Text + "','" + txtenginetype.Text + "','" + dateTimePicker1.Text + "','" + txtleindesigner.Text + "','" + txtcphdesigner.Text + "','" + txtexpweek.Text + "','" + txtactioncode.Text + "','" + txtrevdescription.Text + "','" + txtrefpatern.Text + "','" + txtmockup.Text + "','" + txtepcdwg.Text + "','" + txtturbono.Text + "','" + txtenginereq.Text + "','" + txtdraft.Text + "','" + txtaircolertype.Text + "','" + txtdespjob.Text + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[3].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[4].Value.ToString() + "','" + DateTime.Today + "','" + mdlconnection.user_name + "')";
int dd = mdlconnection.excuteQuery(str);
MessageBox.Show(str);
//if (dd > 0)
{
MessageBox.Show("Data Saved Successfully..!!!");
}
}
}
Code:
public static int excuteQuery(string q)
{
int d = 0;
try
{
OleDbCommand cmd = new OleDbCommand(q, con);
d = cmd.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return d;
}
if you are using DataContext (you provided to little info)
you should rewrite your statement to match the example:
var customers = db.ExecuteQuery<Customer>(#"SELECT CustomerID, CompanyName, ContactName, ContactTitle,
Address, City, Region, PostalCode, Country, Phone, Fax
FROM dbo.Customers
WHERE City = {0}", "London");
I should suggest to use this tutorial for the connection instead actually

Code Doesn't work. C# Execute Non Query

string conStr = null;
SqlCommand cmd;
SqlConnection cnn;
string sql = null;
conStr = "Data Source=DELL-PC\\SQLEXPRESS;Initial Catalog=DBMSI;Integrated Security=True";
sql = "insert into CEC_Employee values('"+empid + "','" + name + "','" + fname + "','" + mname + "','" + lname + "','" + address + "','" + postcode + "','" + job + "','" + sdate + "','" + whours + "','" + sph + "','" + spa + "','" + location + "','" + working + "','" + gender + "','" + dob + "','" + pn + "','" + exp + "','" + vtype + "','" + vexp + "','" + qualification + "','" + email + "','" + number + "','" + nin + "','" + sort + "','" + acc + "','" + bank + "','" + nname + "','" + rel + "','" + addkin + "','" + cnokin + "','" + emailkin + "')";
cnn = new SqlConnection(conStr);
try
{
cnn.Open();
cnn = new SqlConnection(conStr);
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Open();
MessageBox.Show("Employee Details registered Succesffuly");
// Keeps on moving to the Exception part of the code. Doesn't execute the try portion of the program.
}
catch (Exception ex)
{
MessageBox.Show("Error Occoured - Employee Details were not recorded");
}
Found the code online. Please help to make it work. Thanks!
Hopefully your primary key on CEC_Employee isn't "empid", and if it is set to be an autonumber, like IDENTITY(1,1), the SQL command will fail as it won't let you hand it a primary key value.
This is speculation of course, since you haven't posted the actual exception message or stack trace.

Data not inserting in c# but same data is inserted in SQL Server query browser

I have a link button in my gridview at which I have some to insert value in table but it is not inserting but query data on debug mode when I tested on SQL Server it is inserted so whats the problem
protected void gvPO_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
c.GetConection();
SqlCommand cmd = new SqlCommand("delete from tmpMateIN", c.con);
cmd.ExecuteNonQuery();
DataTable dt;
int index = Convert.ToInt32(e.CommandArgument);
gvPO.SelectedIndex = index;
if (Convert.ToInt16(gvPO.SelectedIndex) < 0)
{
lblMsg.Text = "Please Select Code !";
return;
}
dt = oAccount.GetPO((int)Session["CompCode"], 79, Convert.ToInt16(((LinkButton)gvPO.Rows[gvPO.SelectedIndex].Cells[0].FindControl("lnkCode")).Text.ToString()));
for (int i = 0; i < dt.Rows.Count; i++)
{
String s6 = "insert into tmpMateIN(compcode ,msttype ,mstcode,mstdate ,mstchno ,mstblno ,mstbldt ,mstcust ,itdsrno , itditem ,itdquan ,itdrema ,itemname ,acctname ,ItmSize , unitname ,itemsize ,chno , chdt ,godown, packsize ,itdRate , itdDisc , itdAmou , mstInvNo , mstOrdNo,mstInvDt ,mstOrdDt ,mstrema , mstexcDes , msttaxDes ,msttaxper , mstfrghtDes , mstfrghtper , mstdeliDes ,mstpayDes , mstvaliDes, mstqno, mstqdt , itdthickness , itdlength ,itdwidth ,itdweight, itdtowt , acctaddr , custemail , mstpayMode , mstdepa,itdrefq,itdorgq)values(" + (int)Session["CompCode"] + ",79,'" + dt.Rows[i]["mstcode"] + "','" + dt.Rows[i]["mstdate"] + "'," + dt.Rows[i]["mstchno"] + ",'" + dt.Rows[i]["mstchno"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstptcode"] + "','" + (i + 1) + "','" + dt.Rows[i]["itditem"] + "','" + dt.Rows[i]["itdquan"] + "','" + dt.Rows[i]["itdrema"] + "','" + dt.Rows[i]["itdnarr"] + "','" + dt.Rows[i]["AcctName"] + "','" + dt.Rows[i]["itdnarr"] + "','" + dt.Rows[i]["UnitName"] + "' ,'" + dt.Rows[i]["itdunit"] + "','','" + dt.Rows[i]["mstdate"] + "','',''," + dt.Rows[i]["itdRate"] + "," + dt.Rows[i]["itdamou"] + " ," + dt.Rows[i]["itdAmou"] + ",'" + dt.Rows[i]["mstInvNo"] + "','" + dt.Rows[i]["mstindno"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstrema"] + "','','','" + dt.Rows[i]["mstTaxPer"] + "','" + dt.Rows[i]["mstfrghtDes"] + "','" + dt.Rows[i]["mstfrghtper"] + "','" + dt.Rows[i]["mstdeliDes"] + "','" + dt.Rows[i]["mstpayDes"] + "','" + dt.Rows[i]["mstvaliDes"] + "','" + dt.Rows[i]["mstqno"] + "','" + dt.Rows[i]["mstpodate"] + "','" + dt.Rows[i]["itdthickness"] + "','" + dt.Rows[i]["itdsource"] + "','" + dt.Rows[i]["itddestin"] + "','" + dt.Rows[i]["itdweight"] + "','" + dt.Rows[i]["itdtowt"] + "','','" + dt.Rows[i]["acctaddr"] + "','" + dt.Rows[i]["mstpayMode"] + "','" + dt.Rows[i]["mstContactPerson"] + "','" + dt.Rows[i]["mstlotno"] + "','" + dt.Rows[i]["mstsection"] + "' )";
SqlCommand cmd1 = new SqlCommand(s6, c.con);
cmd1.ExecuteNonQuery();
}
c.CloseConnection();
Response.Redirect("Poreport.aspx");
}
}
You can run the SQL Server Profiler to see if the call is made to SQL Server for insertion at the time of execution of your program.
Suggestion: Why don't you use stored procedure instead of having this inline query this way:
var dr = dt.Rows[i];
SqlCommand cmd1 = new SqlCommand(s6, c.con);
cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.CommandText = "tmpMateIN_Insert";
cmd1.Parameters.Add(new SqlParameter("#compcode", (int)Session["CompCode"]);
cmd1.Parameters.Add(new SqlParameter("#msttype", 79);
cmd1.Parameters.Add(new SqlParameter("#mstcode", dr["mstcode"]);
cmd1.Parameters.Add(new SqlParameter("#mstdate", dr["mstdate"]);
// ...
cmd1.ExecuteNonQuery();
ADDED:
OR if you really want to stick with an inline query then preferred approach is to use parameterized inline query as shown below:
String s6 = "insert into tmpMateIN(compcode, msttype, mstcode, mstdate, ..." +
"values(#compcode, #msttype, #mstcode, #mstdate, ...";
cmd1.Parameters.Add(new SqlParameter("#compcode", (int)Session["CompCode"]);
cmd1.Parameters.Add(new SqlParameter("#msttype", 79);
cmd1.Parameters.Add(new SqlParameter("#mstcode", dr["mstcode"]);
cmd1.Parameters.Add(new SqlParameter("#mstdate", dr["mstdate"]);
// ...
cmd1.ExecuteNonQuery();

Categories