Check if a record exists in the database - c#

I am using these lines of code to check if the record exists or not.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
But I am getting an error:
Object reference not set to an instance of an object.
I want to do:
if (UserExist > 0)
// Update record
else
// Insert record

ExecuteScalar returns the first column of the first row. Other columns or rows are ignored. It looks like your first column of the first row is null, and that's why you get NullReferenceException when you try to use the ExecuteScalar method.
From MSDN;
Return Value
The first column of the first row in the result set, or a null
reference if the result set is empty.
You might need to use COUNT in your statement instead which returns the number of rows affected...
Using parameterized queries is always a good practise. It prevents SQL Injection attacks.
And Table is a reserved keyword in T-SQL. You should use it with square brackets, like [Table] also.
As a final suggestion, use the using statement for dispose your SqlConnection and SqlCommand:
SqlCommand check_User_Name = new SqlCommand("SELECT COUNT(*) FROM [Table] WHERE ([user] = #user)" , conn);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
int UserExist = (int)check_User_Name.ExecuteScalar();
if(UserExist > 0)
{
//Username exist
}
else
{
//Username doesn't exist.
}

The ExecuteScalar method should be used when you are really sure your query returns only one value like below:
SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'
If you want the whole row then the below code should more appropriate.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = #user)" , conn);
check_User_Name.Parameters.AddWithValue("#user", txtBox_UserName.Text);
SqlDataReader reader = check_User_Name.ExecuteReader();
if(reader.HasRows)
{
//User Exists
}
else
{
//User NOT Exists
}

sqlConnection.Open();
using (var sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "'", sqlConnection))
{
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
lblMessage.Text ="Record Already Exists.";
}
else
{
lblMessage.Text ="Record Not Exists.";
}
reader.Close();
reader.Dispose();
}
sqlConnection.Close();

MySqlCommand cmd = new MySqlCommand("select * from table where user = '" + user.Text + "'", con);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds1 = new DataSet();
da.Fill(ds1);
int i = ds1.Tables[0].Rows.Count;
if (i > 0) {
// Exist
}
else {
// Add
}

I would use the "count" for having always an integer as a result
SqlCommand check_User_Name = new SqlCommand("SELECT count([user]) FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') " , conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist == 1) //anything different from 1 should be wrong
{
//Username Exist
}

try this
public static bool CheckUserData(string phone, string config)
{
string sql = #"SELECT * FROM AspNetUsers WHERE PhoneNumber = #PhoneNumber";
using (SqlConnection conn = new SqlConnection(config)
)
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#PhoneNumber", phone);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (reader.HasRows)
{
return true; // data exist
}
else
{
return false; //data not exist
}
}
}
}

Use try catch:
try
{
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
int UserExist = (int)check_User_Name.ExecuteScalar();
// Update query
}
catch
{
// Insert query
}

You can write as follows:
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = '" + txtBox_UserName.Text + "') ", conn);
if (check_User_Name.ExecuteScalar()!=null)
{
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
//Username Exist
}
}

I was asking myself the same question, and I found no clear answers, so I created a simple test.
I tried to add 100 rows with duplicate primary keys and measured the time needed to process it. I am using SQL Server 2014 Developer and Entity Framework 6.1.3 with a custom repository.
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Dim e = employees.Select(Function(item) item.Name = "e").FirstOrDefault()
If e Is Nothing Then
employees.Insert(newE)
End If
Next
2.1 seconds
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Try
employees.Insert(newE)
Catch ex As Exception
End Try
Next
3.1 seconds

sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM tblAttendance",con);
sda.Fill(dt);
string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);
if (bar >= 1){
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {
dt.Clear();
MetroFramework.MetroMessageBox.Show(this, "empty");
}

protected void btnsubmit_Click(object sender, EventArgs e)
{
string s = #"SELECT * FROM tbl1 WHERE CodNo = #CodNo";
SqlCommand cmd1 = new SqlCommand(s, con);
cmd1.Parameters.AddWithValue("#CodNo", txtid.Text);
con.Open();
int records = (int)cmd1.ExecuteScalar();
if (records > 0)
{
Response.Write("<script>alert('Record not Exist')</script>");
}
else
{
Response.Write("<script>alert('Record Exist')</script>");
}
}
private void insert_data()
{
SqlCommand comm = new SqlCommand("Insert into tbl1(CodNo,name,lname,fname,gname,EmailID,PhonNo,gender,image,province,district,village,address,phonNo2,DateOfBirth,school,YearOfGraduation,exlanguage,province2,district2,village2,PlaceOfBirth,NIDnumber,IDchapter,IDpage,IDRecordNumber,NIDCard,Kankur1Year,Kankur1ID,Kankur1Mark,Kankur2Year,Kankur2ID,Kankur2Mark,Kankur3Year,Kankur3ID,Kankur3Mark) values(#CodNo,N'" + txtname.Text.ToString() + "',N'" + txtlname.Text.ToString() + "',N'" + txtfname.Text.ToString() + "',N'" + txtgname.Text.ToString() + "',N'" + txtemail.Text.ToString() + "','" + txtphonnumber.Text.ToString() + "',N'" + ddlgender.Text.ToString() + "',#image,N'" + txtprovince.Text.ToString() + "',N'" + txtdistrict.Text.ToString() + "',N'" + txtvillage.Text.ToString() + "',N'" + txtaddress.Value.ToString() + "','" + txtphonNo2.Text.ToString() + "',N'" + txtdbo.Text.ToString() + "',N'" + txtschool.Text.ToString() + "','" + txtgraduate.Text.ToString() + "',N'" + txtexlanguage.Text.ToString() + "',N'" + txtprovince1.Text.ToString() + "',N'" + txtdistrict1.Text.ToString() + "',N'" + txtvillage1.Text.ToString() + "',N'" + txtpbirth.Text.ToString() + "','" + txtNIDnumber.Text.ToString() + "','" + txtidchapter.Text.ToString() + "', '" + txtidpage.Text.ToString() + "','" + txtrecordNo.Text.ToString() + "',#NIDCard,'" + txtkankuryear1.Text.ToString() + "','" + txtkankurid1.Text.ToString() + "','" + txtkankurscore1.Text.ToString() + "','" + txtkankuryear2.Text.ToString() + "','" + txtkankurid2.Text.ToString() + "','" + txtkankurscore2.Text.ToString() + "','" + txtkankuryear3.Text.ToString() + "','" + txtkankurid3.Text.ToString() + "','" + txtkankurscore3.Text.ToString() + "')", con);
flpimage.SaveAs(Server.MapPath("~/File/") + flpimage.FileName);
string img = #"~/File/" + flpimage.FileName;
flpnidcard.SaveAs(Server.MapPath("~/Tazkiera/") + flpnidcard.FileName);
string img1 = #"~/Tazkiera/" + flpnidcard.FileName;
comm.Parameters.AddWithValue("CodNo", Convert.ToInt32(txtid.Text));
comm.Parameters.AddWithValue("image", flpimage.FileName);
comm.Parameters.AddWithValue("NIDCard", flpnidcard.FileName);
comm.ExecuteNonQuery();
con.Close();
Response.Redirect("~/SecondPage.aspx");
//Response.Write("<script>alert('Record Inserted')</script>");
}
}

Use the method Int.Parse() instead. It will work.

I had a requirement to register user. In that case I need to check whether that username is already present in the database or not. I have tried the below in C# windows form application(EntityFramework) and it worked.
var result = incomeExpenseManagementDB.Users.FirstOrDefault(x => x.userName == registerUserView.uNameText);
if (result == null) {
register.registerUser(registerUserView.fnameText, registerUserView.lnameText, registerUserView.eMailText, registerUserView.mobileText, registerUserView.bDateText, registerUserView.uNameText, registerUserView.pWordText);
} else {
MessageBox.Show("User Alreay Exist. Try with Different Username");
}

Related

Insert incremented ID from the tbl_project to tbl_expense it must have same ID. I use PKey & Fkey the ID must be returned

