How to update 2 tables in c# - c#

I have 2 tables
tbl_employer(Emp_num,Designation,Fname,Lname,Phone_no)
tbl_system_users(Emp_num,User_name,Password)
those two tables are filled by using one c# form(employer.cs).Only few employers have permission to access the system called system users. there are 2 text boxes for username and password in employer.cs. username and password text box should not null to save data to tbl_system_users and if both text boxes are null, it means they are only employers and not system users.
Emp_num of tbl_employer is auto increment field and a foreign key to tbl_system_users.
how can I update a employer detail?
public void update_employers(DTOUsers Users)
{
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "UPDATE tbl_employer SET Designation = '" + Users.Designation
+ "',,Employer_first_name = '" + Users.EmpFirstName + "',Employer_last_name = '"
+ Users.EmpLastName + "',, Phone_Num = '" + Users.PhoneNum + "' WHERE Emp_Num ='" + Users.EmpNum + "'";
con.Open();
cmd.ExecuteNonQuery();
if (Users.Password != "" && Users.UserName != "")
{
cmd.CommandText = "UPDATE tbl_system_users set User_name='" + Users.UserName + "',Password='" + Users.Password + "' where Emp_Num ='" + Users.EmpNum + "'";
cmd.ExecuteNonQuery();
}
con.Close();
in employer.cs
private void btn_update_Click(object sender, EventArgs e)
{
string emp_num = txt_emp_num.Text;
string designation = cmb_designation.Text;
string fname = txt_emp_fname.Text;
string lname = txt_emp_lname.Text;
string user_name = txt_user_name.Text;
string pw = txt_pw.Text;
string phno = txt_phn_num.Text;
DTOUsers emp = new DTOUsers();
emp.EmpNum = Convert.ToInt16(emp_num);
emp.Designation = designation;
emp.EmpFirstName = fname;
emp.EmpLastName = lname;
emp.UserName = user_name;
emp.Password = strh.Encrypt(pw);
emp.PhoneNum = phno;
dbh.update_employers(emp);
}

public void update_employers(DTOUsers Users)
{
bool firstStep = true;
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(con);
cmd.CommandText = "UPDATE tbl_employer SET Designation = #Designation,Employer_first_name = #EmpFirstName,Employer_last_name = #EmpLastName,Phone_Num = #PhoneNum WHERE Emp_Num = #PhoneNum";
//SqlDbType.VarChar Adjust according to the database values
cmd.Parameters.Add("#Designation", SqlDbType.VarChar, 30).Value = Users.Designation;
cmd.Parameters.Add("#EmpFirstName", SqlDbType.VarChar, 30).Value = Users.EmpFirstName;
cmd.Parameters.Add("#EmpLastName", SqlDbType.VarChar, 30).Value = Users.EmpLastName;
cmd.Parameters.Add("#PhoneNum", SqlDbType.VarChar, 30).Value = Users.PhoneNum;
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
firstStep = false;
}
if (firstStep)
{
if (!string.IsNullOrEmpty(Users.Password) && !string.IsNullOrEmpty(Users.UserName))
{
cmd = new SqlCommand(con);
cmd.CommandText = "UPDATE tbl_system_users set User_name = #UserName,Password = #Password where Emp_Num = #PhoneNum";
cmd.Parameters.Add("#UserName", SqlDbType.VarChar, 30).Value = Users.UserName;
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 30).Value = Users.Password;
cmd.Parameters.Add("#PhoneNum", SqlDbType.VarChar, 30).Value = Users.PhoneNum;
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
con.Close();
}
}
}
}

Related

Update SQL Server table columns with button click from gridview fields

