Delete a record from database - c#

I'm trying to delete record from data base MSSQL by entering the ID and hit delete btn. i didn't get any error and it give recorded deleted successful but once i check database i see the record doesn't deleted
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (txtImgID.Text == "")
{
Response.Write("Enter Image Id To Delete");
}
else
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = new SqlConnection();
con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);
con.Open();
cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);
lblsubmitt.Text = "Data Deleted Sucessfully";
}
}
catch (Exception)
{
lblsubmitt.Text = "You haven't Submited any data";
}
}

var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = #id", con))
{
// I am assuming that id is an integer but if it is a varchar/string then use the line below this one
// cmd.Parameters.Add("#id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
cmd.Parameters.Add("#id", SqlDbType.Int32).Value = idToDelete;
cmd.ExecuteNonQuery();
}
You need to call ExecuteNonQuery which executes the query against the database.
Always use parameters instead of string concatenation in your queries. It guards against sql injection and ensures you never has issues with strings that contain escape characters.
I did not include any error handling or return messages but do note that you are throwing away all the good stuff in your excetion handler's catch block, you will never know why a query failed after this has executed.

Related

Why doesn't my C# code update the SQL Server database although I get the correct number of affected rows

I created the following code:
public static bool setHeadword(int id, string headword)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\pms.mdf;Integrated Security=True";
conn.Open();
SqlCommand command = new SqlCommand("UPDATE headwords SET Headword = #headword WHERE Id = #id", conn);
command.Parameters.AddWithValue("#headword", headword);
command.Parameters.AddWithValue("#id", id);
int result = command.ExecuteNonQuery();
conn.Close();
return true;
}
But the code doesn't work because the value in the database doesn't change.
If I run the code manually in the database the change takes place. But it won't work with C#.
Also the result variable are holding the right number of affected rows (1 in this case).
I'm not sure I have to flush the changes or something else.
Thanks for your help and best regards
Franz
static void Update(int id, string headword)
{
try
{
//You should create connectionString with correct details otherwise fail connection
string connectionString =
"server=.;" +
"initial catalog=employee;" +
"user id=sa;" +
"password=123";
using (SqlConnection conn =
new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE headwords SET Headword=#headword" +
" WHERE Id=#Id", conn))
{
cmd.Parameters.AddWithValue("#Id", id);
cmd.Parameters.AddWithValue("#headword", headword);
int rows = cmd.ExecuteNonQuery();
}
}
}
catch (SqlException ex)
{
//Handle sql Exception
}
}

can't read int value from sql database

I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}

C# Connection must be valid and open Mysql

