Code for checking the same data present in table column - c#

I am facing a problem, that in my customer info table the customer id, contact no & E-mail address should not be same for two or more customers.I also have set custmomerid as the primary key. Plz let me know how to get the warning message box for that, there is the same data already present while adding to database......
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=HP\SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("insert into Customer_Info values('" + Custid.Text.ToString() + "','" + fname.Text.ToString() + "','" + lname.Text.ToString() + "','" + landmark.Text.ToString() + "','" + address.Text.ToString() + "','" + contact.Text.ToString() + "','" + email.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + deposite.Text.ToString() + "')", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("You Have Successfully Inserted");
this.customer_InfoTableAdapter1.Fill(this.cD_GalleryDataSet7Cust_add.Customer_Info);
Custid.Text = "";
fname.Text = "";
lname.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
landmark.Text = "";
deposite.Text = "";
}
}
}

If i understood correctly, you need to prevent duplicate entries on customerID, contactNo and Email. The most straight forward answer is put the primary key on all three columns. This would throw a DuplicateRecord Exception when adding a record that already exists and you should properly catch it.
Another way is to check in the query (with execute scalar):
"IF EXISTS(select 1 from customer_info where customerID = ... and
contactNo = ... and email = ...)
BEGIN select -1 RETURN END
insert into Customer_Info values('.......... (your query)"
Hope that helps

Related

More columns in the INSERT statement than values in the VALUES clause

I also don't know how to add the values of comboboxes and gender radio buttons to the database. This is basically for a registration form to insert its values into a database. I also need to display the values of the database on the form from selecting the combobox value.
private void Btn_register_Click(object sender, EventArgs e)
{
//int regNo = Cbox_regNo.Text; //i need to get the values from the combobox
string fName = Tbox_fName.Text;
string lName = Tbox_lName.Text;
string dob = dtp_dob.Text;
string address = Tbox_address.Text;
string email = Tbox_email.Text;
string mPhone = Tbox_mPhone.Text;
string hPhone = Tbox_hPhone.Text;
string pName = Tbox_parentName.Text;
string nic = Tbox_nic.Text;
string cNumber = Tbox_cntctNumber.Text;
string connString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\abhin\\Desktop\\Final Project\\Visual Studio\\Final Project\\Final Project\\Student.mdf\";Integrated Security=True";
string Query = "insert into Registrations (regNo, firstName, lastName, dateOfBirth, gender, address, email, mobilePhone, homePhone, parentName, nic, contactNo) values('"+this.Cbox_regNo.Text+"','" + this.Tbox_fName.Text + "','" + this.Tbox_lName.Text + "','" + this.dtp_dob.Value + "','" + this.Tbox_address.Text + "','" + this.Tbox_email.Text + "','" + this.Tbox_mPhone.Text + "','" + this.Tbox_hPhone.Text + "','" + this.Tbox_parentName.Text + "','" + this.Tbox_nic.Text + "','" + this.Tbox_cntctNumber.Text + "') ;";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmdDB = new SqlCommand(Query, conn);
SqlDataReader myReader;
try
{
conn.Open();
myReader=cmdDB.ExecuteReader();
MessageBox.Show("Record Added Succesfully", "Register Student", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
while (myReader.Read())
{
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
On declaring your “Query” variable you are using 12 column (regNo, firstName…) and 11 value. You need one more value

I want the corresponding ID of last record in MS Access to appear inside a Message Box [duplicate]

This question already has answers here:
how to get the last record number after inserting record to database in access
(6 answers)
Closed 1 year ago.
Am working with Access as Database in C# (Visual Studio 15). I want to save form entries (add record) into the Access Database and would want the corresponding ID of the record to show in MsgBox upon a successful saving. I have tried the following:
private void Form21_Load(object sender, EventArgs e)
{
try
{
connection.Open();
checkConnection.Text = "Server Connection, Successful";
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error, Server not connected " + ex);
}
}
private void Button6_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into Students_File ([YourNames],[Nationality],[StateOfOrigin],[PlaceOfBirth],[DoB],[HomeAddress],[LastSchools1],[LastClass1],[LastSchools2],[LastClass2],[LastSchools3],[LastClass3],[AdmClass],[CurrentClass],[Guidian],[GuardianContact],[UserName],[PassWord],[Gender],[RegistrationDate]) values('" + YourNames.Text + "','" + Nationality.Text + "','" + StateOfOrigin.Text + "','" + PlaceOfBirth.Text + "','" + DoB.Text + "','" + HomeAddress.Text + "','" + LastSchools1.Text + "','" + LastClass1.Text + "','" + LastSchools2.Text + "','" + LastClass2.Text + "','" + LastSchools3.Text + "','" + LastClass3.Text + "','" + AdmClass.Text + "','" + CurrentClass.Text + "','" + Guidian.Text + "','" + GuardianContact.Text + "','" + UserName.Text + "','" + PassWord.Text + "','" + Gender.Text + "','" + RegistrationDate.Text + "')";
command.ExecuteNonQuery();
//MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
command.CommandText = "Select * from Students_File where UserName='" + UserName.Text + "' and PassWord='" + PassWord.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Congrats! Your registration, is successful. You may now click close button, then proceed to login");
this.Close();
}
else if (count > 1)
{
MessageBox.Show("Sorry, the chosen username or password is currently existing or picked by another user. Consequently, your registration was not successful. Do please, decide another but a unique one. Thank you");
}
connection.Close();
}
You can do it this way:
using (OleDbCommand Command = new OleDbCommand("", conn))
{
Command.CommandText = "Your big ugly mess - need to change this to parmaters!)";
Command.Connection.Open();
Command.ExecuteNonQuery();
Command.CommandText = "Select ##Identity";
var intLastID = Command.ExecuteScalar;
MsgBox("Last id into database = " + intLastID);
}
As noted, you do want to change that insert command - it too long, too difficult to maintain, and subject to mistakes in code and even sql injection.
But, for now, you can use the above approach to get/pick up the last ID insert.
In solution to my inquiry, i have the following code (From Kevin):
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("#CategoryName", OleDbType.Integer);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
Now, my challenge is how do i get the ID to appear in messagebox after a successful record creation. Please consider my earliest code in this post in connection with this.

Insert null values into SQL Server database from datagridview cell changed

I want to insert/update some values from a datagrid with cell changed event. It is not problem when values are entered correctly but if user don't enter any values it is necessary to send null to db columns. My codes like in below and you can see what I try. Maybe it is simple but I haven't wrote codes for so many years.
Thank you
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (conn.State == ConnectionState.Closed)
conn.Open();
id = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
string nikadi = (dataGridView1.Rows[e.RowIndex].Cells[1].Value == null) ? "NULL" : dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
string niuygadi = (dataGridView1.Rows[e.RowIndex].Cells[2].Value == null) ? "NULL" : dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
string niuygdty = (dataGridView1.Rows[e.RowIndex].Cells[3].Value == null) ? "NULL" : dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
string niuygytk = (dataGridView1.Rows[e.RowIndex].Cells[4].Value == null) ? "NULL" : dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
if (id == "")
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
/* cmd.CommandText = "insert into mytable (nikadi,niuygulamaadi,niuygulamadetay,niuygulamayetkisi) values ('"
+ dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString() + "','"
+ dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString() + "','"
+ dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString() + "','"
+ dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString() + "')";*/
cmd.CommandText = "insert into mytable (nikadi, niuygulamaadi, niuygulamadetay, niuygulamayetkisi) values ('"
+ nikadi + "','"
+ niuygadi + "','"
+ niuygdty + "','"
+ niuygytk + "')";
cmd.ExecuteNonQuery();
gridyetki();
MessageBox.Show("Insert operation Done");
}
else
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update mytable set nikadi='"
+ nikadi
+ "',niuygulamaadi='" + niuygadi
+ "',niuygulamadetay='" + niuygdty
+ "',niuygulamayetkisi='" + niuygytk
+ "' where ID='" + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString() + "'";
cmd.ExecuteNonQuery();
gridyetki();
}
conn.Close();
}

