DeleteButton code for deleting the data from SQL Server database - c#

I have a form name "AddNewUnitForm" through this I am saving data in a SQL Server database. Please advice code for "DeleteButton" deleting the data from database by selected data of datagridview
SaveButton code is as under for the reference
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("usp_UnitMasterInsertDetails", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
//Parameter
cmd.Parameters.AddWithValue("UNITNAME", AddUnitTextBox.Text);
//Open Connection
conn.Open();
// ExecuteReader (Select Statement)
// ExecuteScalar (Select Statement)
// ExecuteNoQuery (Insert, Update or Delete)
cmd.ExecuteNonQuery();
MessageBox.Show("ADDED SUCCESSFULLY", "Succesful", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

create a stored procedure to delete records
use transactions to if there is a fall back, while deleting
your delete button code will be similar to the insert here you will be calling stored procedure for deleting, with key parameter to pass the stored procedure.
if you want to do soft delete make a column with flag IsDeleted and changes the flag when deleted

Related

Prepared MySQL Statement fails insert with no error

I'm using MySQL to try and add a new user to my database. User got an Id, a First Name, a Last Name and a Date of Birth. But when I run the code below (And run conn.close() after I'm done) the database tells me (using HeidiSQL) that in the Table Overview there is now a new row in the table but when I open the Data Tab to look at the rows, there is nothing. It's empty. Running a COUNT(*) also returns 0.
using (MySqlTransaction transaction = conn.BeginTransaction())
{
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO USERS(NAME_FIRST,NAME_LAST,DATE_OF_BIRTH) VALUES(#nameFirst,#nameLast,#dateOfBirth)";
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#nameFirst", user.NameFirst);
cmd.Parameters.AddWithValue("#nameLast", user.NameLast);
cmd.Parameters.AddWithValue("#dateOfBirth", user.DateOfBirth);
cmd.Prepare();
cmd.ExecuteNonQuery();
lastInsertId = (uint)cmd.LastInsertedId;
}
}
I get no errors. Nothing shows up in any log and everyone sees the same as me.
What am I doing wrong?
It feels like it's the use of begintransaction which starts a transaction. This means autocommit=false for the entirety of the transaction.
After ExecuteNonQuery Do a transaction.Commit(); and see if they show up.
More Info Here

Can't seem to insert date into SQL Server database

I have created a table tblAttendence in the database that has 2 columns: Date (datetime) and RegNo (int). I have to insert the current date & time and a registration number from a label in the form.
C# code:
private void btnMarkAtt_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("MarkAtt", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#Date", DateTime.Now);
sqlCmd.Parameters.AddWithValue("#RegNo", int.Parse(lblRegNo.Text));
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Attendance marked successfully!");
}
}
Stored procedure MarkAtt:
ALTER PROCEDURE [dbo].[MarkAtt]
#Date DATETIME,
#RegNo INT
AS
INSERT INTO tblAttendence(Date, RegNo)
VALUES (#Date, #RegNo)
There is no error shown in the code. The debugging doesn't stop to show an error. When I press the button, just nothing happens (neither the data is inserted, nor the message box is shown).
I can't seem to find out what is going on. The connection string is correct (I have used it in the same form and it works). Is there something wrong with the connection? Or the stored procedure? Or anything else that I am missing?

insert data into second table if insert into first table has been done successfully otherwise don't insert data

i have two tables in Sqlite i want if user inserted data into first table then a specific data be inserted into the second table but if insertion on the first table succeded and on second table failed then data inserted into the first table must be removed , how to manage this in c# with sqlite ?
i mean is there any way in sqlite or sql to manage this??
here is the code i use in c# :
queryString = string.Format(#"insert into customerHost values('{0}','{1}','{2}','{3}','{4}','{5}')",
"1", userID, hostPlan, hostServiceDate, hostExpiresOn ,hostPrice);
if (new dataAccess().insertQuery(queryString) == 1)// if data has been inserted into the first table successfully then insert into the second one
{
MessageBox.Show("good", "good");
queryString = String.Format(#"insert into hostUpdate values('{0}','{1}','{2}','{3}')",
Guid.NewGuid().ToString(), userID, hostServiceDate, hostExpiresOn);
if (new dataAccess().insertQuery(queryString) != 1)//if data insertion into the second table failed then throw an errro....in fact data inserted into the first table must be removed
MessageBox.Show("some errors has been occured ", "error");
}
you can use triggers in SQLite.
https://www.sqlite.org/lang_createtrigger.html
you can google about it easily.. i did and below is some part of the code which was found in the first link given by google.
please note that below is just an example, below is the the complete answer and it is a must that you read the attached and may be few more articles on transactions in databases....
string cs = "URI=file:test.db";
using (SqliteConnection con = new SqliteConnection(cs))
{
con.Open();
using(SqliteTransaction tr = con.BeginTransaction())
{
using (SqliteCommand cmd = con.CreateCommand())
{
cmd.Transaction = tr;
cmd.CommandText = "DROP TABLE IF EXISTS Friends";
cmd.ExecuteNonQuery();
...............
}
tr.Commit();
}
con.Close();
}
}