I have a gridview that displays all the fields from my table.
My problem is that I need to update my SQL Server table when I click the save button (onclick) because I added a new field that generates a unique ID to every Item I have in my table. And It will add the generated id to the database table whenever I click the save button.
I have tried this
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text +
"' , [prno], [itemaname], [specification], [qty], [uomid], [expenseid],
[statusid], [userid], [inserteddate], [withquotation], [potempid] WHERE
idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
But I get an error
Here is my complete code:
public void SaveTogrdPOTemp()
{
SqlConnection ConnString = new SqlConnection(ConfigurationManager.ConnectionStrings["MUCS2.0ConnectionString"].ConnectionString);
string strSql = string.Empty;
pextid = "TPID";
using (SqlCommand cmd = new SqlCommand("SELECT * FROM GenIDGen WHERE extid = '" + pextid + "'"))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = ConnString;
ConnString.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
var extid = sdr["extid"].ToString().Trim();
var genID = sdr["generatedid"].ToString().Trim();
var gentr = sdr["generator"].ToString();
var potempoid = extid + genID;
ConnString.Close();
}
}
strSql = "UPDATE [dbo].[GenIDGen] SET [generator] = generator + 1
WHERE extid = '" + pextid + "' ";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
try
{
strSql = "UPDATE [dbo].[PRDetails] SET [buyerid] = '" + txtBuyerID.Text + "' WHERE idnum = '" + pridnum + "'";
SqlCommand UpdateCommand = new SqlCommand();
UpdateCommand = new SqlCommand(strSql, ConnString);
ConnString.Open();
UpdateCommand.ExecuteNonQuery();
ConnString.Close();
}
catch (Exception ex)
{
throw ex;
}
}
For the generating of ID and the updating of the gridview. Thank you!

How to do if/else statement for fileUpload

Heyy all. I am trying to do an if/else statement for my fileupload function on my Edit Profile page in my ASP.net webpage.
Here is my code:
protected void btnContinue_Click(object sender, EventArgs e)
{
//Declaration of variable to update Profile Image
string imageName, newContact;
imageName = FileUpload1.FileName.ToString();
newContact = tbMobile.Text.ToString();
username = (String)Session["NonAdmin"];
MySqlConnection mcon = new MySqlConnection("server=182.50.133.91;user id=Jonathan;password=jon123;persistsecurityinfo=True;database=ajactrac_;allowuservariables=True");
MySqlDataAdapter sda = new MySqlDataAdapter("select * from pointofcontact where Username = '" + username.ToString() + "'", mcon);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows.Count.ToString() == "1")
{
MySqlCommand command = mcon.CreateCommand();
MySqlCommand command1 = mcon.CreateCommand();
MySqlCommand command2 = mcon.CreateCommand();
MySqlCommand command3 = mcon.CreateCommand();
MySqlCommand command4 = mcon.CreateCommand();
MySqlCommand command5 = mcon.CreateCommand();
MySqlCommand command6 = mcon.CreateCommand();
MySqlCommand command7 = mcon.CreateCommand();
command.CommandText = "update pointofcontact set Password = ?pwd where Username = '" + username.ToString() + "'";
command1.CommandText = "update pointofcontact set FirstName = ?firstname where Username = '" + username.ToString() + "'";
command2.CommandText = "update pointofcontact set LastName = ?lastname where Username = '" + username.ToString() + "'";
command3.CommandText = "update pointofcontact set ContactNumber = ?contact where Username = '" + username.ToString() + "'";
command4.CommandText = "update pointofcontact set EmailAddress = ?email where Username = '" + username.ToString() + "'";
command5.CommandText = "update pointofcontact set Address = ?address where Username = '" + username.ToString() + "'";
command6.CommandText = "update pointofcontact set BackupContactNumber = ?backupnumber where Username = '" + username.ToString() + "'";
command7.CommandText = "update pointofcontact set ProfilePic = ?newimage where Username = '" + username.ToString() + "'";
mcon.Open();
if (tbNewPassword.Text == "")
{
command.Parameters.AddWithValue("?pwd", tbOldPassword.Text.Trim());
}
else
{
command.Parameters.AddWithValue("?pwd", tbNewPassword.Text.Trim());
}
if(tbNewFirstName.Text == "")
{
command1.Parameters.AddWithValue("?firstname", tbFirstName.Text.Trim());
}
else
{
command1.Parameters.AddWithValue("?firstname", tbNewFirstName.Text.Trim());
}
if(tbNewLastName.Text == "")
{
command2.Parameters.AddWithValue("?lastname", tbLastName.Text.Trim());
}
else
{
command2.Parameters.AddWithValue("?lastname", tbNewLastName.Text.Trim());
}
if(tbNewContact.Text == "")
{
command3.Parameters.AddWithValue("?contact", tbMobile.Text.Trim());
}
else
{
command3.Parameters.AddWithValue("?contact", tbNewContact.Text.Trim());
}
if(tbNewEmail.Text == "")
{
command4.Parameters.AddWithValue("?email", tbEmail.Text.Trim());
}
else
{
command4.Parameters.AddWithValue("?email", tbNewEmail.Text.Trim());
}
if(tbNewAddress.Text == "")
{
command5.Parameters.AddWithValue("?address", tbAddress.Text.Trim());
}
else
{
command5.Parameters.AddWithValue("?address", tbNewAddress.Text.Trim());
}
if(tbNewBackupContact.Text == "")
{
command6.Parameters.AddWithValue("?backupnumber", tbBackupContact.Text.Trim());
}
else
{
command6.Parameters.AddWithValue("?backupnumber", tbNewBackupContact.Text.Trim());
}
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + imageName);
command7.Parameters.AddWithValue("?newimage", imageName);
command.ExecuteNonQuery();
command1.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command4.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
command7.ExecuteNonQuery();
mcon.Close();
string javaScript = "<script language=JavaScript>\n" + "alert('Profile Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
else
{
string javaScript = "<script language=JavaScript>\n" + "alert('Some Error Occured! Profile Not Updated!');\n" + "</script>";
RegisterStartupScript("xyz", javaScript);
}
tbNewPassword.Text = "";
}
I had planned to use the if else statement for my fileupload function such that if the user has not uploaded a new picture, he/she would be still able to update their profile.
Currently when I try to edit a user's profile, this error message comes out.
Before uploading files to any directory, it is good to have this statement before saving file.
if (!Directory.Exists(Server.MapPath("~/Images")))
Directory.CreateDirectory("~/Images");
add above statement before this line
FileUpload1.PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Images", imageName)));

