Save,Update and delete page. Saving duplicated data - c#

I was watching https://www.youtube.com/watch?v=SJ-RyDl5E7U It basically teaches me how to create my update and delete button after following the video my program works just like his!
But there is no "checking" statement for my btnSave, allowing the user to enter duplicated data in the data base if they click more than once shown here
So I was wondering if there is a "checking statement" I can use, like if the IndexNumber (first column) exist there will be a message box showing out saying something like "ID is already exists"
This is my current code for the btnSave
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + Application.StartupPath + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
cmd.ExecuteNonQuery();
con.Close();

As you are using ado.net something like this;
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=" + "Application.StartupPath" + "\\GlennTeoDB.mdf; Integrated Security=True;Connect Timeout=30");
con.Open();
//get a count records with your index number
SqlCommand validate = new SqlCommand(string.Format("SELECT count(IndexNumber) FROM GlennTeoStudents WHERE IndexNumber = {0}", numIN.Value), con);
int count = (Int32)validate.ExecuteScalar();
if (count == 0)
{
//insert your unqiue index number into a new row
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text + "','" + numGPA.Value + "')", con);
cmd.ExecuteNonQuery();
}
else
{
//don't insert it, do something else like return an error
}
con.Close();

You should add an existence check:
SqlCommand cmd = new SqlCommand(#"INSERT INTO GlennTeoStudents (IndexNumber,Name,Age,HandphoneNumber,GPA) VALUES ('" + numIN.Value +
"','" + txtName.Text + "','" + txtAge.Text + "','" + txtHP.Text +
"','" + numGPA.Value + "') WHERE NOT EXISTS ( SELECT * FROM
GlennTeoStudents WHERE IndexNumber = '" + numIN.Value + "')", con);

Related

Error in insert query in visual studio

