SQL Update not actually updating? Done - c#

SOLVED: I figured out my own issue. It was working as I thought. I just was not reading the correct row.
I am trying to update a few columns in a row, in the Table [Profiles]. I don't get any errors when running this code but it doesn't actually update the columns. I have never used an update before. What am I doing wrong.
string currentPage = Request.Url.ToString();
Uri myUri = new Uri(currentPage);
string position = HttpUtility.ParseQueryString(myUri.Query).Get("position");
string electionYear = HttpUtility.ParseQueryString(myUri.Query).Get("year");
var finalkey = Session["Userid"].ToString() + "^" + position + "^" + electionYear;
string sqlquery = "UPDATE [Profiles] SET Qualifications=#Qualifications, Platform=#Platform, FamilyLife=#FamilyLife, Website=#Website where FinalKey=#FinalKey";
SqlConnection conn = new SqlConnection(dbLocation);
SqlCommand comm = new SqlCommand(sqlquery, conn);
try
{
conn.Open();
comm.Parameters.AddWithValue("#FinalKey", finalkey);
comm.Parameters.AddWithValue("#Qualifications", qualificationsBox.Text);
comm.Parameters.AddWithValue("#Platform", platformBox.Text);
comm.Parameters.AddWithValue("#FamilyLife", familyBox.Text);
comm.Parameters.AddWithValue("#Website", candWebsiteBox.Text);
comm.ExecuteNonQuery();
}
catch { }
conn.Close()

Please refer the value of finalkey by set break Point ! Only Possible for Not Updating is,
There is no matching record found with this finalkey value.
another option
set where class value manually Like where finalvalue="user1dec" and check if it is work, then u can........
var finalkey = Session["Userid"].ToString() + "^" + position + "^" + electionYear;

Related

Mysql update query works without using parameters but doesn't when using them

Good day,
In c#, I am trying to run a MySQL update query to update one record, based on its id. Everything goes well as long as I'm not using parameters.
I'm experiencing the issue once I am adding one or several parameters. I have made the test with only one parameter and same problem here.
What am I missing here ?
Thank you very much for your help.
public static void editCustomerTest(ClsCustomerTest pTest)
{
MySqlConnection l_Connection = null;
string l_SpName = string.Empty;
MySqlCommand l_MyCommand = null;
try
{
l_Connection = ClsIconEnv.getDataAccess().MySqlConnection;
ClsDataAccess.OpenConnection(l_Connection);
l_SpName = "update tbTestCustomers " +
"set sName = '#sLastName', " +
"sFirstName = '#sFirstName', " +
"sAddress = '#sAddress' " +
"Where id = #id);";
l_MyCommand = new MySqlCommand(l_SpName, l_Connection);
l_MyCommand.Parameters.Add("#sLastName", pTest.Last_Name);
l_MyCommand.Parameters.Add("#sFirstName", pTest.First_name);
l_MyCommand.Parameters.Add("#sAddress", pTest.Address);
l_MyCommand.Parameters.Add("#id", pTest.id);
l_MyCommand.ExecuteNonQuery(); // <----- This is the line at which the execution stops
ClsDataAccess.CloseConnection(l_Connection);
}
catch (Exception exc)
{
ClsIconErrorManager.manageException(exc);
}
finally
{
}
}
You do not need to wrap your params into the string and you have to use AddWithValue instead of Add if you don't want to explicitly specify the type, like this
l_SpName = "update tbTestCustomers " +
"set sName = #sLastName, " +
"sFirstName = #sFirstName, " +
"sAddress = #sAddress" +
"Where id = #id);";
l_MyCommand.Parameters.AddWithValue("#sLastName", pTest.Last_Name);
l_MyCommand.Parameters.AddWithValue("#sFirstName", pTest.First_name);
l_MyCommand.Parameters.AddWithValue("#sAddress", pTest.Address);
l_MyCommand.Parameters.AddWithValue("#id", pTest.id);
Like this:
l_SpName = #"update tbTestCustomers
set sName = #sLastName,
sFirstName = #sFirstName,
sAddress = #sAddress
Where id = #id";
l_MyCommand = new MySqlCommand(l_SpName, l_Connection);
l_MyCommand.Parameters.AddWithValue("#sLastName", pTest.Last_Name);
l_MyCommand.Parameters.AddWithValue("#sFirstName", pTest.First_name);
l_MyCommand.Parameters.AddWithValue("#sAddress", pTest.Address);
l_MyCommand.Parameters.AddWithValue("#id", pTest.id);
l_MyCommand.ExecuteNonQuery();

