insert,update in single button clickin winforms - c#

I am not getting, how to do insert and update of the data in C# WinForms on single button click.
private void save_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=Sai;database=kaur; user id=sa;password=azxc;";
cn.Open();
string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
string clas = null;
clas = comboBox1.Text;
string section = null;
section = comboBox2.Text;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");
SqlDataAdapter da = new SqlDataAdapter("select * from studetail ", cn);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;

You can add a deletion before the insertion:
private void save_Click(object sender, EventArgs e)
{
DeletePerson(id); // add this
SqlConnection cn = new SqlConnection();
...
}
public void DeletePerson(int id)
{
using(SqlConnection connection = new SqlConnection(credentials))
{
connection.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = "delete from studetail where someUniqeIdColumn = " + id;
cmd.ExecuteNonQuery();
}
}
Using responsible to dispose the connection.
Consider using Entity Framework or LINQ to SQL.
You are exposed to SQL injection.

First off the SQL query isn't quite right. It should look something like the following:
INSERT INTO studetail (columnName1, columnName2, ...columnNameN)
VALUES (value1, value2, ...valueN);
Where the column names are the columns where you want data to be inserted, and the values are the data you want inserted into said columns.
You should also be disposing the connection by wrapping the connection within a using statement.
using(var con = new SqlConnection(connectionString))
{
con.Open();
//rest of code that needs a connection here
}
Additionally, you need to be wary of SQL injection. I highly suggest reading this example from the MSDN website. It will give you an example of using an SQL Update and avoiding SQL injection with use of SqlCommand.Paramaters property.
You should also have a Primary Key in your database tables, if you don't already, so you can uniquely identify each record in a table.
To do an update and a save on the same button, you will need to check if a row already exists for the data that is being edited. This when a Primary comes in handy. You will want to check your database to see if a record already exists
SELECT 1 FROM studetail WHERE <Condition>
The WHERE condition will be the way you uniquely identify (a Primary Key) a row in your table. If the rows in the table are uniquely identified, the above SQL statement will return 1 if a value exists, which means you can UPDATE or 0 if no record exists, so you can INSERT

Related

Updating values from excel to database