SQL query for update statement in (C#)

I am new to the C# programming. Facing the problem Incorrect syntax near 'First_Name'.! in the given below code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=HP\SQLEXPRESS100;Database=CD_Gallery;Integrated Security=true";
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name ='" + fname.Text + "'");
//'" + fname.Text.ToString() + "','" + lname.Text.ToString() + "','" + landmark.Text.ToString() + "','" + address.Text.ToString() + "','" + contact.Text.ToString() + "','" + email.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + deposite.Text.ToString() + "')", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
MessageBox.Show("You Have Successfully Updated");
Custid.Text = "";
fname.Text = "";
lname.Text = "";
address.Text = "";
contact.Text = "";
email.Text = "";
landmark.Text = "";
deposite.Text = "";
}
}
}
Problem : You forgot to add word SET after your table name in update statement.
Solution1 : Add the word SET after table name in Update query (Don't Recommend this)
"update Customer_Info SET First_Name ='" + fname.Text + "'"
Warning : Your query is open to sql injection attacks.please use parameterised queries to avoid them
Solution 2: Using Parameterised Queries
Replace This:
SqlCommand cmd = new SqlCommand("update Customer_Info SET First_Name
='"+fname.Text+"'");
With This:
SqlCommand cmd = new SqlCommand("update Customer_Info First_Name = #fname");
cmd.Parameters.AddWithValue("#fname" , fname.Text);
Your problem not in C#, in SQL syntax (you miss set keyword)
SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");
you are missing SET keyword:
update Customer_Info SET First_Name ='" + fname.Text + "'"
and also provide where clause otherwise it will update all the records in your table.
You are missing set keyword in query you have to place set like this
SqlCommand cmd = new SqlCommand("update Customer_Info set First_Name ='" + fname.Text + "'");

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