How to insert rows into Mysql database without duplicate? - c#

When i want to insert a row into my MySql database 4 rows will be inserted instead of 1. Could you help me?
MySqlConnection con = new MySqlConnection(cs);
string Query = "Insert Into csokolade (márka,ár,darab) values('" + this.Marka_Textbox.Text + "','" + this.Ar_Textbox.Text + "','" + this.Darab_Textbox.Text + "')";
MySqlCommand com = new MySqlCommand(Query, con);
com.ExecuteNonQuery();
EDIT: Here is the part of the code that has to insert the row:
try
{
MySqlConnection con = new MySqlConnection(cs);
con.Open();
int a = 0;
string q = "select count(*) from csokolade where márka='" + this.Marka_Textbox.Text + "';";
MySqlCommand com = new MySqlCommand(q, con);
try
{
a = Convert.ToInt32(com.ExecuteScalar());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (a == 0)
{
string Query = "Insert Into csokolade (márka,ár,darab) values('" + this.Marka_Textbox.Text + "','" + this.Ar_Textbox.Text + "','" + this.Darab_Textbox.Text + "')";
com = new MySqlCommand(Query, con);
com.ExecuteNonQuery();
}
else
{
MessageBox.Show("Ez a rekord már létezik!");
return;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Related

I have tried to run this update method using Oracle command but I keep getting an error as "sql command not properly ended"

My code
public void SaveEdits()
{
string SQL = "UPDATE SURVEY_CAMPAIGN SET OUTGOING_VDN =" + txtOutgoing.Value + "AND LANG_CD =" + txtlang.Value + "AND ANNOUNCEMENT_FOLDER =" + txtAnnouc.Value + "AND EXCEEDED_AUDIO =" + txtExceed.Value + "AND VALID_ENTRY_AUDIO =" + txtExit.Value +
" WHERE CAMPAIGN_ID =" + CampignsDRP.SelectedValue;
try
{
using (OracleConnection conn = SingleConnection.Instance.ActiveConn)
{
conn.Open();
OracleCommand cmd = conn.CreateCommand();
OracleDataAdapter dataAdapter = new OracleDataAdapter(SQL, conn);
System.Data.DataSet db = new System.Data.DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = SQL;
int result = cmd.ExecuteNonQuery();
dataAdapter.Fill(db, "Campaign");
cmd.Dispose();
conn.Close();
}
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "UpdateCompleted()", true);
}
catch (Exception ex)
{
string error = ex.Message;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "ShowError('" + error + "')", true);
LogUtil.Debug("Page Campaign Update Exception Occured " + ex.Message);
}
}
string SQL = "UPDATE SURVEY_CAMPAIGN SET OUTGOING_VDN = #OUTGOING_VDN, LANG_CD = #LANG_CD, ANNOUNCEMENT_FOLDER = #ANNOUNCEMENT_FOLDER, EXCEEDED_AUDIO = #EXCEEDED_AUDIO, VALID_ENTRY_AUDIO = #VALID_ENTRY_AUDIO WHERE CAMPAIGN_ID = #CAMPAIGN_ID" ;
//Now put this parameters before int result = cmd.ExecuteNonQuery();
cmd.Parameters.AddWithValue("#OUTGOING_VDN", txtOutgoing.Text);
cmd.Parameters.AddWithValue("#LANG_CD", txtlang.Text);
cmd.Parameters.AddWithValue("#ANNOUNCEMENT_FOLDER",
txtAnnouc.Text);
cmd.Parameters.AddWithValue("#EXCEEDED_AUDIO", txtExceed.Text);
cmd.Parameters.AddWithValue("#VALID_ENTRY_AUDIO", txtExit.Text);
cmd.Parameters.AddWithValue("#CAMPAIGN_ID", CampignsDRP.SelectedValue);

How to insert a different selectedindex combobox value into database?

In my project i have a countries combobox (PaysCmBx0) that is filled from countries database table [Pays] column [pays], what i want to do is when i select a country in the combobox it insert the Alpha country code token from the Alpha country code column [Alpha2] in another table (exemple : United-states = US).
so when i select a country from the combobox it does nothing it's intserting the same value.
My table look like this:
[Aplha2] [Pays]
GB United Kingdom
IM Isle of Man
TZ United Republic Of Tanzania
US United States
BF Burkina Faso
UY Uruguay
UZ Uzbekistan
here's my code :
void Fillcombo()
{
string Query = "SELECT * FROM Pays";
SqlCommand cmd = new SqlCommand(Query, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd.ExecuteReader();
while (myRead.Read())
{
string sName = myRead["Pays"].ToString();
PaysCmBx0.Items.Add(sName);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
private void AddBtn_Click(object sender, EventArgs e)
{
try
{
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + TypeAdrCmBx.Text+ "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + this.PaysCmBx0.Text + "')";
SqlCommand cmd = new SqlCommand(Query, con);
con.Open();
SqlDataReader Read;
try
{
Read = cmd.ExecuteReader();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void PaysCmBx0_SelectedIndexChanged(object sender, EventArgs e)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
string Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
thanks every one i fund a solutions for this :
i create a function that gets the country code corresponding to what's selected in the combobox:
private string get_code_pays(string nom_pays)
{
string Query1 = "SELECT * FROM Pays WHERE Pays='" + PaysCmBx0.Text + "'";
string Code_Pays="";
SqlCommand cmd1 = new SqlCommand(Query1, con);
SqlDataReader myRead;
try
{
con.Open();
myRead = cmd1.ExecuteReader();
while (myRead.Read())
{
Code_Pays = myRead["Alpha2"].ToString();
PaysCmBx0.SelectedIndex.Equals(Code_Pays);
}
con.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
return Code_Pays;
}
and then call my funtion with the parameter in my insert:
string Query = "INSERT INTO [dbo].[Adresses] ([idParent],[Type] ,[Adresse0],[Adresse1],[Adresse2],[CPT],[Ville],[Pays]) VALUES ('"+Contact.idContact+"','" + A + "','" + this.AdrTxtBx0.Text + "','" + this.AdrTxtBx1.Text + "','" + this.AdrTxtBx2.Text + "','" + this.CptTxtBx.Text + "','" + this.VilleTxtBx.Text + "','" + get_code_pays( this.PaysCmBx0.Text) + "')";

How to update datagridview based on its Id?

I'm developing software in which I have a datagridview in wpf in which I have successfully done with inserting the values through fields in datagridview when clicked on insert button. But when I'm clicking on update I'm getting following exception .Find the screenshot of error below:
https://imgur.com/a/CV3n77K
The code that have been tried by myself is below :
public partial class Machine : Window
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\ATS\ATS Data Management System\ATS Data Management System\ATSDataManagementsystemDB.mdf;Integrated Security=True;User Instance=True");
public Machine()
{
InitializeComponent();
MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth;
BindMyData();
}
public void BindMyData()
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("SELECT * FROM tblmachines", conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(comm);
da.Fill(ds);
gridmachine.ItemsSource = ds.Tables[0].DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
}
}
private void btninsert_Click(object sender, RoutedEventArgs e)
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("INSERT INTO tblmachines VALUES('" + txtid.Text + "','" + txtsalesdate.Text + "','" + txtname.Text + "','" + txtpartname.Text + "','" + txtprice.Text + "','" + txtquantity.Text + "','" + txttotalamount.Text + "','" + paidpending.Text + "','" + txtpaidamount.Text + "','" + txtpendingamount.Text + "','" + txtcreditamountpaid.Text + "','" + txtpaiddate.Text + "','" + txtpaymentmode.Text + "')", conn);
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
BindMyData();
}
}
private void btnupdate_Click(object sender, RoutedEventArgs e)
{
try
{
conn.Open();
SqlCommand comm = new SqlCommand("UPDATE tblmachines SET SalesDate='" +txtsalesdate.Text+ "',Name='" +txtname.Text+"',Part Name='"+txtpartname.Text+"',Price="+txtprice.Text+",Quantity="+txtquantity.Text+",Total Amount="+txttotalamount.Text+",PaymentStatus='"+paidpending.Text+"',Paid Amount="+txtpaidamount.Text+",Pending Amount="+txtpendingamount.Text+",Credit Amount Paid="+txtcreditamountpaid.Text+",Paid Date='"+txtpaiddate.Text+"',Payment Mode='"+txtpaymentmode.Text+"'WHERE Id=" + txtid.Text + "", conn);
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
conn.Close();
BindMyData();
}
}
}
}
I want the data to get updated and show up in data grid view but its not happening.
check your Part Name,Paid Amount, Pending Amount and Credit Amount Paid column, i think the error is the column name
SqlCommand comm = new SqlCommand("UPDATE tblmachines SET SalesDate='" +txtsalesdate.Text+ "',Name='" +txtname.Text+"',Part Name='"+txtpartname.Text+"',Price="+txtprice.Text+",Quantity="+txtquantity.Text+",Total Amount="+txttotalamount.Text+",PaymentStatus='"+paidpending.Text+"',Paid Amount="+txtpaidamount.Text+",Pending Amount="+txtpendingamount.Text+",Credit Amount Paid="+txtcreditamountpaid.Text+",Paid Date='"+txtpaiddate.Text+"',Payment Mode='"+txtpaymentmode.Text+"'WHERE Id=" + txtid.Text + "", conn);
You should also add space in the WHERE
Show your table structure

I want to get an alert if email already exits in my database in c# with help of execute scalar method

protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("select EmailID from Reg where EmailID='" + txtEmail.Text + "'", con);
con.Open();
Int32 count = (Int32)cmd.ExecuteScalar();
if (count==0)
{
Response.Write("email already Exists");
Response.End();
}
else
{
cmd.CommandText = "insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + "','" + txtMobile.Text + "','" + RdoGender.SelectedItem.Value + "','" + db + "')";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
}
}
Please help me with this. And also for errors like use new keyword to create an object instance that I’m getting.
Put a unique index on EmailID, then perform just the insert and catch for SqlExceptions and check if exception.Number == 2601
Note: Use using statements to ensure that IDisposables will be disposed and use parameterized commands!
protected void btnSubmit_Click(object sender, EventArgs e)
{
string db = DropDownList1.SelectedItem.Value + "-" + DropDownList2.SelectedItem.Value + "-" + DropDownList3.SelectedItem.Value;
using(SqlConnection con = new SqlConnection("data source=BAN095\\SQLEXPRESS; database=Reg-DB; integrated security=SSPI"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("insert into Reg(FirstName,LastName,EmailID,PhoneNum,Gender,DOB)values(#FirstName,#LastName,#Email,#Mobile,#Gender,#Db)", con))
{
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
//Do the same with other parameters
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
if (ex.Number == 2601) // If instead of unique index, you have a unique constraint/primary key, check for ex.number==2627
{
// Duplicate key! Do whatever you want
}
}
}
}
}

Use right syntax error in Mysql

Am not able to fix the error below:
`"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'When,Then) values( '79','WBT-CoE','gyj','yi','yi')' at line 1"` error.
Here's the code:
protected void Button3_Click(object sender, EventArgs e){
string MyconnectionString = "server=localhost;database=requirement_doc;Uid=t;Pwd=123;";
MySqlConnection conn = new MySqlConnection(MyconnectionString);
MySqlCommand cmd;
DataTable dt1 = new DataTable();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT Req_ID, Actor FROM UseCase where Req_ID='" + txtReqID.Text + "' AND Actor='" + DropDownList1.Text + "'";
MySqlDataAdapter da1 = new MySqlDataAdapter();
da1.SelectCommand = cmd;
da1.Fill(dt1);
if (dt1.Rows.Count > 0)
{
Label1.Text = "Data already exist";
}
else
{
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,When,Then) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
}
try
{
cmd.ExecuteNonQuery();
Label1.Text = " Successfully saved";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
Surround When and then with `` because they are reserved names.
string sql = "INSERT INTO UseCase (Req_ID,Actor,Given,`When`,`Then`) values( '" + txtReqID.Text + "','" + DropDownList1.Text + "','" + giventxt.Text + "','" + whentbl.Text + "','" + thentbl.Text + "')";
When and Then are reserved names in MySQL. So if you use those as column names, you get that error.

Categories