How to retrieve a data from a table and insert into another table?

I am trying to retrieve "customer_id" from Customer table and insert it into
fare_tariff(tariff_id, customer_id, total_price)
So I retrieve the customer_id from Customer table as below:
using (SqlCommand command = new SqlCommand("SELECT customer_id FROM Customer WHERE UserName = '" + username + "' Password = '"+password +"' ", connection))
{
string cust_id = customer_id.ToString();
SqlDataReader myReader = command.ExecuteReader();
if (myReader.Read())
{
cust_id = myReader["customer_id"].ToString();
}
int c_id = Convert.ToInt32(cust_id);
myReader.Close();
custID(c_id);
}
and insert the customer_id into table fare_tariff like below:
using (SqlCommand command = new SqlCommand("INSERT INTO flight_reservation(tariff_id, customer_id, total_price) VALUES(#val1,#val2,#val3)", connection))
{
command.Parameters.Add("#val1", SqlDbType.Int).Value = tariff_id;
command.Parameters.Add("#val2", SqlDbType.Int).Value = customer_id;
command.Parameters.Add("#val3", SqlDbType.VarChar).Value = total_price.ToString();
command.ExecuteNonQuery();
}
I declared customer_id as a variable for storing customer_id.
Problem is : tariff_id and total_price inserted successfully but the column customer_id is null yet.
Help needed.
Fetching data to the client and returning row by row back to the server
can well produce big overhead. There's better way to do the same,
so called "insert/select" query:
using (SqlCommand command = connection.CreateCommand()) {
command.CommandText =
"insert into Flight_Reservation(\n" +
" Customer_Id,\n" +
" Tariff_Id,\n" +
" Total_Price)\n" +
" select Customer_Id,\n" +
" #prm_Tariff_Id,\n" +
" #prm_Total_Price\n" +
" from Customer\n" +
" where (UserName = #prm_UserName)\n" +
" (Password = #prm_Password)";
command.Parameters.Add("#prm_Tariff_Id", SqlDbType.VarChar, 80).Value = tariff_id;
command.Parameters.Add("#prm_Total_Price", SqlDbType.VarChar, 80).Value = total_price.ToString();
command.Parameters.Add("#prm_UserName", SqlDbType.VarChar, 80).Value = username;
command.Parameters.Add("#prm_Password", SqlDbType.VarChar, 80).Value = password;
command.ExecuteNonQuery();
}

Update, Insert to sql .. There is already an open DataReader associated with