I am facing difficulty on writing logic to insert data into the database from some array. My requirement is if the data already exist in SQL insert query should not be executed. only when that data does not exist in database the insert query has to be executed where data will be inserted. I have tried a lot please find my code below.
public void writetodatabase()
{
//SQL connection String
SqlConnection cnn = new SqlConnection(#"Data Source=ABDUL-TPS\TPSSQLSERVER;Initial Catalog=Automation;Integrated Security=True");
// Open Connection to sql
cnn.Open();
// Declare a DataTable which will contain the result from SQL query
DataTable DT = new DataTable();
for(int m =0; m < globalZoho_Names.Length; m++)
{
string query1 = "select * from tbl_Zoho_data where col_Zoho_SKU like '" + globalZoho_SKU[m] + "'";
SqlCommand cmd1 = new SqlCommand(query1, cnn);
SqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
{
string zohosku = reader1["col_Zoho_SKU"].ToString();
if (zohosku == null)
{
string ItemName = reader1["col_item_name"].ToString();
string insert1 = "insert into tbl_zOHO_DATA values ('" + globalZoho_SKU[m] + "','" + globalZoho_Names[m] + "')";
SqlDataAdapter DA_insert = new SqlDataAdapter(insert1, cnn);
DA_insert.Fill(DT);
Label1.Text = "Khulja Sim Sim";
}
}
reader1.Close();
}
}
I want the code to check for the values first into the database and then insert only those values which do not exist in the database.

DataReader Associated with this Command Error

OleDbConnection baglanti =
new OleDbConnection("connect");
OleDbCommand komut = new OleDbCommand();
OleDbDataReader dr;
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text=="" || textBox2.Text=="" || textBox3.Text=="" || maskedTextBox1.Text=="" || dateTimePicker1.Text=="" || maskedTextBox2.Text=="" || textBox6.Text=="")
{
MessageBox.Show("Lütfen Boş alanları doldurunuz !!");
}
else
{
baglanti.Open();
komut.Connection = baglanti;
komut.CommandText=("Select TcKimlik from Hasta");
dr = komut.ExecuteReader();
while(dr.Read())
{
if(dr["TcKimlik"].ToString()==textBox1.Text.ToString())
{
MessageBox.Show("aaaaa");
}
else
{
komut.CommandText = ("insert into Hasta (TcKimlik,h_adı,h_soyadı,tel_no,ran_tar,ran_saati,sikayet_nedeni) values('" + textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "','" + textBox3.Text.ToString() + "','" + maskedTextBox1.Text.ToString() + "','" + dateTimePicker1.Text.ToString() + "','" + maskedTextBox2.Text.ToString() + "','" + textBox6.Text.ToString() + "')");
komut.ExecuteNonQuery();
MessageBox.Show("Kayıt Başarı İle Tamamlandı", "Kayıt Başarılı", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
baglanti.Close();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
maskedTextBox1.Clear();
maskedTextBox2.Clear();
textBox6.Clear();
}
}
I have tried a lot of ways but I could not go to a solution. If I check the data or make dr.Close() before registering the data, I can save the data, but then I get an error because I close the data reader prematurely.
I want to check the data in the database but I get an error like below.
Associated with this Command, there is already an explicit DataReader that should be closed first.
Issue with you code is you are making use of Command object for performing reading and inserting record at one time.
you require to perform operation one by one , you cannot do both in one time. so you code should be like this
using (OleDbconnection connection = new OleDbconnection (ConnectionString))
{
connection.Open();
OleDbCommand select = new OleDbCommand("..selecte query",connection);
OleDbDataReader reader = select.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//read data you want
//you might not need another connection , but i added to seperate it , you can reuse connection you created and perfrom update
using(OleDbconnection connection1 = new OleDbconnection (ConnectionString))
{
OleDbCommand insert= new OleDbCommand ("..insertquery", connection1);
insert.ExecuteNonQuery();
}
}
}
reader.Close();
}
}
you can use command object to perfrom multiple task but it should be one by one , example
//first complete reading and close reader
//second do insert operation complete it
//third do update operation
One more suggstion make use of Parameter as your insert query is open for sql injection attack, if you go with parameterise query can resolve that issue

How do I code for an insert with a foreign key?

