UpdateQuery not working with no errors - c#

I can use these UpdateQuery on WinForms, now I convert it to ASP.NET Version and use this UpdateQuery again and not work. Others SELECT, INSERT, DELETE all works well, only update, also no error have given.
protected void updateBtn_Click(object sender, EventArgs e) {
DataTable dt = new DataTable();
string sql = "UPDATE patient SET ID=?ID, NameCH=?NameCH, NameEn=?NameEn, NRIC=?IC, Tel=?Tel, Email=?Email, Sex=?Sex, Occupation=?Occupation, Married=?Married, Address=?Address, Allergies=?Allergies, LTM=?LTM, MH=?MH, Other=?Other WHERE ( 'ID'=?ID )";
MySqlConnection con = new MySqlConnection(conStr);
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.Parameters.AddWithValue("?ID", ids.Text);
cmd.Parameters.AddWithValue("?NameCH", CHName.Text);
cmd.Parameters.AddWithValue("?NameEN", ENName.Text);
cmd.Parameters.AddWithValue("?IC", NRIC.Text);
cmd.Parameters.AddWithValue("?Tel", TEL.Text);
cmd.Parameters.AddWithValue("?Email", Email.Text);
cmd.Parameters.AddWithValue("?Sex", sex.Text);
cmd.Parameters.AddWithValue("?Occupation", occupation.Text);
if (married.Checked) {
cmd.Parameters.AddWithValue("?Married", "YES");
} else {
cmd.Parameters.AddWithValue("?Married", "NO");
}
cmd.Parameters.AddWithValue("?Address", address.Text);
cmd.Parameters.AddWithValue("?Allergies", Allergies.Text);
cmd.Parameters.AddWithValue("?LTM", ltm.Text);
cmd.Parameters.AddWithValue("?MH", medicalhis.Text);
cmd.Parameters.AddWithValue("?Other", record.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/Pages/Home.aspx/Update");
}

Related

How to insert into an identity column in MS SQL

I have the following code:
SqlCommand writeCommand = new SqlCommand("INSERT INTO computers(id)VALUES()", conn.GetConnection());
writeCommand.ExecuteNonQuery();
The table computers contains an INT idientity(1,1) column named id.
When I run the code, I get a System.Data.SqlClient.SqlException: Incorrect syntax near ')'. I've tried to find a solution, but can't find one on the internet.
If the table has other columns as well, and you want to populate them with NULL or their DEFAULT values, then you can use DEFAULT VALUES:
INSERT INTO dbo.computers
DEFAULT VALUES;
If, however, your table only have the one column, then personally using an IDENTITY is the wrong choice; a table that just has an IDENTITY is clearly being misused. Instead, use a SEQUENCE:
CREATE SEQUENCE dbo.Computers START WITH 1 INCREMENT BY 1;
This scales far better, and doesn't suffer the likely race conditions you have. Then, when running an INSERT (or similar) you would use NEXT VALUE FOR dbo.Computers.
For an auto-incrementing identity column the database handles the id value unless I missed something in what you are attempting to do.
public void DemoInsert(string ComputerName, ref int newIdentifier)
{
using (var conn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = conn })
{
cmd.CommandText = "INSERT INTO computers (ComputerName) " +
"VALUES (#ComputerName); " +
"SELECT CAST(scope_identity() AS int);";
cmd.Parameters.AddWithValue("#ComputerName", ComputerName);
cn.Open();
newIdentifier = (int)cmd.ExecuteScalar();
}
}
}
I have similar code like your app, think about it simple crud app
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
void fillGrid()
{
con = new SqlConnection("Data Source=.;Initial Catalog=schoolDb;Integrated Security=True");
da = new SqlDataAdapter("Select * from ogrenciler",con);
ds = new DataSet();
con.Open();
da.Fill(ds, "students");
dataGridView1.DataSource = ds.Tables["students"];
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
fillGrid();
}
private void Addbtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText="insert into students(StudentId,StudentName,StudentSurname,City) values("+StudentId.Text+",'"+StudentName.Text+"','"+StudentSurname.Text+"','"+City.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Updatebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "update Students set ogrenci_ad='"+StudentName.Text+"',StudentName='"+StudentSurname.Text+"',City='"+City.Text+"' where StudentId="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Deletebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "delete from ogrenciler where ogrenci_no="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
}
}

