Updating 2 rows in SQL database with one query string "UPDATE" - c#

I need to figure out how to update the two rows in my database but cnt get my query string correct..
Here is the code that I am using. If you could provide me with a query string that would be great..
string birdnametextupdate = birdsnametext.Text;
string birdnamedetailsupdate = birdnamedetails.Text;
int row = int.Parse(Request.QueryString["PhotoID"]);
string query = "UPDATE Photos Set PhotoName = #PhotoNewName Set Deatils = #DetailsNew WHERE PhotoID = #PhotoID";
SqlCommand myCommand = new SqlCommand(query, myConnection);
//create parameterised object
myCommand.Parameters.AddWithValue("#PhotoNewName", birdnametextupdate);
myCommand.Parameters.AddWithValue("#DetailsNew", birdnamedetailsupdate);
myCommand.Parameters.AddWithValue("#PhotoID", row);
myCommand.ExecuteNonQuery();

try this
string query = "UPDATE Photos Set PhotoName = '#PhotoNewName' ,Details = '#DetailsNew' WHERE PhotoID = '#PhotoID'";
I saw error in your query, do not duplicate set. just use comma instead

int photoId = int.Parse(Request.QueryString["PhotoID"]);
string query = "UPDATE Photos SET PhotoName = #PhotoNewName, Details = #DetailsNew WHERE PhotoID = #PhotoID";
using(var cmd = new SqlCommand(query, myConnection))
{
cmd.Parameters.Add("#PhotoNewName").Value = birdsnametext.Text;
cmd.Parameters.Add("#DetailsNew").Value = birdnamedetails.Text;
cmd.Parameters.Add("#PhotoID").Value = photoId;
cmd.ExecuteNonQuery();
}
The Sql syntax is:
https://msdn.microsoft.com/en-us/library/ms177523.aspx
A simple example is:
UPDATE <tableName>
SET
<Column1> = <newColumn1Value>
,<Column2> = <newColumn2Value>
WHERE <condition>

Related

Update query C# SQL server radio button

