asp.NET C# - Problems with ExecuteNonQuery() with Oracle Commands - c#

I have this problem with a query I have, I am using Oracle Commands and Parameters. I have hundreds of other queries in my code, but just this one is failing to execute. It is a very simple update query and it works in SQL Navigator because I tried it.
Within the code, the execute non query method seems like it freezes and i get "Waiting for http:// localhost:8081/MaintainUserProfile.aspx" in my webpage.
I appreciate your help because I've wasted hours on it and I'm clueless at this stage.
Let me know if I should state more information.
The code below (Please note I work with oracle parameters, but in this case I am just using plain strings to debug the problem, the same happens with oracle parameters, it get stuck on execute non query):
string sqlQuery = #"UPDATE schema_name.table_name
SET
officer_name = '" + fullName +
"', channel_code = " + channelCode +
", male_female_ind = '" + maleFemale +
"', user_status_code = '" + userStatusCode +
"', identity_number = '" + idNumber +
"', extension_number = " + extensionNumber +
" WHERE user_profile_id = " + userProfileID;
OracleCommand oraCommand2 = new OracleCommand(sqlQuery, db);
oraCommand2.ExecuteNonQuery();

You can try with this code - Based on AddWithValue
oraCommand2.CommandText="UPDATE schema_name.table_name SET
officer_name = :fullName , channel_code = :channelCode,
male_female_ind = :male_female_ind, user_status_code = :user_status_code,
identity_number = :idNumber, extension_number = :extensionNumber
WHERE user_profile_id = :userProfileID";
oraCommand2.Parameters.AddWithValue(":fullName", fullName);
oraCommand2.Parameters.AddWithValue(":channelCode", channelCode);
oraCommand2.Parameters.AddWithValue(":male_female_ind", male_female_ind );
oraCommand2 .Parameters.AddWithValue(":user_status_code", user_status_code );
oraCommand2 .Parameters.AddWithValue(":identity_number", identity_number );
oraCommand2 .Parameters.AddWithValue(":extension_number", extension_number );
oraCommand2 .Parameters.AddWithValue(":user_profile_id", user_profile_id );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.oracleclient.oracleparametercollection.addwithvalue.aspx

Kenneth answered it in this Post, it may be due to an uncommitted operation in SQLDeveloper (or any other uncommitted pending database change).

Related

How to make start with / contains work with EF and SQL Text column storing JSON

I have table with nvarchar (max) column storing json like one below,
{"status":"Archieved","oldCategories":{"name":"LONG Life -
Milk","products":{"tagPrice1Notes":"800 Times
Said","columnType2":"","columnType3":"someValue3","columnType4":"someValue4","columnType5":"someValue5","columnType6":"someValue6","columnType7":"someValue7"}},"moreProperties":.... so on
Now I need to get all columns where value starts with above string, however I am getting 0 rows back, here is what I am trying,
var matchMe = (
"{'status':'Archieved'" +
"','oldCategories': {'name': '" + someObject.Name +
"','products': {'tagPrice1Notes': '" + someObject.C1 +
"','columnType2': '" + someObject.C2 +
"','columnType3': '" + someObject.C3 +
"','columnType4': '" + someObject.C4 +
"','columnType5': '" + someObject.C5 +
"','columnType6': '" + someObject.C6 +
"','columnType7': '" + someObject.C7 +
"'}}"
);
dbContext.CategoriesProducts.Where(x => x.MyJsonDetailsColumn.ToUpper().Trim().Contains(matchMe.ToUpper().Trim()))
.ToList();
This is a temporary fix and we will do a refactor later on.
Your example code will basically read all the data back to your client (the ToUpper/Trim parts will mean this is a client side check), so why not just read all the data, deserialise it into an object and perform a proper comparison of the fields you need to?

Is it possible to update data without actually removing the previously added data in MySQL?

Im tasked to update selected information however not delete the previous data added...How do I update without replacing the old data and is it possible to view it if necessary?
Heres a part of my code:
MySqlConnection conn = new MySqlConnection(mycon);
string Query = "update mydb.client set clientLN='" + txtClientLName.Text + "', clientFN='" + txtClientFName.Text + "', clientMN='" + txtClientMName.Text + "', clientType='" + cmbTypeMembership.Text + "', clientMembershipType='" + cmbRates.Text + "', clientMembershipValidity='" + Days.ToString() + "', clientMembershipStatus='" + validity + "' where clientID='" + clientID + "';";
conn.Open();
MySqlCommand myCommand = new MySqlCommand(Query, conn);
myReader = myCommand.ExecuteReader();
conn.Close();
MessageBox.Show("Client Successfully Renewed!");
In sql, an update without replacing old data is called an insert
It sounds like you need to keep the old values related to the client around for [backup, audit, some other reason]. Two possible approaches;
1) Keep a archive table where you insert the existing record (with a timestamp) before issuing the update.
2) Make you main table effective-dated (but your application will need to know how to deal w/ effective-dated records).