How To delete from both database and datagridview

So i've been looking around the google for the anwser to this found so many diffrenet anwsers but i do not quite understand them and dont really see the way to implement them even thoug i have tryed alot so my issue is basicly that my delete button only deletes from the datagridview and not the database itself i do have the gridview bound to my knowledge but this is the very first form app i make so im a bit puzzeld to what i am doing
private void buttonDel_Click(object sender, EventArgs e)
{///////////////////////////////////////////////////////issue is here
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
//string del = "DELETE FROM Data WHERE RowID = #RowID";
}
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
string query = "insert into data(Navn, NummerPlade, KMKørt, dato)";
query += " values (#Navn, #NummerPlade, #KMKørt, #dato)";
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.AddWithValue("#Navn", textBox1.Text);
cmd.Parameters.AddWithValue("#NummerPlade", textBox8.Text);
cmd.Parameters.AddWithValue("#KMKørt", textBox6.Text);
cmd.Parameters.AddWithValue("#dato", textBox7.Text);
cmd.ExecuteNonQuery();
Connection.Close();
button4_Click(sender, e);
}
private void button4_Click(object sender, EventArgs e)
{
/// Connect / Update
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
Connection.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Data", Connection);
DataTable data = new DataTable();
sqlDa.Fill(data);
dataGridView1.DataSource = data;
}
buttonConn.Hide();
}

Proper way of closing sql connection - without using MARS

My client server is not supporting MARS. So I need to close each sql connection after executing each query. But I have doubt on closing connection when its coming to multiple nested loop query .
My code is
protected void btn_upload_Click(object sender, ImageClickEventArgs e)
{
try
{
SqlConnection con = obj.getcon();
con.Open();
SqlCommand cmd77 = new SqlCommand("select * from emp_details where emp_id='"+emp_id+"'", con);
SqlDataReader dr77 = cmd77.ExecuteReader();
if (dr77.HasRows)//dont insert if employee already exist
{
string query1 = "UPDATE emp_details SET emp_name= #emp_name where emp_id=#emp_id";
SqlCommand cmd = new SqlCommand(query1, con);
cmd.Parameters.Add(new SqlParameter("emp_id", emp_id));
cmd.Parameters.Add(new SqlParameter("emp_name", emp_name))
cmd.ExecuteNonQuery();
}
else
{
insertdataintosql(GetempID,GetempName);
}
con.Close();
}
catch (Exception ex)
{
string ex=ex.Message;
}
}
public void insertdataintosql(string emp_id, string emp_name)
{
SqlConnection con = obj.getcon();
con.Open();
string query = "insert into emp_details(emp_id,emp_name) values(#emp_id,#emp_name)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("emp_id", emp_id));
cmd.Parameters.Add(new SqlParameter("emp_name", emp_name))
cmd.ExecuteNonQuery();
con.Close();
}
Where should I close the first connection for SqlDataReader (dr77) since it is used in if else loop? If not using MARS , Shall I need to open/close a new connection on update query? So is it necessary to close dr77 to before it?

C# Listview , Data type Mismatch on insertion of record

