I have a table and I want to delete all rows with a specific card serial . There are multiple rows with the same card serial .So I wrote this code but it seems that's not working:
try
{
using (SqlConnection con = new SqlConnection(WF_AbsPres.Properties.Settings.Default.DbConnectionString))
{
con.Open();
SqlCommand command2 = new SqlCommand("DELETE FORM DevInOut where Cardserial='" + textBox5.Text + "'", con);
command2.ExecuteNonQuery();
con.Close();
}
}
catch (SqlException ex)
{
}
how can assure all the rows will be deleted . Should I use procedure? How do I use procedure?
Change your FORM to FROM.
And please always use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.
using (SqlConnection con = new SqlConnection(WF_AbsPres.Properties.Settings.Default.DbConnectionString))
{
con.Open();
SqlCommand command2 = new SqlCommand("DELETE FROM DevInOut where Cardserial=#Cardserial", con);
commdand2.Parameters.AddWithValue("#Cardserial", textBox5.Text);
command2.ExecuteNonQuery();
con.Close();
}
Read more from DELETE (Transact-SQL)
Related
I'm writing a SQL command to insert new record into a SQL Server database using an ASP.NET website, but it's not working, although it's preserving the id of an auto-increment column.
When the auto-increment value is 5, and then I try to insert a new row using Management Studio, it does insert the record with id=7.
Thanks to anyone who tells me what I'm doing wrong here
Here is the code:
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter();
try
{
cmd.CommandText = "insert into Bill values (#car, #date, #client, #speedometer, #employee, #notes)";
cmd.Parameters.AddWithValue("#car", carid);
cmd.Parameters.AddWithValue("#date", txt_bill_date.Value);
cmd.Parameters.AddWithValue("#client", cmb_client_name.Value);
cmd.Parameters.AddWithValue("#speedometer", txt_car_gas.Value);
cmd.Parameters.AddWithValue("#employee", cmb_emp.Value);
cmd.Parameters.AddWithValue("#notes", txt_notes.Value);
cmd.ExecuteNonQuery();
cmd.CommandText = "select top 1 bill_id from Bill order by bill_id DESC";
DataTable inserted = new DataTable();
sda.Fill(inserted);
if (inserted.Rows.Count > 0)
{
billid = inserted.Rows[0]["bill_id"].ToString();
contractid.Values["id"] = inserted.Rows[0]["bill_id"].ToString();
Response.Redirect("BillContracts.aspx");
}
}
catch(Exception ex)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "swal('خطأ', '" + ex.Message + "', 'error')", true);
}
Sorry for the inconvenience guys
your advice of putting a break point on the catch saved my day
the problem was with the columns type
apparently be mistake i added an int column for a string value
i apologize again if i didn't do this right
Here is a Picture of My Table Named CategoryTable
I used The Following Code to Delete Data from the Above Table using a ComboBox which is named as SelectCategoryComboBoxBut it does nothing.it acts like an un-programed button.
here is my code:
try
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "DELETE FROM CategoryTable WHERE CategoryName='" + SelectCategoryComboBox.SelectedText + "'";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
}
}
catch{
MessageBox.Show("Error");
}
Change
SelectCategoryComboBox.SelectedText
to
SelectCategoryComboBox.SelectedItem.ToString()
I have successfully created connection of database but now I'm having problem in insertion of data. Here is my code:
String Connection = null;
SqlConnection con;
SqlCommand cmd;
String sql = null;
Connection="Data Source=DELL\\SQLEXPRESS; initial Catalog= BSSE;Integrated Security=True";
con = new SqlConnection(Connection);
sql = "INSERT INTO Records (Roll_No,Name,Marks) VALUES (" + textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + ");";
try
{
con.Open();
cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
First, your SQL statement is incorrect. You are missing single quote between values field. Later, you build SQL statement by using string concatenation and this is dangerous because can be exposed to SQL Injection. Use Parameterized Query instead.
try
{
con.Open();
cmd = new SqlCommand("INSERT INTO Records (Roll_No,Name,Marks) VALUES (#rollNo, #Name, #Marks)", con);
cmd.Parameters.AddWithValue("#rollNo", textBox1.Text);
cmd.Parameters.AddWithValue("#Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Marks", textBox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show ("Success of data insertion ");
cmd.Dispose();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Check your connection string. I usually write it as:
string Connection = #"Data Source=DELL\SQLEXPRESS;Initial Catalog = BSSE; Integrated Security = true";
If the roll number is supposed to be an integer, you need to parse
it.
int.Parse(textBox1.Text)
I suggest to use store procedures instead of sending blocks of SQL code from the c# Application, here is a reference to the SQL Store Procedures: https://msdn.microsoft.com/en-us/library/ms190782.aspx. You can reduce the possibility of SQL injection by adding parameters to your query instead of plain text, also you need to validate the input. You can create calls with parameters too. There are many ways to call a SQL database query from C#, Here is more information about Store Procedures that can give you a clue: http://csharp-station.com/Tutorial/AdoDotNet/Lesson07
Here is what I have written so far.There is no exception so I am assuming the connection is working fine but no data is inserted into the database table. Please tell me what is wrong with my code
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyETL.Properties.Settings.connectionStr"].ConnectionString);
try
{
conn.Open();
// foreach (student stu in stulist)
// {
string strQuery = "INSERT INTO Student(Sid,st_name) VALUES (#id,#name)";
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#id", "111");
cmd.Parameters.AddWithValue("#name", "nallia");
cmd.ExecuteNonQuery();
}
catch
{
conn.Close();
}
Try this
static void Insert()
{
try
{
string connectionString =System.Configuration.ConfigurationManager.ConnectionStrings["MyETL.Properties.Settings.connectionStr"].ConnectionString;
using (SqlConnection conn =new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Student(Sid,st_name) VALUES (" +
"#id,#name)", conn))
{
cmd.Parameters.AddWithValue("#Id", 111);
cmd.Parameters.AddWithValue("#Name", "nallia");
int rows = cmd.ExecuteNonQuery();
//rows number of record got inserted
}
}
}
catch (SqlException ex)
{
//Log exception
//Display Error message
}
}
It has been nearly 2,5 years but if you haven't still solved this problem, you should change the "copy to output directory" attribute to "copy if newer". Your database is changing but every time you start debugging, you read the initial version of database so, you see that there is no changes.
i want to write data into a local database table.
When i run the code there are no erros and when i count the rows after the insert statement the message box shows me that a row was inserted.
But when i close the programm and look in my database there are no new rows.
I'm using C# and Visual Studio 2013.
Do anybody know what the problem is?
Thank you.
String connection = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Datenbank.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection cnn = new SqlConnection(connection);
cnn.Open();
String query = "INSERT INTO Customer (ID, Name) VALUES (#id, #name)";
SqlCommand command = new SqlCommand(query, cnn);
command.Parameters.AddWithValue("#id", 1);
command.Parameters.AddWithValue("#name", 'John');
SqlDataReader reader;
command.ExecuteNonQuery();
query = "Select count(ID) from Customer";
command = new SqlCommand(query, cnn);
reader = command.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader[0].ToString());
}
reader.Close();
Try like this:
try {
int rowsAffected = command.ExecuteNonQuery();
if (0 < rowsAffected)
MessageBox.Show("Success!");
else
MessageBox.Show("Failed!");
} catch (SqlException ex) {
MessageBox.Show(ex.Message);
} finally {
if (cnn.State == ConnectionState.Open)
cnn.Close();
}
Also refer: Why saving changes to a database fails?