I have a Q and A page on my website where it displays a question pulled from a question table in my database. Below the question are two text boxes - one for the person's name and another for their answer, which is to be inserted into the answer table. The answer table has a FK questionID on it and that is where I am stuck. How do I write the script for the answer table in my code so it uses that questionID from the question table?
This is what I have so far:
protected void btnSubmitAnswer_onClick(object sender, EventArgs e)
{
String connectionString = "Server=root;Database=test;User=name;Password=test;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Answers (QuestionID, Answer_Name, Answer)" +
"VALUES (%%, '" + txtName.Text + "', '" + txtAnswer.Text + "')");
cmd.Connection = conn;
conn.Open();
cmd.ExecuteScalar().ToString();
}
}
The %% is what I need fixed. I was thinking about using a String variable but then I still don't know what I should use for that data type.
When you fetch the Question Id, you should store it into a variable in order to reuse it when inserting the command.
Like:
SELECT Id, /*And anything else you need*/ FROM QUESTION
And store it in a variable like Int32 QuestionId;
Also, for the sake of completeness, never concatenate SQL Strings, it makes your code vulnerable, instead use sql parameters.
protected void btnSubmitAnswer_onClick(object sender, EventArgs e)
{
String connectionString = "Server=root;Database=test;User=name;Password=test;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand(
"INSERT INTO Answers (QuestionID, Answer_Name, Answer)" +
"VALUES (#prmQuestionId, #prmAnswerName, #prmAnswer)");
cmd.Parameters.Add(new SqlParameter("#prmQuestionId", QuestionId/*HERE INSERT THE ID VALUE OF THE FETCHED QUESTION*/));
cmd.Parameters.Add(new SqlParameter("#prmAnswerName", txtName.Text));
cmd.Parameters.Add(new SqlParameter("#prmAnswer", txtAnswer.Text));
cmd.Connection = conn;
conn.Open();
cmd.ExecuteScalar().ToString();
}
}
You will need to either store the id of the question in a hidden field and reference that else use an inner select within your insert statement to retrive the ID of the question.
The hidden field would be set up as below:
<input type="hidden" id="questionId" value="questionId" />
and then:
SqlCommand cmd = new SqlCommand("INSERT INTO Answers (QuestionID, Answer_Name, Answer)" +
"VALUES (questionId.Value, '" + txtName.Text + "', '" + txtAnswer.Text + "')");
The inner select would be in the form of
insert into table ((select id from questiontable where question = [the question text]), 'name', 'answer')
You need to do a get Query (Select Statement) to from the question table to retrieve the Question Id and then do an insert.
Also, use parameter strings, don't concatenate, your code can be injected with malicious behavior possibly deleting your database tables!
You need to create an int QuestionID variable to hold the current QuestionID. Just change it when the user changes questions. You could store this in Session.
Side note: I recommend parameterizing txtName.Text and txtAnswer.Text to avoid SQL injection.
At the time you are getting the question for the database get the Id as well and store it somewhere.
On a side note your code is open to SQL Injection. Use parameters instead to store the values from your textboxes like this:
SqlParameter param = new SqlParameter("#Name", SqlDbType.VarChar);
param.Value = txtName.Text;
cmd.Parameters.Add(param);
So your control is Gridview, this may be the case.. Try it.
protected void myRowCommand(object sender, GridViewCommandEventArgs e)
{
String connectionString = "Server=root;Database=test;User=name;Password=test;";
GridViewRow row = this.GridView1.SelectedRow;
int EntryID = row.RowIndex;
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Answers (QuestionID, Answer_Name, Answer)" +
"VALUES (EntryID, '" + txtName.Text + "', '" + txtAnswer.Text + "')");
cmd.Connection = conn;
conn.Open();
cmd.ExecuteScalar().ToString();
}
}
}

How to avoid insert duplicate record in SQL Server using windows form in C# [duplicate]

This question already has an answer here:
Code for checking the same data present in table column
(1 answer)
Closed 8 years ago.
I want to ask while inserting the data in customer datatable, the customer id, contact no email should be not same. It should show a message box the the particular record is already present in the following code:
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 = "";
}
}
}
Please edit the code, so I could know.......
Before you run the query to insert the data in the customer datatable, Run another query to see if this record already exists in the table. As you have not mentioned the mata-data of this table, so i am writing an example query assuming some attributes names myself.
Try running this query before the insert query, and if this query returns some values in result set, that means this data already exists in the table, so tell user accordingly, otherwise if it returns NULL, then you can insert the data in the table as this doesn't already exists.
"select * from Customer_Info where cust_id = '" +Custid.Text.ToString()+"' OR contact = '" +contact.Text.ToString()+ "' OR email = '"+email.Text.ToString()+"'" ;
You can use UNIQUE constraints to make sure that no duplicate values are entered in specific columns that do not participate in a primary key.
As you have table definition already in your database you can add a unique constraint as:
ALTER TABLE dbo.Customer_Info
ADD CONSTRAINT uccustomerinfo UNIQUE NONCLUSTERED (customer_id,contact_no, email);
Check Demo here
Solution 1: if you want to check for only Duplicate CustomerID(one column) actually you don't need to write any logic for this , you just need to declare your Custid column as IDENTITY to solve the issue.
IDENTITY columns need not be inserted from INSERT INTO statement they will be inserted by default.
Example: if you want to start the Custid with number 500 and increment for each insertion.
Try This:
CREATE TABLE Customer
(
CustID int IDENTITY(500,1) PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)
You can skip the values for the IDENTITY while writing the INSERT INTO statement.
Try This:
INSERT INTO Customer(LastName,FirstName,Address,City)
VALUES('xyz','abc','address','city');
Solution 2 : You can write small function to detect wether the customerID is already there in database or not.
Try This:
bool CheckDuplicateCustomer(int custid,string contact,string email)
{
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("select count(*) from Customer_Info where custid = #custid and contactno=#contactno and email=#email", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#custid",custid);
cmd.Parameters.AddWithValue("#contactno",contact);
cmd.Parameters.AddWithValue("#email",email);
int CustomerCount = Convert.ToInt32(cmd.ExecuteScalar());
}
con.Close();
if(CustomerCount > 0)
return true;
return false;
}
You can call the above function to identify the duplicate customer
call the above function as below from your code:
private void button1_Click(object sender, EventArgs e)
{
int custid=Convert.ToInt32(CustID.Text);
int contact=Contact.Text;
int email=Email.Text;
if(CheckDuplicateCustomer(custid,contact,email))
{
MessageBox.Show("Customer Already Exists with ID "+CustId.Text);
}
else
{
//your code to insert the customer into table
}
}