There is no error in this code. The only concern I face is when I try to save in the database the FK won't get the id of PK. I already setup my database relationship and it connect id - projectid.
if (textID.Text == "" && textProject.Text == "" && textAmount.Text == "")
{
MessageBox.Show("Please Enter Details..!");
}
else
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM tbl_project WHERE Contract_ID = '" + textID.Text + "'", conn);
DataTable datatbl = new DataTable();
adapter.Fill(datatbl);
if (datatbl.Rows.Count == 1)
{
MessageBox.Show("Contract ID Already Exist!!");
}
else
{
SqlDataAdapter adap1 = new SqlDataAdapter("INSERT INTO tbl_project(Contract_ID,Contract_Amount,Contractor,Project_Name,Start_Date,End_Date,Year,Address,Remarks,Status)VALUES('" + textID.Text + "','" + textAmount.Text + "','" + textContract.Text + "','" + textProject.Text + "','" + dateTimePicker1.Value.Date + "','" + dateTimePicker2.Value.Date + "','" + textYear.Text + "','" + textAddress.Text + "','" + textOthers.Text + "','" + comboBox5.Text + "')", conn);
DataTable fill1 = new DataTable();
adap1.Fill(fill1);
SqlDataAdapter adap2 = new SqlDataAdapter("INSERT INTO tbl_expense(CONTRACT,CONTRACT_ID,CONTRACTOR,PROJECT_STATUS,COVERED_PERIOD,END_PERIOD,PROJECT_AMOUNT)VALUES('" + textProject.Text + "','" + textID.Text + "','" + textContract.Text + "','" + comboBox5.Text + "','" + dateTimePicker1.Value.Date + "','" + dateTimePicker2.Value.Date + "','" + textAmount.Text + "')", conn);
DataTable data2 = new DataTable();
adap2.Fill(data2);
MessageBox.Show("Project Details Save...");
clear();
refresh();
}
}
From the information you've provided, it seems you are creating a value in two tables based on Contract_Id column and you are checking if the record already exists, you do not insert the records, otherwise you post the records.
Since, I cannot see the relationship between tbl_project and tbl_expense, I assume you are trying to insert Contract_Id as a foreign key in both the tables.
If that is the case, then I would suggest use below version of the code.
public void InsertIfNotExists()
{
if (textID.Text == "" && textProject.Text == "" && textAmount.Text == "")
{
MessageBox.Show("Please Enter Details..!");
}
else
{
using(var connection = new SqlConnection(DbConnectionString)) // Pass DbConnectionString for your SQL server instance
{
var query = #"
IF NOT EXISTS (SELECT * FROM tbl_project WHERE Contract_ID = #Contract_ID)
BEGIN
-- Here we are checking if the row already exists for the variable #Contract_ID
INSERT INTO tbl_project (Contract_ID, Contract_Amount, Contractor, Project_Name, Start_Date, End_Date, Year, Address, Remarks, Status)
VALUES (#Contract_ID, #Contract_Amount, #Contractor, #Project_Name, #Start_Date, #End_Date, #Year, #Address, #Remarks, #Status);
-- We are inserting the values since Contract_ID was not matched in the database.
INSERT INTO tbl_expense (CONTRACT, CONTRACT_ID, CONTRACTOR, PROJECT_STATUS, COVERED_PERIOD, END_PERIOD, PROJECT_AMOUNT)
VALUES (#CONTRACT, #CONTRACT_ID, #CONTRACTOR, #PROJECT_STATUS, #COVERED_PERIOD, #END_PERIOD, #PROJECT_AMOUNT);
-- We are inserting expense based on Contract_ID
END;
"
;
using (var cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#Contract_ID", textID.Text);
cmd.Parameters.AddWithValue("#Contract_Amount", textAmount.Text);
cmd.Parameters.AddWithValue("#Contractor", textContract.Text);
cmd.Parameters.AddWithValue("#Project_Name", textProject.Text);
cmd.Parameters.AddWithValue("#Start_Date", dateTimePicker1.Value.Date);
cmd.Parameters.AddWithValue("#End_Date", dateTimePicker2.Value.Date);
cmd.Parameters.AddWithValue("#Year", textYear.Text);
cmd.Parameters.AddWithValue("#Address", textAddress.Text);
cmd.Parameters.AddWithValue("#Remarks", textOthers.Text);
cmd.Parameters.AddWithValue("#Status", comboBox5.Text);
cmd.Parameters.AddWithValue("#CONTRACT", textProject.Text);
cmd.Parameters.AddWithValue("#CONTRACTOR", textContract.Text);
cmd.Parameters.AddWithValue("#PROJECT_STATUS", comboBox5.Text);
cmd.Parameters.AddWithValue("#COVERED_PERIOD", dateTimePicker1.Value.Date);
cmd.Parameters.AddWithValue("#END_PERIOD", dateTimePicker2.Value.Date);
cmd.Parameters.AddWithValue("#PROJECT_AMOUNT", textAmount.Text);
connection.Open();
var rA = cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show(rA > 0 ? "Data Successfully saved!" : "Data already exists!");
}
}
}
}
In the code above, we are formulating the SQL Statement in a way, that you do not have to fetch and compare and then post to the database, saves you from the round trips for a simple operation.
Also, you'll notice, we are using parameterized query, where we are passing the parameters in the SQL statement, as mentioned in the comments by #Always Learning, it is a good thing from guys who try to mess around with your database, this will prevent SQL Injections.

System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'

Im trying to insert this test data in my sql database and I'm getting this error: System.Data.SqlClient.SqlException: 'Incorrect syntax near '2'.'
Any ideas how to solve this?
DateTime date = DateTime.Now;
string test = "{'payload': {'businessName': 'COMPANY1', 'subscriberName': 'JOHN DOE', 'accountNumber': 'CY68005000121234567890123456', 'numberOfRecords': 1," +
"'currentBalance': 4195.5, 'transactions': [{'transactionNumber': 'TR00000000','sequenceNumber': '000','transactionCode': '305','actualDateTime': '201812041624'," +
"'transactionValueDate': '2018-12-04', 'transactionCurrencyCode': 'EUR', 'transactionAmount': -1149.5, 'balance': 4195.5, 'chequeNo': '', 'depositedBy': 'CY68005000121234567890123456'," +
"'customerReference': 'uniqueValue', 'paymentNotes': 'NOTES', 'exchangeRate': 0}]}, 'errors': null}";
trans = JsonConvert.DeserializeObject<HB_transactions>(test);
for (int i=0; i<trans.payload.transactions.Count; i++)
{
string query = "SELECT TransactionId FROM AABankTransTable";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dataReader = cmd.ExecuteReader();
bool exists = false;
while(dataReader.Read())
{
if(dataReader[0].ToString() == trans.payload.transactions[i].transactionNumber)
{
exists = true;
break;
}
}
dataReader.Close();
if (exists) continue;
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES ('" + trans.payload.transactions[i].transactionNumber + "', 'HB', " + args[0] + ", '" + trans.payload.transactions[i].transactionCurrencyCode + "', " +
trans.payload.transactions[i].transactionAmount + ", " + date + ", 0, '" + trans.payload.transactions[i].depositedBy + "', '" +
trans.payload.transactions[i].paymentNotes + "', " + DateTime.Parse(trans.payload.transactions[i].transactionValueDate) + ")";
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
Solved by using SQL parameters instead of string concatenation.
query = "INSERT INTO AABankTransTable " +
"(TransactionId, Bank, ComID, Currency, Amount, DownloadDate, Processed, CreditorName, RemittanceDetails, ValueDate)" +
"VALUES (#TransID, 'HB', #COMID, #curr, #amount, #dlDate, 0, #depositor, #Details, #TransDate)";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#TransID", trans.payload.transactions[i].transactionNumber);
cmd.Parameters.AddWithValue("#COMID", args[0]);
cmd.Parameters.AddWithValue("#curr", trans.payload.transactions[i].transactionCurrencyCode);
cmd.Parameters.AddWithValue("#amount", trans.payload.transactions[i].transactionAmount);
cmd.Parameters.AddWithValue("#dlDate", date);
cmd.Parameters.AddWithValue("#depositor", trans.payload.transactions[i].depositedBy);
cmd.Parameters.AddWithValue("#Details", trans.payload.transactions[i].paymentNotes);
cmd.Parameters.AddWithValue("#TransDate", DateTime.Parse(trans.payload.transactions[i].transactionValueDate));
cmd.ExecuteNonQuery();

OleDbDataReader does not read last record

I see 5 records to be inserted, but only 4 are inserted. The last record is not inserted, and I can not figure out why. Copying from one database to the other. First is an access database, the second is a sql server database.
OleDbCommand cmd2 = new OleDbCommand();
OleDbDataReader oledbReader2;
using (cmd2 = new OleDbCommand())
{
query = "SELECT ID, STRAATNAAM, 'NL' AS TAALCODE, PKANCODE, CITY FROM Temp_Unique_Streetnames WHERE TRIM(Temp_Unique_Streetnames.STRAATNAAM) <> '' AND ID > " + lastId.ToString() + " ORDER BY ID";
WriteToFile(query);
cmd2.CommandText = query;
cmd2.CommandType = CommandType.Text;
cmd2.Connection = cn2;
using (oledbReader2 = cmd2.ExecuteReader())
{
while (oledbReader2.Read())
{
try
{
counter += 1;
query = "insert into tblgeo_street ( autoid, street_id, language, country, city, streetname, zip) values (" + counter.ToString() +
" , " + oledbReader2.GetValue(0).ToString() +
" , 'NL', 23, " + oledbReader2.GetValue(4).ToString() +
" , '" + oledbReader2.GetValue(1).ToString().Replace('\'', 'ยด') + "'" +
" , " + oledbReader2.GetValue(3).ToString() + ") ";
OleDbCommand cmd3 = new OleDbCommand(query, cn3);
WriteToFile(query);
cmd3.ExecuteNonQuery();
}
catch (Exception errorException)
{
actionSucceedded = false;
//eventLog1.WriteEntry("Open db threw exception " + errorException.Message);
WriteToFile("insert tblgeo_street threw exception " + errorException.Message);
}
}
}
}

How to Update existing record and insert new record in SQL table ? SQL

I have a table.I want to update the table.Actually I have a gridview which retrieve values from SQL table.When page load then gridview load the values .I want that when i insert new values in gridview then in SQL Table existing values update and also new values insert in the same table using SINGLE query.How can i do this?Just tell me SQL query which works in C#,ASP.NET
Thanks
public void insert(object sender, EventArgs e)
{
string user = Session["name"].ToString();
SqlConnection cnn = new SqlConnection("Data Source=HAMEED_KHAN\\SQLEXPRESS;Initial Catalog=db_compiler;Integrated Security=True");
SqlCommand cmd3 = new SqlCommand("SELECT User_ID from tbl_user WHERE User_Name='" + user + "'", cnn);
cnn.Open();
string id = cmd3.ExecuteScalar().ToString();
int ID = Int32.Parse(id);
Session["ID"] = ID;
string d = Session["value"].ToString();
SqlCommand cmd2 = new SqlCommand("SELECT Database_id FROM Create_db WHERE Database_Name='" + d + "'", cnn);
Response.Write("<script>Var Z=Prompt('Enter Table Name');</script>");
string dbid = cmd2.ExecuteScalar().ToString();
cnn.Close();
int D_ID = Int32.Parse(dbid);
string str = "";
string type = "";
for (int i = 0; i < GridView2.Rows.Count; i++)
{
str = GridView2.Rows[i].Cells[1].Text.ToString();
type = GridView2.Rows[i].Cells[2].Text.ToString();
string Name = GridView2.Rows[i].Cells[1].Text.ToString();
string Type = GridView2.Rows[i].Cells[2].Text.ToString();
string size = GridView2.Rows[i].Cells[3].Text.ToString();
CheckBox allow = GridView2.Rows[i].Cells[4].Controls[0] as CheckBox;
CheckBox primary = GridView2.Rows[i].Cells[5].Controls[0] as CheckBox;
string UserID = Session["ID"].ToString();
int UID = Int32.Parse(UserID);
string date = DateTime.Now.ToString();
string A = (allow.Checked == true ? "NULL" : "NOT NULL");
string P = (primary.Checked == true ? "PRIMARY KEY" : "");
string Table = Session["TBL_NAME"].ToString();
string queryy ="USE db_compiler UPDATE tbl_field SET Column_Name='" + Name + "', Data_Type='" + Type + "',Size='" + size + "',Database_id='" + D_ID + "',Allow_Null_='" + (allow.Checked == true ? "true" : "false") + "',Primary_Key_='" + (primary.Checked == true ? "true" : "false") + "',User_id='" + UID + "',Date='" + date + "' WHERE Table_Name='" + Table + "' IF ##ROWCOUNT=0 insert into tbl_field (Table_Name,Column_Name,Data_Type,Size,Database_id,Allow_Null_,Primary_Key_,User_id,Date) VALUES('" + Table + "','" + Name + "','" + Type + "','" + size + "','" + D_ID + "','" + (allow.Checked == true ? "true" : "false") + "','" + (primary.Checked == true ? "true" : "false") + "','" + UID + "','" + date + "')";
SqlCommand cmd = new SqlCommand(queryy, cnn);
SqlDataAdapter ad = new SqlDataAdapter(cmd);
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
}
}
gridview-image
Table name is 'employee' first i have 3 rows in gridview 'Name','id','address' when i insert new row 'ph' and click on 'update tabe' then i update all rows with 'ph'
db image
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
com = new SqlCommand("insert into student(sid,sname,smarks,saddress) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
If you insert new record at last row of gridview then get the index of last wow using:
Int32 index = dataGridveiw1.Rows.Count - 1;
For More You can refer this Article : Insert Data in Database Using GridView Control
EDIT:
You can use this approach to insert and update data with single query:
INSERT INTO student(sid, sname, smarks) VALUES('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "') ON DUPLICATE KEY UPDATE sname="g1.Cells[1].Text", smarks="g1.Cells[2].Text";

SQL Query Command not working but does not give error SQL Server

I am developing a database application in C#.NET and SQL Server 2012.
Some of my SQL statements are not working properly . When I execute the code it does not give any error. But when I try to delete something or Update a record, I does not do that. The code lies below:
public void updateFinalTable()
{
DialogResult result = MessageBox.Show("Please make sure no fields are empty or they will get changed. \n\t\t Do you want to continue?",
"Important Note",
MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE fianlTable SET AccountNumber='" + textBox1.Text + "', Date='" + dateTimePicker1.Value.ToString("MM/dd/yyyy") + "', CustomerName='" + textBox3.Text + "' , Debit='" + txtDebit.Text + "', Credit='" + txtCredit.Text + "', Balance='" + txtBalance.Text + "' WHERE Id LIKE '" + textBox4.Text + "' ", con);
cmd.ExecuteNonQuery();
this.fianlTableBindingSource.AddNew();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("select * from fianlTable WHERE (UserName LIKE '" + LoginSession.UserID + "')", con);
sda.Fill(dt);
dataGridView1.DataSource = dt;
refresh();
con.Close();
MessageBox.Show("Record Updated Successfully!");
catch (Exception)
{
MessageBox.Show("Record Could Not be updated...! ");
}
}
}
Similar is the case with delete operation . Both codes give no error but inside the database no change is observed.
You have used Like in your where condition instead of =. So your code should be like this -
SqlCommand cmd = new SqlCommand("UPDATE fianlTable SET AccountNumber='" + textBox1.Text + "', Date='" +
dateTimePicker1.Value.ToString("MM/dd/yyyy") + "', CustomerName='" +
textBox3.Text + "' , Debit='" + txtDebit.Text + "', Credit='" +
txtCredit.Text + "', Balance='" + txtBalance.Text +
"' WHERE Id = '" + textBox4.Text + "' ", con);
ATTENTION This type of query potentially lead to SQL Injection. You better go with parametrized queries, like this -
string qry = = "UPDATE fianlTable SET AccountNumber = #accnt, CustomerName = #cname Where ID = #id)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#accnt", textBox1.Text);
cmd.Parameters.AddWithValue("#cname", textBox3.Text);
cmd.Parameters.AddWithValue("#id", textBox4.Text);
cmd.ExecuteNonQuery();

Categories

Resources