This update query isn't working when clicking the button. Here Group is the radio button but the program is throwing an excption
private void editAll_Click(object sender, EventArgs e)
{
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DELL\source\repos\phoneBookwin\phoneBookwin\Database1.mdf;Integrated Security=True";
string value;
bool friendCheck = newFriends.Checked;
bool familyCheck = newFamily.Checked;
bool emergencyCheck = newEmergency.Checked;
bool collCheck = newColl.Checked;
if (friendCheck)
value = newFriends.Text;
else if (familyCheck)
value = newFamily.Text;
else if (emergencyCheck)
value = newEmergency.Text;
else if (collCheck)
value = newColl.Text;
else
value = "";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand Command = con.CreateCommand())
{
con.Open();
Command.CommandText = " update Contacts set Name =#newName, Contacts = #newNumber, Email = #newEmail, Group = #newGroup where Name = #changeName";
Command.Parameters.AddWithValue("#newName",newName.Text);
Command.Parameters.AddWithValue("#newNumber", newNumber.Text);
Command.Parameters.AddWithValue("#newEmail", newEmail.Text);
Command.Parameters.AddWithValue("#newGroup", value);
Command.Parameters.AddWithValue("#changeName", changeName.Text);
Command.ExecuteNonQuery();
con.Close();
}
this.Hide();
Form1 save = new Form1();
save.ShowDialog();
}
Exception thrown
'Incorrect syntax near the keyword 'Group'.'
Wrap keyword "Group" with square brackets in your SQL query:
update Contacts
set Name =#newName, Contacts = #newNumber, Email = #newEmail, [Group] = #newGroup
where Name = #changeName
As I already wrote in my comment here, first you should use square brackets for the keyword group
Command.CommandText = " update Contacts set [Group] = #newGroup, Name =#newName, Contacts = #newNumber, Email = #newEmail where Name = #changeName";
Second, avoid AddWithValue is has some problems as explained here
replace
Command.Parameters.Add(new AddWithValue("#newName",newName.Text);
with this
command.Parameters.Add(new SqlParameter("#newName", SqlDbType.VarChar)
{ Value = (newName.Text == "") ? (object)DBNull.Value : newName.Text });

passing columnname with a parameter SQLcommand

I've been googling something I dont really cant understand.
In short my problem is this;
When using this;
String sYear2 = "2020";
string query = #"Select decJan from Stats where intRecnum = (select intRecnum from Stats where intAr = #year)";
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#year", sYear2);
The result is returning "111" (which is correct vaule of column decJan the year 2020.
But when trying this;
String sYear2 = "2020";
String sColumn2 = "decJan";
string query = #"Select " + #column + #" from tbFuGraddagar where intRecnum = (select intRecnum from tbfuGraddagar where intAr = #year)";
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#year", sYear2);
cmd.Parameters.AddWithValue("#column", sColumn2);
I recieve "decJan" as result.
When googling all I have found that its not possible without dynamic SQL or that is bad design.
But I fail to understand what the diffrence is...all I want is to change the static code with a value similar to #year-parameter. the "interpretation" shouldn't care about the validation of SQL-syntax, it's just a matter och string-manipulation.
Or is it just me beeing a bad C#-coder?
Probably addwithvalue method is not valid for adding dynamic column names in select statements. I think you should use c# 8.0 feature, string interpolation to solve this problem.  You can add column names with string interpolation. Can you try this approach :
String sYear2 = "2020";
string deccan = "decJan";
string query = $(Select {decJan} from Stats where intRecnum = (select intRecnum from Stats where intAr = #year)
query = #query;
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#year", sYear2);

How to get selected ID from SQL database using textBox and update information?

I am trying to update a databse entry under a specific id in my table when the users enter their ID number in a textBox.
At the moment it updates but updates all entries in my table except the entry containing the users ID number.
This is the code I am currently using:
private void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123");
SqlCommand check_User_Name = new SqlCommand("SELECT Id FROM NewVisitor WHERE (IDNumber = #IDNumber)", con);
check_User_Name.Parameters.AddWithValue("#IDNumber", idNumber_TxtBox.Text);
con.Open();
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
var connetionString = #"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123";
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer";
try
{
using (var connection = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#PersonVisit", SqlDbType.NVarChar).Value = personVisiting_TxtBox.Text;
command.Parameters.Add("#PurposeVisit", SqlDbType.NVarChar).Value = purposeOfVisit_CMBox.SelectedItem;
command.Parameters.Add("#Duration", SqlDbType.Date).Value = duration_dateTimePicker1.Value.Date;
command.Parameters.Add("#Disclaimer", SqlDbType.NVarChar).Value = disclaimer_CHKBox.Checked;
connection.Open();
command.ExecuteNonQuery();
}
}
}
The whole table has many more fields but would like to just update the above fields within that specific ID.
Thanks
You forgot the WHERE clause on the UPDATE statement, telling it specifically which records to update. It sounds like you just want to add the exact same WHERE clause that you have on your SELECT:
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer WHERE (IDNumber = #IDNumber)";
And don't forget to add the paramter for it:
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber_TxtBox.Text;
You may need to convert the input value to an integer first, I'm not 100% certain (it's been a while since I've had to use ADO.NET directly). Something like this:
if (!int.TryParse(idNumber_TxtBox.Text, out var idNumber))
{
// input wasn't an integer, handle the error
}
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber;

ASP.NET Multiple Queries not executing within a loop

I am trying to run multiple queries within a loop. The first query runs ok as I can see it when I step through the code.
However the second query (which is within a loop) is supposed to run depending on the value held from the first. When the loop runs based on that value it seems to be ignoring the query. I put a label to display in place of the query and it displayed so I believe how I have opened/closed my connection is not correct.
c# code:
protected void Page_Load(object sender, EventArgs e)
{
// Get the session of the user
string staffid = Session["StaffId"].ToString();
//Proxy on page load to check IsActive Status
string DefaultConnection = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection = new SqlConnection(DefaultConnection);
myConnection.Open();
//select the userdetail specific to the logged in user using parameterisation
string query = "SELECT ProxyStatus.ProxyStatusId, ProxyStatus.FunctionId, ProxyStatus.StartDate, ProxyStatus.EndDate, ProxyStatus.IsActive FROM ProxyStatus INNER JOIN Staff ON Staff.StaffId = ProxyStatus.Proxee WHERE (Staff.StaffId = #StaffId)";
DateTime thisDay = DateTime.Today;
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("#staffid", staffid);
SqlDataReader rdr = myCommand.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
Session["StartDate"] = rdr["StartDate"].ToString();
Session["EndDate"] = rdr["EndDate"].ToString();
Session["ProxyStatusId"] = rdr["ProxyStatusId"].ToString();
Session["FunctionId"] = rdr["FunctionId"].ToString();
// Get the session of StartDate and endate, use the session value in a query to compare against the current date
string startdate = Session["StartDate"].ToString();
string enddate = Session["EndDate"].ToString();
string proxystatus = Session["ProxyStatusId"].ToString();
DateTime startdatedata = Convert.ToDateTime(startdate);
DateTime enddatedata = Convert.ToDateTime(enddate);
if (startdatedata > thisDay)
{
string DefaultConnection2 = WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection myConnection2 = new SqlConnection(DefaultConnection2);
myConnection2.Open();
string query2 = "UPDATE ProxyStatus SET ProxyStatus.IsActive = 'False' WHERE ProxyStatus.ProxyStatusId = #proxystatus";
myCommand.Parameters.AddWithValue("#newproxystatus", proxystatusnew);
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
}
}
}
else
{
rdr.Close();
}
}
}
}
Shouldn't the lines be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand.ExecuteNonQuery();
be
SqlCommand myCommand2 = new SqlCommand(query2, myConnection2);
myCommand2.ExecuteNonQuery();
instead? The first "myCommand" will still be in use with "rdr".