string[] stringList2 = new string[10];
if (VaildDataRow == true)
{
//Response.Write("<script>alert('2valid data row" + TbRow + "')</script>");
TbCol = 0;
TcCol = 1;
foreach (TableCell tc in tr.Cells)
{
#region //Load array with valid row text boxes' value
foreach (Control c1 in tc.Controls)
{
if (c1 is TextBox)
{
if (c1.ID.StartsWith("DataTbFld_"))
{
TextBox txt = (TextBox)t11.FindControl(c1.ID);
if (string.IsNullOrEmpty(txt.Text))
{
//Response.Write("<script>alert('txt#id ..not hidden..: " + txt.ID + " found data in textbox, rec is valid , will break')</script>");
txt.Text="Null";
}
stringList2[TbCol] = txt.Text.ToString();
//Response.Write("<script>alert('TbRow : " + TbRow + " TcCol : " + TcCol + " TbCol : " + TbCol + " txt.Text.ToString() : " + txt.Text.ToString() + "')</script>");
}
TbCol += 1;
}
}
#endregion//===
TcCol += 1;
}
Response.Write("<script>alert('TbRow : " + TbRow + "')</script>");
#region //if exist update else insert
Response.Write("<script>alert('InputDate = " + stringList2[6] +
" and Dept= " + stringList2[7] + " and DeptType= " + stringList2[8] +
" and DeptSubType= " + stringList2[9] + "')</script>");
con.Open();
cmd = new SqlCommand("SELECT * FROM MainDailyData WHERE Dept= '" + stringList2[7] + "' and DeptType = '" + stringList2[8] + "' and DeptSubType= '" + stringList2[9] + "'", con);
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
{
Response.Write("<script>alert('Found,Update')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.UpdateCommand = new SqlCommand("UPDATE MainDailyData SET Product1 = #Prod1, Product2 = #Prod2, Product3 = #Prod3, Product4 = #Prod4, Product5 = #Prod5, Product6 = #Prod6, InputDate = #InDate, Dept = #Dpt, DeptType = #DptType, DeptSubType = #DptSubType", con);
myda.UpdateCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.UpdateCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.UpdateCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.UpdateCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.UpdateCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.UpdateCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.UpdateCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.UpdateCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.UpdateCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.UpdateCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
//dr.Close();
//con.Open();
myda.UpdateCommand.ExecuteNonQuery();
}
else
{
Response.Write("<script>alert('not Found,Insert')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.InsertCommand = new SqlCommand("INSERT INTO MainDailyData (Product1,Product2,Product3,Product4,Product5,Product6,InputDate,Dept,DeptType,DeptSubType) VALUES(#Prod1,#Prod2,#Prod3,#Prod4,#Prod5,#Prod6,#InDate,#Dpt,#DptType,#DptSubType)", con);
myda.InsertCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.InsertCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.InsertCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.InsertCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.InsertCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.InsertCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.InsertCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.InsertCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.InsertCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.InsertCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
//dr.Close();
//con.Open();
myda.InsertCommand.ExecuteNonQuery();
}
con.Close();
#endregion
}
#endregion
TbRow += 1;
}
when excauting
myda.InsertCommand.ExecuteNonQuery();
or
myda.UpdateCommand.ExecuteNonQuery();
i got error msg
There is already an open DataReader associated with this Command which must be closed first
if I close dr the result will be messy. If it found record in row 2 of the table, it will insert record of row 1 from the table to the database
i tried to enable MultipleActiveResultSets="true", but i got a problem attribute is not allowed!
I want to check if record exist, update else ,insert. how to achieve this or how to correct my code?
after edition:
#region //if exist update else insert inserting code
//Response.Write("<script>alert('InputDate = " + stringList2[6] +
//" and Dept= " + stringList2[7] + " and DeptType= " + stringList2[8] +
//" and DeptSubType= " + stringList2[9] + "')</script>");
con.Open();
//cmd = new SqlCommand("SELECT 1 FROM MainDailyData WHERE Dept= '" + stringList2[7] +
// "' and DeptType = '" + stringList2[8] + "' and DeptSubType= '" + stringList2[9] + "'", con);
cmd = new SqlCommand("SELECT 1 FROM MainDailyData WHERE Dept= #dpt and DeptType = #dptType and DeptSubType= #DptSbType", con);
cmd.Parameters.AddWithValue("#dpt", stringList2[7]);
cmd.Parameters.AddWithValue("#dptType", stringList2[8]);
cmd.Parameters.AddWithValue("#DptSbType", stringList2[9]);
bool fRecordExists = false;
SqlDataReader dr = cmd.ExecuteReader();
//SqlDataReader dr = cmd.ExecuteScalar();
if (dr != null && dr.HasRows)
{
fRecordExists = true;
}
dr.Close();
dr.Dispose();
if (fRecordExists)
{
Response.Write("<script>alert('Found,Update')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.UpdateCommand = new SqlCommand("UPDATE MainDailyData SET Product1 = #Prod1, Product2 = #Prod2, Product3 = #Prod3, Product4 = #Prod4, Product5 = #Prod5, Product6 = #Prod6, InputDate = #InDate, Dept = #Dpt, DeptType = #DptType, DeptSubType = #DptSubType", con);
myda.UpdateCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.UpdateCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.UpdateCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.UpdateCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.UpdateCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.UpdateCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.UpdateCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.UpdateCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.UpdateCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.UpdateCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
myda.UpdateCommand.ExecuteNonQuery();
}
else
{
Response.Write("<script>alert('not Found,Insert')</script>");
SqlDataAdapter myda = new SqlDataAdapter();
myda.InsertCommand = new SqlCommand("INSERT INTO MainDailyData (Product1,Product2,Product3,Product4,Product5,Product6,InputDate,Dept,DeptType,DeptSubType) VALUES(#Prod1,#Prod2,#Prod3,#Prod4,#Prod5,#Prod6,#InDate,#Dpt,#DptType,#DptSubType)", con);
myda.InsertCommand.Parameters.Add("#Prod1", SqlDbType.VarChar).Value = stringList2[0];
myda.InsertCommand.Parameters.Add("#Prod2", SqlDbType.VarChar).Value = stringList2[1];
myda.InsertCommand.Parameters.Add("#Prod3", SqlDbType.VarChar).Value = stringList2[2];
myda.InsertCommand.Parameters.Add("#Prod4", SqlDbType.VarChar).Value = stringList2[3];
myda.InsertCommand.Parameters.Add("#Prod5", SqlDbType.VarChar).Value = stringList2[4];
myda.InsertCommand.Parameters.Add("#Prod6", SqlDbType.VarChar).Value = stringList2[5];
myda.InsertCommand.Parameters.Add("#InDate", SqlDbType.VarChar).Value = stringList2[6];
myda.InsertCommand.Parameters.Add("#Dpt", SqlDbType.VarChar).Value = stringList2[7];
myda.InsertCommand.Parameters.Add("#DptType", SqlDbType.VarChar).Value = stringList2[8];
myda.InsertCommand.Parameters.Add("#DptSubType", SqlDbType.VarChar).Value = stringList2[9];
myda.InsertCommand.ExecuteNonQuery();
}
con.Close();
#endregion
still the problem exist for updating or inserting the second row, if i fill 1st first record and leave the second empty, it will insert it to the db but will not eccept any inserting later to the second row, instead it will duplicate the 1st row record. interchangablly, for if i fill the the second row first. if i fill both if them # the begining it will insert them both but will not recognize the second record and will duplicate the first record?
Just close the dr immediately after you determine whether or not it has any results; you aren't using it for anything other than determining if the record exists or not, so this won't affect your logic at all.
Replace:
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
with:
bool fRecordExists = false;
dr = cmd.ExecuteReader();
if (dr != null && dr.HasRows)
{
fRecordExists = true;
}
dr.Close();
if (fRecordExists)
You should also change the select statement to a parameterized query to prevent SQL injection attacks and exceptions due to unexpected characters in the data.
Also, the select statement, if it isn't going to be used for anything other than existence verification, should just do SELECT 1 instead of SELECT * to prevent unneeded processing in both the database and application.
Finally, if your application data supports it (i.e. the select criteria will only select 1 record at the max), I would suggest using ExecuteScalar instead of ExecuteReader, which would eliminate your problem altogether.

How to achieve a search for a certain year & amount using C#

Here is a small demo of a SQL database, where one can add, update delete members from a SQL server.
There are two tables in a single SQL Server DB, one is “members” second is “overview”.
In members there is distinct ID column and members personal info like name, address telephone etc.
In overview there are only three columns which are dID, year & amount.
There is one single windows form, language is c# and project is built in Visual Studio 2010, and of course data base in SQL Server 2010.
The windows form has a “reset, insert, update & delete” buttons.
There is one more button besides the dID text box where a distinct ID can be inserted and after clicking Search button the last entry made about the member shows by filling all the text boxes where name address telephone appear. This serves the function that member full info can be seen and changes can be made or can be removed from dB.
There are two text boxes in particular, which are Year & Amount, which shows that the member has paid a certain amount for the certain year.
But as I mentioned in the text boxes you can only see the last entry made. What function I want to achieve is that after inserting dID of person x I could only in the year text box able to insert lets say any previous year and the press search which should like normally fill all the text boxes with info, and in the amount text box should show me the entry from the dB that according to the year I entered how much amount is there or there is nothing which means that may be member has not paid for a certain year.
I need help in achieving this logic programmatically therefore I would like to request assistance.
The present program is as follows :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SQLDatabase
{
public partial class SQLDBDisplay : Form
{
SqlConnection con = new SqlConnection("Data Source=JG-PC\\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=True");
public SQLDBDisplay()
{
InitializeComponent();
}
SqlDataAdapter da;
DataSet ds = new DataSet();
private void btnSearch_Click(object sender, EventArgs e)
{
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
try
{
string sql = "SELECT * FROM members where dID = '" + txtdID.Text + "' ";
txtYear.Text = sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
sql = "SELECT * FROM Overview where dID = '" + txtdID.Text + "' ";
txtYear.Text = txtYear.Text + " : " + sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtYear.Text = reader["Year"].ToString();
txtAmount.Text = reader["Amount"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnReset_Click(object sender, EventArgs e)
{
txtdID.Text = ""; txtName.Text = ""; txtAddress.Text = "";
txtMobile.Text = ""; txtEmail.Text = ""; txtYear.Text = "";
txtAmount.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO members (dID, Name, Address, Email, Mobile) VALUES ( '" + txtdID.Text+ "','" + txtName.Text + "','"
+ txtAddress.Text + "', '" + txtEmail.Text + "', '" + txtMobile.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Overview (dID, Year, Amount) VALUES ('"+ txtdID.Text +"' ,'" + txtYear.Text + "','" + txtAmount.Text +
"')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Scuessfully!!!");
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "Update members set Name = '" + txtName.Text + "', Address = '" + txtAddress.Text + "', Email = '" +
txtEmail.Text + "', Mobile = '" + txtMobile.Text + "' WHERE dID = '"
+ txtdID.Text + "'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "Update overview set Year = '" + txtYear.Text + "', Amount = '" + txtAmount.Text + "' WHERE dID = '"+ txtdID.Text+"'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data Scuessfully Updated");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM members WHERE dID = '"+ txtdID.Text +"'";
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "DELETE FROM overview WHERE dID = '" + txtdID.Text + "'";
cmd.ExecuteNonQuery();
da = new SqlDataAdapter(cmd);
MessageBox.Show("Record Scuessfully Deleted !");
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
} }
To add a solution to the comments people have made regarding parameters and sql injection, i tend to use the code below when connecting to any database.
using(SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
try
{
using(SqlCommand command = new SqlCommand())
{
command.CommandText = "SELECT * FROM members where dID = #MyId";
command.Connection = connection;
// Set the SqlDbType to your corresponding type
command.Parameters.Add("#MyId", SqlDbType.VarChar).Value = txtdID.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
}
}
finally
{
connection.Close();
}
}
You need to group your SELECT on the Amount column. A simple answer to your question would be to modify your second select query like this:
sql = "SELECT Year, dID, SUM(Amount) as Amount FROM Overview where dID = '" + txtdID.Text + "' AND Year = " + txtYear.Text + "GROUP BY amount";
Probably, you would like to use the txtYear.Text value for an SQL parameter, so:
txtYear.Text = sql;
and
txtYear.Text = txtYear.Text + " : " + sql;
don't make too much sense in your code.
Of course, this is not the correct way, as it is prone to SQL Injection. I would recommend you to use SQL Stored Procedures, which are definitely safer regarding SQL Injection.
Another improvement to the code quality would be that you should use using statements to enclose the SQLConnection, SQLCommand and SQLDataReader objects initializations.

Categories

Resources