Need Millisecond Accuracy in DateTime in DetailsView c# How to Access Data directly in Details View?

So I have been browsing stack overflow and MSDN and cannot find a control (or make sense of the ones I have) to access the data directly of a detailsview. I'm in C# using a .Net WebApplication.
I think what I am looking for is the equivalent in gridview is row.Cells[1].Value can anybody help with the accessor to the DetailsView cells?
What I am trying to do is to access the exact data values I have bound to the DetailsView1
.Text is sufficient for all the numbers and string (only two shown for example) but not for the timestamp MTTS (a datetime) as it lost the milliseconds and the code (SQL query) I use after it cannot find the correct values in the db without the milliseconds. Will I also need to change the way I have bound the data, or some setting to give the bound data millisecond accuracy?
Code example:
Decimal RUN_ID = 0;
DateTime MTTS = new DateTime();
foreach(DetailsViewRow row in DetailsView1.Rows)
{
switch(row.Cells[0].Text)
{
case "RUN_ID":
RUN_ID = Decimal.Parse(row.Cells[1].Text);
break;
case "MTTS":
MTTS = DateTime.Parse(row.Cells[1].ToString());
break;
}
}
I have tried
row.Cells[1].ID = "MTTS";
MTTS = (DateTime)((DataRowView)DetailsView1.DataItem)["MTTS"];
But it does not recognize the MTTS and I am not sure how to set the parameter I have tried a few different things already with no success.
The workaround was messy, essentially I rebuilt the query that gathered the data to the GridView and then I made a function to grab the MTTS directly using LinQ and the parameteres from inside the GridView which assigns the MTTS as a DateTime.
This was in my opinion a bad way of doing things but it worked. I would prefer a better solution.
MTTS = GetMTTS(JOB_PLAN, JOB_NAME,JOB_NAME_ID,RUN_ID,JOB_STATUS);
public DateTime GetMTTS(string JOB_PLAN, string JOB_NAME, string JOB_NAME_ID, Decimal RUN_ID, string JOB_STATUS){
string myEnvName = XXX;
TableName = XXX.ToString();
ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[myEnvName].ToString();
string thisRUN_ID = RUN_ID.ToString();
cmdText = #"SELECT MTTS FROM " + TableName +
" WHERE JOB_PLAN = '" + JOB_PLAN + "'"
+ " AND JOB_NAME = '" + JOB_NAME + "'"
+ " AND JOB_NAME_ID = '" + JOB_NAME_ID + "'"
+ " AND RUN_ID = '" + thisRUN_ID + "'"
+ " AND JOB_STATUS = '" + JOB_STATUS + "'";
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
try
{
SqlCommand SQLcc = new SqlCommand(cmdText,conn);
SqlDataReader reader;
reader = SQLcc.ExecuteReader();
while (reader.Read())
{
MTTS = reader.GetDateTime(0);
}
reader.Dispose();
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
return MTTS;
}

Special Character does not displays in gridview from SQL database with Parameter

Well I have tried all you people suggested but the problem remain same
let me tell you in brief:
Form Name : ​AuzineForum.aspx
Has 1 GridView which displays all the field from the database using ​ select * from QF
its working good , index is also working , the gridView Has Button and onClick I open new Form ​AuzineForumAnswer.aspx​ ..OK
I want to pick one record from ​AuzineForum.aspx​ and display on AuzineForumAnswer.aspx as well as it happens here in http://stackoverflow.com (we click on threads then the new page opens which has the question and answer on which we clicked previous) ...ok
so On AuzineForum.aspx's Button the code is
Button lb = (Button)sender;
GridViewRow row = (GridViewRow)lb.NamingContainer;
if (row != null)
{
int index = row.RowIndex; //gets the row index selected
Label AID1 = (Label)ForumQuesView.Rows[index].FindControl("AID1");
Label AID2 = (Label)ForumQuesView.Rows[index].FindControl("AID2");
Label AID3 = (Label)ForumQuesView.Rows[index].FindControl("AID3");
HyperLink Question = (HyperLink)ForumQuesView.Rows[index].FindControl("Question");
Label Questiontags = (Label)ForumQuesView.Rows[index].FindControl("Questiontags");
Label Askedby = (Label)ForumQuesView.Rows[index].FindControl("Askedby");
Response.Redirect(String.Format("AuzineForumAnswer.aspx?Question=" + Question.Text + "&Questiontags=" + Questiontags.Text + "&Askedby=" + Askedby.Text + "&AID1=" + AID1.Text + "&AID2=" + AID2.Text + "&AID3=" + AID3.Text, Server.UrlEncode(Question.Text), Server.UrlEncode(Questiontags.Text), Server.UrlEncode(Askedby.Text), Server.UrlEncode(AID1.Text), Server.UrlEncode(AID2.Text), Server.UrlEncode(AID3.Text)));
I had passes so many many parameter becuase of accuracy......
Now when I run it and click on the button so its open ​AuzineForumAnswer.AuzineForumAnswerand shows that record very well but problem occurs when the qtags field has "#" type of data like here tags( ​C#, GridView, etc) so, ​ when the tags field has the data includin "#" chracter then it gives "​Object refrence not set to Instance of an object " and if the qtags has normal data like ( specialcharacter gridview sql C ) then it open AuzineForumAnswer.​aspx​ and show data without error
the code behind of AuzineForumAnswer.aspx is below
protected void GetAllData()
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
using (SqlConnection sqlconn = new SqlConnection(connection))
{
using (SqlCommand sqlcomm = sqlconn.CreateCommand())
{
sqlcomm.CommandText = "Select * From QF where Question='" + Server.UrlDecode(Request.QueryString["Question"].ToString()) + "' And qtags='" + Server.UrlDecode(Request.QueryString["Questiontags"].ToString()) + "' And UserFullName='" + Server.UrlDecode(Request.QueryString["Askedby"].ToString()) + "' And AID1='" + Server.UrlDecode(Request.QueryString["AID1"].ToString()) + "' And AID2='" + Server.UrlDecode(Request.QueryString["AID2"].ToString()) + "' And AID3='" + Server.UrlDecode(Request.QueryString["AID3"].ToString()) + "'";
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
try
{
sqlconn.Open();
ForumQuesView.DataSource = dt;
ForumQuesView.DataBind();
ForumQuesView.AllowPaging = true;
}
catch (Exception ex)
{
Status.Text = ex.Message.ToString();
}
}
}
}
NOW I ALSO DO NOT UNDERSTAND What the problem here because only qtags and question is two field in which user allows to store data as they want, the ​question ​is text and qtags and all are the char field but problem is not in database the problem is here with the character #
Try changing your sql statement to include parameters and see if that works.
What you have now is not only difficult to maintain and causes errors but it’s prone to SQL injection attack quite easily.
sqlcomm.CommandText = "Select * From QF where Question=#Question And qtags=#Qtags And UserFullName=#UserName And AID1=#AID1 And AID2=#AID2 And AID3=#AID3";
sqlcomm.Parameters.Add(new SqlParameter("#Question", Server.UrlDecode(Request.QueryString["Question"])));
sqlcomm.Parameters.Add(new SqlParameter("#Qtags", Server.UrlDecode(Request.QueryString["Questiontags"])));
sqlcomm.Parameters.Add(new SqlParameter("#UserName", Server.UrlDecode(Request.QueryString["Askedby"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID1", Server.UrlDecode(Request.QueryString["AID1"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID2", Server.UrlDecode(Request.QueryString["AID2"])));
sqlcomm.Parameters.Add(new SqlParameter("#AID3", Server.UrlDecode(Request.QueryString["AID3"])))
;
As I know the query is fine even if you using # in the condition.
I doubt for a moment, then I tried this query
Select * From QF where Question='question 1'
And qtags='tag #1';
those query still run smooth and return the record.

Why is my MySqlCommand not actually updating my table?

I have the following code in Mono, using the MySQL Connector/Net:
try
{
MatchPersonResult mpr = personServ.MatchPerson(p, "MatchAndStore", null);
using(MySqlCommand successcmd = new MySqlCommand())
{
successcmd.CommandText = "UPDATE myccontacts SET mcid = #mcid, matchresult = #mr, datetimematched = #dtm WHERE id = #id";
successcmd.Connection = conn;
successcmd.Parameters.Add("#mcid", MySqlDbType.Int32).Value = int.Parse(mpr.PersonID);
successcmd.Parameters.Add("#mr", MySqlDbType.Enum).Value = mpr.MatchResultStatus;
successcmd.Parameters.Add("#dtm", MySqlDbType.DateTime).Value = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + " " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString();
successcmd.Parameters.Add("#id", MySqlDbType.Int32).Value = person["id"];
successcmd.ExecuteNonQuery();
Console.WriteLine(mpr.PersonID);
}
}
When the query is executed, the table isn't actually updated with anything. I set a breakpoint on the Console.WriteLine call so I can check what's happening and when it's hit, I load the row with the id mentioned in the code and it has not been updated. Even if I don't debug but just let the code execute, I see that nothing is happening to the database. For clarity's sake - personServ.MatchPerson is actually a web reference imported into my solution, so I can check on the other end and do in fact see that the proper data were sent over and that the db update should take place.
Anyone know what to do?
TIA,
Benjy
P.S.: Everything except for the db updates is working - the catch block here (not posted for brevity's sake) is never hit.
Could u try this code ?
try
{
MatchPersonResult mpr = personServ.MatchPerson(p, "MatchAndStore", null);
using(MySqlCommand successcmd = new MySqlCommand())
{
successcmd.CommandText = "UPDATE myccontacts SET mcid = #mcid, matchresult = #mr, datetimematched = #dtm WHERE id = id";
successcmd.Connection = conn;
successcmd.Parameters.AddWithValue("#mcid",int.Parse(mpr.PersonID));
successcmd.Parameters.AddWithValue("#mr",(int)mpr.MatchResultStatus);
successcmd.Parameters.AddWithValue("#dtm", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
successcmd.Parameters.AddWithValue("#id",Convert.Int32(person["id"]);
successcmd.Connection.Open();
successcmd.ExecuteNonQuery();
successcmd.Connection.Close();
Console.WriteLine(mpr.PersonID);
}
}

Any idea why one assign statement works and the other does not?

Here's my code:
string strSQL = "SELECT * from tMedia where SKU = '" + SKU + "'";
FbCommand command = new FbCommand(strSQL, databaseConn);
if (databaseConn.State == ConnectionState.Closed)
databaseConn.Open();
FbDataReader data = command.ExecuteReader();
data.Read(); // only one row is returned
// assignment to "x" is empty (277?)
string x = (string)data["ProductType"].ToString();
// find product type and set flag for later testing
// obviously, these don't work either!
if (data["ProductType"].ToString().Contains("Video "))
videoFormat = true;
else if (data["ProductType"].ToString().Contains("Music: "))
audioFormat = true;
// coProductType.Text assignment is correct
coProductType.Text = data["ProductType"].ToString();
Maybe you need to deal with the problem that will occur when someone enters an invalid SKU and NO data rows are returned.
Since the only difference is the cast to string, it seems like a reasonable first step would be to remove that. It shouldn't be necessary anyway.
It's working now... here's the code if anyone is interested... I don't understand why moving the objects to outside of the method made it work. If anyone can enlighten me, I would really appreciate it.
string mediaFormat = "";
bool video;
bool audio;
//--------------------------- populate the detail panel ---------------------|
private int PopulateDetailPanel(string SKU) {
decimal convertedMoney;
clearDetailPanel(); // clear out old stuff
// now, find all data for this SKU
if (databaseConn.State == ConnectionState.Closed)
databaseConn.Open();
string strSQL = "SELECT * from tMedia where SKU = '" + SKU + "'";
FbCommand command = new FbCommand(strSQL, databaseConn);
// find product type and set flag for later testing
FbDataReader data = command.ExecuteReader();
data.Read(); // only one row is returned
coProductType.Text = data["ProductType"].ToString(); // while we're here, might as well set it now
mediaFormat = data["ProductType"].ToString();
if (mediaFormat.Substring(0, 6) == "Video ")
video = true;
else if (mediaFormat.Substring(0, 7) == "Music: ")
audio = true;

Categories