Update DATETIME column where said DATETIME < current DATETIME

I've got an ASP.NET 4.0 C# web application that allows multiple users to update rows in the SQL Server DB at the same time. I'm trying to come up with a quick system that will stop USER1 from updating a row that USER2 updated since USER1's last page refresh.
The problem I'm having is that my web application always updates the row, even when I think it shouldn't. But when I manually run the query it only updates when I think it should.
This is my SQL query in C#:
SQLString = "update statuses set stat = '" + UpdaterDD.SelectedValue +
"', tester = '" + Session["Username"].ToString() +
"', timestamp_m = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") +
"' where id IN (" + IDs + ") and timestamp_m < '" + PageLoadTime + "';";
And here's a 'real world' example:
SQLString = "update statuses set stat = 'PASS', tester = 'tester007',
timestamp_m = '2013-01-23 14:20:07.221' where id IN (122645) and
timestamp_m < '2013-01-23 14:20:06.164';"
My idea was that this will only update if no other user has changed this row since the user last loaded the page. I have formatted PageLoadTime to the same formatting as my SQL Server DB, as you can see with DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), but something still isn't right.
Does anyone know why I get two different results? Is what I want to do even possible?
I really think the problem is that the page load time is not being set correctly, or is being set immediately before the DB call. For debugging, you may try hardcoding values into it that you know will allow or disallow the insert.
Here's a parameterized version of what you have. I also am letting the DB server set the timestamp to its current time instead of passing a value. If your DB server and your Web server may not have their time of day in synch, then set it yourself.
Using parameterization, you don't have to worry about whether the date/time format is correct or not. I don't know what the DB types are of stat, tester, and timestamp_m so adding the parameter DB type may need adjusting.
string sql = "update statuses set stat = #stat, tester = #tester" +
", timestamp_m = getdate()" +
" where id IN (" + IDs + ") and timestamp_m < #pageLoadTime";
SQLConnection conn = getMeASqlConnection();
SQLCommand cmd = new SQLCommand(sql, conn);
cmd.Parameters.Add("#stat", System.Data.SqlDbType.NVarChar).Value = UpdaterDD.SelectedValue;
cmd.Parameters.Add("#tester", System.Data.SqlDbType.NVarChar).Value = Session["Username"].ToString();
// Here, pageLoadTime is a DateTime object, not a string
cmd.Parameters.Add("#pageLoadTime", System.Data.SqlDbType.DateTime).Value = pageLoadTime;

SQL Delete query not working properly