I want to insert some data into Database Using C#
But I get below error
Error:Data type Mismatch when try to Execute
cmd1.ExecuteNonQuery();
private void btnFirst_Click(object sender, EventArgs e)
{
conString =Properties.Settings.Default.TransportationConnectionString;
con.ConnectionString = conString;
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
cmd1.Connection = con;
cmd1.CommandText = "INSERT INTO [BillingGrd] ([InvoiceNo],[FromLocation],[ToLocation],[Material],[Trip],[MetricTon],[BillWeight],[Rate],[BillAmount],[GrandTotal]) Values (#InvoiceNo,#FromLocation,#ToLocation,#Material,#Trip,#MetricTon,#BillWeight,#Rate,#BillAmount,#GrandTotal)";
for(inc=0;inc<listView1.Items.Count;inc++)
{
cmd1.Parameters.AddWithValue("#InvoiceNo", txtBilNo.Text);
cmd1.Parameters.AddWithValue("#FromLocation", listView1.Items[inc].SubItems[0].Text);
cmd1.Parameters.AddWithValue("#ToLocation", listView1.Items[inc].SubItems[1].Text);
cmd1.Parameters.AddWithValue("#Material", listView1.Items[inc].SubItems[2].Text);
cmd1.Parameters.AddWithValue("#Trip", listView1.Items[inc].SubItems[3].Text);
cmd1.Parameters.AddWithValue("#MetricTon", listView1.Items[inc].SubItems[4].Text);
cmd1.Parameters.AddWithValue("#BillWeight", listView1.Items[inc].SubItems[5].Text);
cmd1.Parameters.AddWithValue("#Rate", listView1.Items[inc].SubItems[6].Text);
cmd1.Parameters.AddWithValue("#BillAmount", listView1.Items[inc].SubItems[7].Text);
cmd1.Parameters.AddWithValue("#GrandTotal", textBox1.Text);
}
con.Open();
cmd1.ExecuteNonQuery();//error here datatype mismatch
con.Close();
}
Try This might be work for you.....
if not Then let me know by comment
private void btnFirst_Click(object sender, EventArgs e)
{
conString =Properties.Settings.Default.TransportationConnectionString;
con.ConnectionString = conString;
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
cmd1.Connection = con;
for(inc=0;inc<listView1.Items.Count;inc++)
{
cmd1.CommandText="";
con.Open();
cmd1.CommandText = "INSERT INTO [BillingGrd] ([InvoiceNo],[FromLocation],[ToLocation],[Material],[Trip],[MetricTon],[BillWeight],[Rate],[BillAmount],[GrandTotal]) Values ('"+txtBilNo.Text+"','"+listView1.Items[inc].SubItems[0].Text+"','"+listView1.Items[inc].SubItems[1].Text+"','"+listView1.Items[inc].SubItems[2].Text+"','"+listView1.Items[inc].SubItems[3].Text+"','"+listView1.Items[inc].SubItems[4].Text+"','"+listView1.Items[inc].SubItems[5].Text+"','"+listView1.Items[inc].SubItems[6].Text+"','"+listView1.Items[inc].SubItems[7].Text+'")";
cmd1.ExecuteNonQuery();//error here datatype mismatch
con.Close();
}
}

inserting textbox value to sql server using c#

I need to add a text box value to SQL Server database table. Below is my code:
private void button1_Click(object sender, EventArgs e)
{
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(str);
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
con.Close();
}
But, data should not add in table... please help me...
thanks for ur help...
Try debugging your query first if it works i think your connection with your db isnt working.
string str = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\timetablesystem.mdf;Integrated Security=True;User Instance=True";
is there supposed to be this '.' after data source Data Source=.\\SQLEXPRESS
try this and tell me what is the message information content
private void button1_Click(object sender, EventArgs e)
{
string str = "Server=.\SQLEXPRESS;Database=TestDB;Trusted_Connection=True;";
using( SqlConnection con = new SqlConnection(str)){
try{
con.Open();
string qry = "insert into SubjectMaster (SubjectName) values (#TxtSubjectName)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#TxtSubjectName", TxtSubjectName.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Added Successfully!!");
}
catch{
MessageBox.Show("connection is failed!!");
}
}
}
try this
SqlConnection con = new SqlConnection(#"Data Source=SL-20\SQLEXPRESS;Initial Catalog=TestDB;User ID=sa;Password=sl123;");
string query = " insert into name(name)values('" + TextboxTest.Text + "')";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();

Categories