is there something wrong with my codes. I already try another codes but the problem is still the same. I've been solving this error for a couple of weeks now, and i can't figure it out how to solve it. And also I already try some another code but the problem is still the same.
I want to save a multiple row from dataGrid to my database.
here's the codes that i use to save a multiple row
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conString = new MySqlConnection("datasource = localhost; port = 3306; Initial catalog = dbnewsystem; username = root;password = 1234");
MySqlCommand command1 = new MySqlCommand("INSERT INTO purchaseorder (orNo, ProdNo, Quantity, total)" +
"VALUES(#ORNo,#ProductNo,#quantity,#total )", conString);
command1.Parameters.AddWithValue("#ORNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#ProductNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#quantity", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#total", textBox6.Text);
conString.Open();
command1.ExecuteNonQuery();
command1.Connection = conString;
conString.Close();
command1.CommandType = CommandType.StoredProcedure;
command1.CommandText = "pos_save";
if (command1.ExecuteNonQuery() == 1)
{
MessageBox.Show("saved");
}
else
{
MessageBox.Show("Sorry Nothing to be Update");
}
conString.Close();
}
change sequence
command1.Connection = conString;
command1.ExecuteNonQuery();
You have implemented wrong sequence:
...
conString.Open(); // Connection opened
command1.ExecuteNonQuery(); // Try executing (fail)
command1.Connection = conString; // Connection assigned
Change to
conString.Open(); // Connection opened
command1.Connection = conString; // Connection assigned
command1.ExecuteNonQuery(); // Try executing (fail)
A better design is
// Wrap IDisposable into using
using (MySqlConnection conString = new MySqlConnection("...")) {
conString.Open();
// Make SQL Readable
string sql =
#"INSERT INTO purchaseorder(
orNo,
ProdNo,
Quantity,
total)
VALUES(
#ORNo,
#ProductNo,
#quantity,
#total)";
// Wrap IDisposable into using
using (MySqlCommand command1 = new MySqlCommand(sql, conString)) {
command1.Parameters.AddWithValue("#ORNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#ProductNo", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#quantity", dataGridView1.Rows.Count);
command1.Parameters.AddWithValue("#total", textBox6.Text);
command1.ExecuteNonQuery();
}
}

Deleting Several Rows with a condition

Hello trying to delete several rows of the table according to a condition, however i need some help with it, basically i want to delete all rows, while the condition is true and then stop and leave the rest untouched.
EDIT: Regarding the comments i apologize, im fairly new to programming, sorry if not doing things correctly im new to this website as well.
private void button1_Click(object sender, EventArgs e)
{
string varsql2check = "";
do{
SqlConnection conn = new SqlConnection(#"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd");
conn.Open();
string varsql = "DELETE FROM wgcdoccab WHERE 'tipodoc' ='FSS' and 'FP' "; //sql query
SqlCommand cmd = new SqlCommand(varsql, conn);
SqlDataReader dr = cmd.ExecuteReader();
} while(varsql2check = "SELECT * from wgcdoccab where 'tipodoc' !='FSS' and !='FP' and contribuinte !='999999990' and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120);");
dr.Close();
conn.Close();
}
What you need to do is:
private void button1_Click(object sender, EventArgs e)
{
bool check = true;
do
{
string connectionString = #"Data Source=.\wintouch;Initial Catalog=bbl;User ID=sa;Password=Pa$$w0rd";
string queryString = string.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "DELETE FROM wgcdoccab WHERE 'tipodoc' ='FSS' and 'FP' ";
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
queryString = "SELECT * from wgcdoccab where 'tipodoc' !='FSS' and !='FP' and contribuinte !='999999990' and datadoc != CONVERT(varchar(10),(dateadd(dd, -1, getdate())),120)";
using (SqlCommand command = new SqlCommand(queryString, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
check = true;
}
else
{
check = false;
}
}
}
}
while (check);
}
Generally what I have done by editing your code is:
Add the using statement in order to release the resources from the established connections.
You should be using the returned types from the exeqution of the queries. The ExecuteNonQuery() will return the numbers of rows affected, in our case we are particularly interested in the rows returned from the select statement after the delete query. We create a reader and depending of the number of rows, in our case we are only interested if there are rows or no, branch accoringly. If we get no rows from the select (everything is deleted) we just continue, if we get nothing (reader.HasRows returns false) we repeat the delete query and check again.
Simple as that.

How to insert data into a database table using a SqlCommand

I am trying to insert data into a database that I have that has a table called EmployeeInfo
The user is prompted to enter a last name and select a department ID (displayed to the user as either marketing or development) The column ID automatically increments.
Here is my Code behind
protected void SubmitEmployee_Click(object sender, EventArgs e)
{
var submittedEmployeeName = TextBox1.Text;
var submittedDepartment = selectEmployeeDepartment.Text;
if (submittedEmployeeName == "")
{
nameError.Text = "*Last name cannot be blank";
}
else
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("ConnString");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO EmployeeInfo (LastName, DepartmentID ) VALUES ('" + submittedEmployeeName + "', " + submittedDepartment + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
The error I'm recieving is 'Arguement exception was unhandled by user code'
Here is a picture of it.
As requested. More details
If I had enough reputation, I would rather post this as a reply, but it might actually be the solution.
The reason why it stops there is because you are not providing a legit SqlConnection, since your input is: "ConnString", which is just that text.
The connection string should look something like:
const string MyConnectionString = "SERVER=localhost;DATABASE=DbName;UID=userID;PWD=userPW;"
Which in your case should end up like:
System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(MyConnectionString);
Besides that, you should build your connections like following:
using (SqlConnection con = new SqlConnection(MyConnectionString)) {
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = xxxxxx; // Your query to the database
cmd.Connection = con;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
This will do the closing for you and it also makes it easier for you to nestle connections. I did a project recently and did the connection your way, which ended up not working when I wanted to do more than one execute in one function. Just important to make a new command for each execute.

Categories