I had a logic error in my sql delete query which would not give any error in visual studio and did not delete the record in the database
Here is a snippet of my code
SqlCommand cmd = new SqlCommand(
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "",
con);
cmd.ExecuteNonQuery();
here is my conString
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=InvenotyBB;Integrated Security=SSPI")
I have confirmed that the other verbs (select, update, etc) work, just not the specific command for delete.
I can almost guarantee your connection string has:
User Instance=true;AttachDbFileName=|Data Directory|...something.mdf;
If this is the case, STOP DOING THAT. The AttachDbFileName feature actually creates a copy of your database file. So the one you have open in Management Studio or Visual Studio is different from the one your application created via the connection string. Your application deletes from the copy, there are no exceptions (because it worked), you refresh the original, and it looks like it didn't work.
See the answer from #marc_s's here:
https://stackoverflow.com/a/7222952/61305
If this isn't it, then I suspect either (a) errors are being ignored due to try/catch somewhere, or (b) your method for checking if the command worked is suspect. For example, if you are relying on a count, and the where clause matches zero rows, then the command worked but it didn't delete anything, therefore the count remains the same.
If neither of those are true, then goto line 1 of my answer. There is no magic here, a delete command will either affect 0 or more rows, or it will return an exception. Anything else can only be explained by improper troubleshooting / debugging.
Given this original code (via my formatting):
SqlCommand cmd = new SqlCommand(
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "",
con);
cmd.ExecuteNonQuery();
Let's change this to:
string deleteQuery =
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "";
SqlCommand cmd = new SqlCommand(deleteQuery, con); /* set a breakpoint here */
cmd.ExecuteNonQuery();
Set the breakpoint and copy-paste that query to a comment here so we can see it.

insert date into SQL

I'm trying to insert a date into a SQL table, but it when the program runs it gives the following error.
Conversion failed when converting date and/or time from character string.
string dateReleased = DateReleasedDate.Value.ToString("YYYY-MM-DD");
string myQuery = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, dateAdded, developerID, publisherID, consoleID) VALUES('"
+ GameNameTxt.Text + "', '" + GenreCombo.SelectedValue + "', '" + PlayersNUD.Value + "', '" + OnlineCombo.SelectedText + "', '"
+ dateReleased + "', 'GETDATE()', '" + DeveloperCombo.SelectedValue + "', '"
+ PublisherCombo.SelectedValue + "','" + ConsoleCombo.SelectedValue + "')";
Please use parametrized queries. My eyes hurt when I see string concatenations used to construct SQL queries:
using (var conn = new SqlConnection("SOME CONNECTION STRING"))
using (var cmd = new SqlCommand(conn))
{
conn.Open();
cmd.CommandText = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, developerID, publisherID, consoleID) VALUES (#gameName, #genreID, #players, #online, #dateReleased, #developerID, #publisherID, #consoleID)";
cmd.Parameters.AddWithValue("#gameName", GameNameTxt.Text);
cmd.Parameters.AddWithValue("#genreID", GenreCombo.SelectedValue);
cmd.Parameters.AddWithValue("#players", PlayersNUD.Value);
cmd.Parameters.AddWithValue("#online", OnlineCombo.SelectedText);
cmd.Parameters.AddWithValue("#dateReleased", DateReleasedDate.Value);
cmd.Parameters.AddWithValue("#developerID", DeveloperCombo.SelectedValue);
cmd.Parameters.AddWithValue("#publisherID", PublisherCombo.SelectedValue);
cmd.Parameters.AddWithValue("#consoleID", ConsoleCombo.SelectedValue);
var result = cmd.ExecuteNonQuery();
...
}
As far as the dateAdded column is concerned I would simply remove it from the INSERT and add it a default value directly in the SQL database.
Notice how you are directly passing DateTime instances and you leave ADO.NET handle the formats. As a bonus your code is safe against SQL injections.
DateReleasedDate.Value.ToString("yyyy-MM-dd");
The problem is you put GETDATE() into single-quotes. It is trying to convert the string 'GETDATE()' into a date.
The best way to pass a date into SQL from .net, IMO, is to use the .ToOADate function.
The function passes in a numerical representation of the date that will work on any database datetime \ date field regardless of the regional setup.
Some info for you: ToOADate

Categories