I'm new in this field. Trying to insert the values from textbox to my database table, but I get an error at
adapter.InsertCommand.ExecuteNonQuery();
Can anyone help me solve this?
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql,con);
adapter.InsertCommand = new SqlCommand(sql,con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Since your table is called table and that is a SQL reserved word, you have two choices:
Change your table name. This is the only option you should be considering but for completeness;
Quote the name of the table:
insert into [table] values....
You do not list your column name on insert. This means you are also attempting to insert your identity column as well. Always list your column names
insert into NewName (firstname, lastname, username, email, password, contact)
values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')
Yes I've done it .I was using "user" in table column which is not allowed .After changing the column name everything works.
This is the code
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql, con);
adapter.InsertCommand = new SqlCommand(sql, con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();

incorrect syntax when I select, the error near the first name

I have a little problem with an error. but I have this command in another form and do not give me the error.
This is the code:
string select = "select CONCAT(nume,' ',prenume) from echipa where email=#EMAIL";
cmd.Connection = con;
if (bunifuCheckbox1.Checked == true)
{
con.Open();
cmd.CommandText = "Insert into clienti_fizici(nume,prenume,email,telefon,adresa,data_nasterii,data_ora,CNP,sex,judetprovenienta,temperamentclient,provenientaclient,descriere,numeagent)values('"
+ bunifuMaterialTextbox1.Text + "','" + bunifuMaterialTextbox2.Text + "','" + bunifuMaterialTextbox4.Text + "','" + bunifuMaterialTextbox8.Text + "','" + bunifuMaterialTextbox3.Text + "','" + DateTime.Now.ToString("yyyy-MM-dd HH: mm:ss") + "','" + bunifuDatepicker1.Value.Date + "','" + bunifuMaterialTextbox11.Text + "','" + gender + "','" + bunifuMaterialTextbox12.Text + "','" + bunifuDropdown1.selectedValue + "','" + bunifuDropdown2.selectedValue
+ "','" + richTextBox1.Text + "','" + select + "')";
cmd.Parameters.AddWithValue("#EMAIL", loginform.Email);
MessageBox.Show("Datele au fost introduse in baza de date !");
cmd.ExecuteNonQuery();
con.Close();
}
and the error would be from that select.
First, you must never concatenate strings with user input to create SQL Statement. Instead, always parameterize your SQL statements. Otherwise you are risking SQL injection attacks.
Second, you can't use select inside the values clause.
What you can do add parameters or hard coded values to your select statement.
Third, SqlConnection and SqlCommand both implement the IDisposable interface and should be used as a local variable inside a using block.
A better code would look like this:
if (bunifuCheckbox1.Checked == true)
{
string sql = "Insert into clienti_fizici(nume, prenume, email, telefon, adresa, data_nasterii, data_ora, CNP, sex, judetprovenienta, temperamentclient, provenientaclient, descriere, numeagent) " +
"SELECT #nume, #prenume, #email, #telefon, #adresa, #data_nasterii, #data_ora, #CNP, #sex, #judetprovenienta, #temperamentclient, #provenientaclient, #descriere, CONCAT(nume,' ',prenume) " +
"FROM echipa where email = #EMAIL";
// Note: SqlConnection should be opened for the shortest time possible - the using statement close and dispose it when done.
using(var con = new SqlConnection(connectionString))
{
// SqlCommand is also an IDisposable and should be disposed when done.
using(var cmd = new SqlCommand(sql, con)
{
cmd.Parameters.Add("#nume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox1.Text;
cmd.Parameters.Add("#prenume", SqlDbType.NVarChar).Value = bunifuMaterialTextbox2.Text;
//... Add the rest of the parameters here...
cmd.Parameters.Add("#EMAIL", SqlDbType.NVarChar).Value = loginform.Email;
// Why is this here? MessageBox.Show("Datele au fost introduse in baza de date !");
con.Open();
cmd.ExecuteNonQuery();
}
}
}

Error connecting to Local Data Base i need to pass info from CSV file into the localdb table c#

I have an error message when I'm trying to run the code and pass the information from a CSV file into the Local DataBase
the error message is :
System.ArgumentException: 'Format of the initialization string does not conform to specification starting at index 0.'
and I'm not sure what is the problem in here:
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','"
+ rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6]
+ "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
image screenshot of visual:
image screenshot
when I run the app the LOCALDBSHILOV have a red X on him is it noraml
red X image
the code is:
private void button1_Click(object sender, EventArgs e)
{
string strFilePat = #"C:\Users\oz\Desktop\sql\backup\tabel3.csv";
ConvertCSVtoDataTable(strFilePat, strFilePat);
}
public static DataTable ConvertCSVtoDataTable(string strFilePath, string conLocoldbString1)
{
MessageBox.Show("start", "SHILOV", MessageBoxButtons.OK);
DataTable dt = new DataTable();
using (StreamReader sr = new StreamReader(strFilePath))
{
string[] headers = sr.ReadLine().Split(',');
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = sr.ReadLine().Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
try
{
SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into PhoneTable(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('"
+ rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','"
+ rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
dt.Rows.Add(dr);
}
}
MessageBox.Show("finish", "SHILOVI2R", MessageBoxButtons.OK);
return dt;
}
Your connection string is not correct. Use one like this:
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
when i run it its stuck in conn.Open(); and does nothing and there is no error but the application continues to run only that it does not pass to the next line of code and there is no update of the table
try
{
//SqlConnection conn = new SqlConnection(#"C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOV\SHILOV\LOCALDBSHILOV.MDF");
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;
AttachDbFilename=C:\USERS\OZ\DOCUMENTS\VISUAL STUDIO 2017\PROJECTS\SHILOVI2R\SHILOVI2R\PHONENUM.MDF;
Integrated Security=True;
Connect Timeout=30;
User Instance=True");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into phonebook(שם,עיר,כתובת,מספר טלפון,אזור,מספר זיהוי,מחוז,נפה,דת)VALUES('" + rows[0] + "','" + rows[1] + "','" + rows[2] + "','" + rows[3] + "','" + rows[4] + "','" + rows[5] + "','" + rows[6] + "','" + rows[7] + "','" + rows[8] + "') ", conn);
cmd.ExecuteNonQuery();
MessageBox.Show("middle2", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch (Exception e)
{
MessageBox.Show("dont_work", "SHILOVI2R", MessageBoxButtons.OK);
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}

auto suggest data from grid to textboxes..in winforms

Auto suggest data from grid to textboxes, in winforms.
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";
int n = cmd.ExecuteNonQuery();

Insert item to database

I have a problem with insert into statement..
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#Position", comboBox1.SelectedValue);
con.Open();
int n = cmd.ExecuteNonQuery();
//cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Inserted");
loaddata();
rno++;
}
else
MessageBox.Show("No Insert");
ERROR : Syntax Error INSERT INTO
Anyone can advise me? Please, Sorry for my bad English grammar.
Seem like you are missing out a parameter in your query, try using this
cmd.CommandText = "insert into Table1 (id,Position) values (#id,#Position)";
cmd.parameters.addwithvalue("#id", textBox1.Text);
cmd.parameters.addwithvalue("#Position", combobox1.selectedvalue);
new updated
-the position is the oleh db reserved words, try change to this query, put the cover to Position like below
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,[Position],Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
You have missed adding #Photo parameter in your code.
That is ok for testing purpose but you should never insert to database this way. This expose your system to a SQL Injection. You should use parametrized queries where possible. Something like
int result=0;
using (OleDbConnection myConnection = new OleDbConnection ("YourConnectionString"))
{
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) values (#ID, #Gender, #DateOfBirth, #Race, #WorkingPlace, #PassportNO, #DateOfExpire, #Position, #Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#ID", textBox5.Text);
// Specify all parameters like this
try
{
con.Open();
result = Convert.ToInt32(cmd.ExecuteNonQuery());
}
catch( OledbException ex)
{
// Log error
}
finally
{
if (con!=null) con.Close();
}
}
if(result > 0)
// Show success message
Also note that OleDb parameters are positional, means you have to
specify them in the exact order as in your query. OleDbParameter Class (MSDN)
There is no value for parameter #Photo, and if your photo field is not nullable or empty
in database structure then how you can add null value in that.So make your data field
nullable or pass value to parameter #Photo.I think it will solve your problem.
cmd = new OleDbCommand("insert into FWINFOS (ID,Name,Gender,DateOfBirth,Race,WorkingPlace,PassportNO,DateOfExpire,Position,Photo) " +
"values('" + textBox5.Text + "','" + textBox1.Text + "','" + textBox2.Text +
"','" + dateTimePicker1.Value + "','" + textBox3.Text + "','" + textBox4.Text +
"','" + textBox6.Text + "','" + dateTimePicker2.Value + "',#Position,#Photo)", con);
conv_photo();
cmd.Parameters.AddWithValue("#Position", comboBox1.SelectedValue);
cmd.Parameters.AddWithValue("#Photo", assignvalue);
con.Open();
int n = cmd.ExecuteNonQuery();
//cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Inserted");
loaddata();
rno++;
}
else
MessageBox.Show("No Insert");

Categories