SqlDataReader not reading any row apart from first

New to stackoverflow and very much a c# beginner
Currently creating a form which produces a bar chart from data stored in a database. The chosen record is identified by pID (patient's ID) and tdate (Test date). These values are determined by 2 combo boxes that the user can select from, The problem I am having is that only the first and last records stored in the database are populating the barchart.
if (radioButtonTestResult.Checked)
{
foreach (var series in TestResultBarChart.Series)
{
series.Points.Clear();
}
string tdate = comboBox2.Text;
using (SqlConnection connection = new SqlConnection(#"Data Source= (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\MMSEDB.mdf;Integrated Security=True"))
{
connection.Open();
string sql = "SELECT T_CLOCK_SCORE,T_LANGUAGE_SCORE,T_RECALL_SCORE,T_REGISTRATION_SCORE,T_ORIENTATION _SCORE,T_TIME FROM TEST_RESULTS WHERE P_ID='" + pID + "' AND T_DATE='"+ tdate +"'";
using(SqlCommand command = new SqlCommand(sql, connection))
{
command.CommandTimeout = 3600;
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
MessageBox.Show("hello4");
String clockScoreString = reader["T_CLOCK_SCORE"].ToString();
MessageBox.Show(clockScoreString);
clockScore = Int32.Parse(clockScoreString);
String langScoreString = reader["T_LANGUAGE_SCORE"].ToString();
langScore = Int32.Parse(langScoreString);
String recallScoreString = reader["T_RECALL_SCORE"].ToString();
recallScore = Int32.Parse(recallScoreString);
String regScoreString = reader["T_REGISTRATION_SCORE"].ToString();
regScore = Int32.Parse(regScoreString);
String orientScoreString = reader["T_ORIENTATION_SCORE"].ToString();
orientScore = Int32.Parse(orientScoreString);
String timeScoreString = reader["T_TIME"].ToString();
timeScore = Int32.Parse(timeScoreString);
}
reader.Close();
}
}
this.TestResultBarChart.Series["Series1"].Points.AddXY("Clock Score", clockScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Language Score", langScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Recall Score", recallScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Registration Score", regScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Orientation Score", orientScore);
}
}
Here is a pic of the data:
Test_results_table
here is a pic of the interface with the first record working:
interface
I know this has something to do with the reader but can't work out how to get to function correctly
Any help is very much appreciated
You are reading in a loop all the returned values, then exit from the loop and use just the last value to set your Points. You should move the Point settings inside the loop
....
while (reader.Read())
{
clockScore = Convert.ToInt32(reader["T_CLOCK_SCORE"]);
langScore = Convert.ToInt32(reader["T_LANGUAGE_SCORE"]);
recallScore = Convert.ToInt32(reader["T_RECALL_SCORE"]);
regScore = Convert.ToInt32(reader["T_REGISTRATION_SCORE"]);
orientScore = Convert.ToInt32(reader["T_ORIENTATION_SCORE"]);
timeScore = Convert.ToInt32(reader["T_TIME"]);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Clock Score", clockScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Language Score", langScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Recall Score", recallScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Registration Score", regScore);
this.TestResultBarChart.Series["Series1"].Points.AddXY("Orientation Score", orientScore);
}
reader.Close();
Note that your query is built using string concatenation. This is a well known problem with database code. Never do it and use a parameterized query
EDIT
Looking at your comment below, I repeat the advice to use a parameterized query instead of string concatenation. Not only this avoid Sql Injection hacks but also you don't leave the job to understand the meaning of your values to the database engine
DateTime tDate = Convert.ToDateTime(comboBox2.Text);
......
string sql = #"SELECT
T_CLOCK_SCORE,T_LANGUAGE_SCORE,T_RECALL_SCORE,
T_REGISTRATION_SCORE,T_ORIENTATION_SCORE,T_TIME
FROM TEST_RESULTS
WHERE P_ID=#id AND T_DATE=#date";
using(SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#id", SqlDbType.Int).Value = pID;
command.Parameters.Add("#date", SqlDbType.Date).Value = tdate;
command.CommandTimeout = 3600;
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
....
In this example I assume that the variable pID is of type integer and the variable tDate is of type DateTime matching the type of the database fields. This doesn't leave any doubt to the database engine on your values.
Of course if the fields are of different type then you should change the SqlDbType accordingly.

Categories