DML query execution from datagridview to SSCE

What I am trying to do:
Execute DML statements into database (SSCE) using Datagridview and command buttons.
The Problem:
I am getting exact same error as this post: SQL [Error]: There was an error parsing the query. [ Token line number = 1,Token line offset = 44,Token in error = - ]
Based on those answers and others available on the web, I have validated the query string, yet not able to solve it. There's also one other aspect I have doubts.
private void button2_Click(object sender, EventArgs e)
{
using (SqlCeConnection CONN = new SqlCeConnection("Data
Source=LocalDBSSCompactEdition.sdf;"))
{
SqlCeCommand comm = new SqlCeCommand();
comm.Connection = CONN;
CONN.Open();
int i = dataGridView2.Rows.Count-1;
String queryString = #"INSERT INTO tblEmployee VALUES ("
+ dataGridView2.Rows[i].Cells["E_ID"].Value + ", "
+ dataGridView2.Rows[i].Cells["FirstName"].Value + ", "
+ dataGridView2.Rows[i].Cells["LastName"].Value + ", "
+ dataGridView2.Rows[i].Cells["DeptID"].Value + ");";
comm.CommandText = queryString;
comm.ExecuteNonQuery();
}
}
1) E_ID column is IDENTITY(auto-increment). However I got an error, saying that I must include all the columns in DataGridview to match to the database table. Could this be the issue that I am getting or could it be my syntax?
2) I want to insert new rows/updates/deleted rows from Datagridview to the database table using a button click event. Is this the efficient way of doing so?
Some insights to the right direction is appreciated.
I managed to get it solved. I don't believe in answering my own-question. Just added the answer hoping for someone else's reference in the future.
1) i variable was referring to an empty row in the datagridview...Hence the values to be inserted were null and these columns are specified NOT NULL...
2) First rule was to follow the usual INSERT statement when ID column is auto-increment. So I specify the columns that I want to insert data for.
3) The data that I was entering were not quoted to treat as String. Fixed.
private void button2_Click(object sender, EventArgs e)
{
using (SqlCeConnection CONN = new SqlCeConnection("Data Source=LocalDBSSCompactEdition.sdf;"))
{
CONN.Open();
SqlCeCommand comm = CONN.CreateCommand();
int i = dataGridView2.Rows.Count-1;
String queryString = #"INSERT INTO tblEmployee (FirstName, LastName, DeptID) VALUES ('"
+ dataGridView2.Rows[5].Cells["FirstName"].Value + "','"
+ dataGridView2.Rows[5].Cells["LastName"].Value + "',"
+ dataGridView2.Rows[5].Cells["DeptID"].Value + ");";
comm.CommandText = queryString;
comm.ExecuteNonQuery();
CONN.Close();
}
}

Categories