ASP.NET Not sure if reading from SQL Server database correctly

I am trying to make a user register page that uploads the user data to a sql server database. I want to have the capability to check if a username already exists and prevent it from being made. I am able to create a new user with first name, last name, username, etc and it updates the database, but it doesn't stop me from creating a user with a username that already exists in the database. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
//connect registration form to database
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sandboxConnectionStringUserData"].ConnectionString);
conn.Open(); //open connection
//SQL Query
string checkUserName = "select count(*) from UserData where UserName='"+TextBoxUserName.Text+"'";//checks if username is already there
SqlCommand command = new SqlCommand(checkUserName, conn);
int temp = Convert.ToInt32(command.ExecuteScalar().ToString());
if(temp == 1)
{
Response.Write("User name already exists");
}
conn.Close(); //close the database
}
}
I tried debugging and temp's value never changes to 1.
Thanks!
Just add a UNIQUE constraint to the username column and handle the sql exception in your app. Additionally you can/should write an SP that takes username as an argument and checks for existence in the table, and use that in your server-side validation after the form is sorted but before the insert (save()) occurs. That way you reduce the probability of encountering a sql exception but can still deal with it if it occurs.
Your current method of appending the form data to a raw sql query is going to open you up to sql injection. Use a parameterized query instead.
Creating a UNIQUE constraint on the UserName column is a good start. I would also create a stored procedure that checks the existence of the user and inserts or updates as well structure your code a bit more efficiently. The username should be passed in as a parameter and you should properly dispose of the connection object.
As an example your stored procedure may look like:
CREATE PROCEDURE dbo.uspUserData #userName VARCHAR(50)
AS
BEGIN
IF EXISTS(SELECT 1 FROM dbo.UserData WITH(NOLOCK)
WHERE UserName = #userName)
BEGIN
-- update
END
ELSE
BEGIN
-- insert
END
END
And your .NET code may look like:
using (
SqlConnection conn =
new SqlConnection(
ConfigurationManager.ConnectionStrings["sandboxConnectionStringUserData"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("uspUserData", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = TextBoxUserName.Text;
conn.Open();
cmd.ExecuteNonQuery();
}
}

How can I delete a single entry from a table

I have a listbox with usernames, and a remove button I want the selected a user (with all entered data associated with that user) to be deleted when the remove button is clicked.
My code
SqlConnection con = new SqlConnection("Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=staff;Integrated Security=True");
con.Open();
string sql = #"DELETE FROM staff1;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
this code deletes the whole table.
How can I just delete the selected user?
You need a WHERE clause to select the required record. You have to get the username of the selected user to be deleted and pass it to #UserName parameter.
var userName = (listBox.SelectedItem as DataRowView)["UserName"].ToString();
string sql = #"DELETE FROM staff1 WHERE Username = #UserName;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#UserName",useName);
cmd.ExecuteNonQuery();
con.Close();
See this thread on how to use parameters in the SQL.
When you execute a delete query, in order to delete only 1 row from the table you need to add a WHERE clause.
Based on the comments the workflow should be something like: you click on a delete button, you send the name of the staff you want to delete to the command, which looks like:
string sql = #"DELETE FROM staff1 where Name=#Name;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Name","NameReceivedFromList");
cmd.ExecuteNonQuery();
con.Close();
When you are deleting you should remember to add a Where clause, it is actually very powerfull here is some examples that will get you started
The following query will delete only one element
DELETE FROM Table WHERE Table.PrimaryField = Value
The following query will delete all items that matches
DELETE FROM Table WHERE Table.Field = Value
You can also have a join in your delete statement for more complex delete queries
DELETE A FROM Table A
INNER JOIN TableB B ON A.Key = B.Key
WHERE B.PrimaryField = Value

Categories

Resources