Display the records that were updated C# - c#

I have a simple update statement which updates locations where it is a certain Location. I am currently making a small desktop app where When I press a button, it will update and then display the records that were updated. How can I return the Ids of the records that were updated and then display those records in C#.
SqlCommand cmd = new SqlCommand(" update conset set location='LA' where deal in (select deal from dealset where location='LA') and locationid = 'NY'", con);
int rowsAffected = cmd.ExecuteNonQuery();
This however, only tells me the number of records that were updated not which ids were updated so I can query to display them. Help?
For example if 3 records were updated with the IDs: 1102, 1105, 111
Then it should display their Number based on the Id.
However, I am unsure how I can do that. How would I loop through the updated results.

I'd use an OUTPUT clause and loop the DataReader:
string sql = #"
UPDATE c
SET c.location = 'LA'
OUTPUT INSERTED.IdColumn
FROM conset c
WHERE deal IN (SELECT deal
FROM dealset
WHERE location = 'LA')
AND c.locationid = 'NY';";
List<int> updatedIDs = new List<int>();
using (var con = new SqlConnection(Properties.Settings.Default.ConnectionString))
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
using (var rd = cmd.ExecuteReader())
{
while (rd.Read())
{
updatedIDs.Add(rd.GetInt32(0));
}
}
}

Related

Crystal report ModuleNames dispalyed horizontally

I have data set with following columns
1. PRN
2. Name
3. Module name
4. Theory Marks
5. Total Marks
this data set is field with different modules of same course and data is comes from database
I have given this data set data to crystal report as data source
I want to display TheoryMarks and totalMarks under ModuleName in below format
ModuleName1 ModuleName2 ModuleName3
PRN Name Theory Marks TotalMarks Theory Marks TotalMarks
I have tried group column using Module Name .I have also tried CrossTab Expert but its not allowing me to add theory marks and total marks
string reportPath;
string pathText = "PGCourseResultCrystalreport";
string path = "PGCourseResult.rpt";
if (pathText == "PGCourseResultCrystalreport")
{
reportPath = Server.HtmlEncode(Request.PhysicalApplicationPath).ToString() + "MemberArea\\ResultReport\\" + path;
rptDoc.Load(reportPath);
error.Text += "reportdocloaded";
//DataTable Resut = GetResultData();
try
{
string query = "select P.PRN, P.[StudentName] ,P.TheoryMarks,L.TotalMarks,L.ModuleName from [PGCoursesTheoryMarksMaster] P,[ModulewiseLabInternalMarks] L where L.PRN=P.PRN and P.Centre_ID=L.CentreId and P.Course_ID=L.Course_ID and P.Module_ID=L.Module_ID and P.Batch_ID=L.Batch_ID and P.Centre_ID=#centreId and P.Course_ID=#courseId and P.Batch_ID=#batchId ";
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["aoldbConnectionString"].ConnectionString);
string centreID = DDLCentreList.SelectedValue;
// string BatchID = BatchIdDropDown.SelectedValue;
int CourseId = Convert.ToInt32( DropDownListCourse.SelectedValue);
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#CentreId", Convert.ToInt32(centreID));
cmd.Parameters.AddWithValue("#courseId", CourseId);
cmd.Parameters.AddWithValue("#batchId", batchId);
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(CourseMarks, "MainResultData");
foreach (DataRow row in CourseMarks.Tables[0].Rows)
{
error.Text += row["PRN"].ToString();
}
I want to display result as explained .
CrossTab is the right approach.
Let the CrossTab do the totals.
In other words, instead of trying to select totals as the CrossTab values, select the detail data and let the CrossTab do the averaging, summing, etc.

Update Set command works in Access but not in Visual Studio with #parameters

I have been working on a personal project for the company I work for to control stock levels in order to practice my c#.
I want my application to search through tblJuiceStock, find a matching FlavourID to what the user is inputting and update the stock of that record through an UPDATE SET query.
public void InsertJuiceStockWithCheck()
{
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = ConnectionString;
conn.Open();
string tblJuiceStockCheck = "SELECT FlavourID, Quantity FROM tblJuiceStock";
OleDbCommand cmdCheck = new OleDbCommand(tblJuiceStockCheck, conn);
OleDbDataAdapter daCheck = new OleDbDataAdapter(cmdCheck);
DataTable dtCheck = new DataTable();
daCheck.Fill(dtCheck);
foreach (DataRow row in dtCheck.Rows)
{
if ((int)row["FlavourID"] == fID)
{
int currentQty = (int)row["Quantity"];
int updatedQty = currentQty + qty;
string tblJuiceStockExisting = #"UPDATE tblJuiceStock
SET Quantity = #newquantity
WHERE FlavourID = #flavourID";
OleDbCommand cmdJuiceStockExisting = new OleDbCommand(tblJuiceStockExisting, conn);
cmdJuiceStockExisting.Parameters.AddWithValue("#flavourID", fID);
cmdJuiceStockExisting.Parameters.AddWithValue("#newquantity", updatedQty);
cmdJuiceStockExisting.ExecuteNonQuery();
matchFound = true;
break;
}
}
if (!matchFound)
{
string tblJuiceStockNew = "INSERT INTO tblJuiceStock (FlavourID, Quantity, MinStockPOS) VALUES (#fID, #quantity, #minstock)";
OleDbCommand cmdJuiceStockNew = new OleDbCommand(tblJuiceStockNew, conn);
cmdJuiceStockNew.Parameters.AddWithValue("#fID", fID);
cmdJuiceStockNew.Parameters.AddWithValue("#quantity", qty);
cmdJuiceStockNew.Parameters.AddWithValue("#minstock", amt);
cmdJuiceStockNew.ExecuteNonQuery();
}
}
}
Please note: this query works fine in Access when I replace parameters with the same values. Also, using breakpoints I identified that the parameters have the correct values set to them, the variables assigned to them are obtained within another method, all methods are called in the submit button event.
However, the Quantity value in TblJuiceStock remains the same.
My tblJuiceStock table
After some time of messing about the answer was simple.
OLEDB does work with named parameters but you have to declare them, if you don't declare them they use the parameters positioning to match them up.
My problem was that in my query string I had #newquantity first and #flavourID second, whereas when adding my parameters I added #flavourID first and #newquantity second.

c# .net Core OracleDataReader check count in results

I know only one way how to count rows in results after ExecuteReader with this code:
while (er.Read()) {
count++;
}
How can I check with no while?
Short answer: you can't.
Long answer: ExecuteReader returns a forward-only sequential stream iterator, each time you advance one position you will point to and read one record until it reaches the end of the available data. Therefore it is impossible to know how many records you have until you have read all of them.
Here is a solution that may work for you, though.
Imagine you want to run this simple query: select * from Users
Even if you run this in your Oracle database directly, you won't know how many records you have until the query is executed. If you wanted to know the number of records you would use a count query, something like select count(*) from Users.
You can do the same using c#:
int count = 0;
using (var conn = new OracleConnection("Some connection string"))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "select count(*) from users";
count = (int)cmd.ExecuteScalar();
}
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "select * from users";
using(var reader = cmd.ExecuteReader())
{
while (reader.Read()) {
[...]
}
}
}
}
You could load your results into a DataTable and get the row count of of it:
using(var dt = new DataTable())
{
dt.Load(er); //assuming er is the OracleDataReader
}
Now you can read the rowCount with dt.Rows.Count.

unreachable code detected on for loop

Tried finding similar from my problem but it seems there are too many unreachable code detectedmy table consist of 4 rows and I tried this code
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand(query, conn);
int num = Convert.ToInt32(cmd.ExecuteScalar());
MySqlCommand cmd1 = new MySqlCommand(query2, conn);
MySqlDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
for (int a = 0; a <= num; a++)
{
List li = new List();
li.linkLabel1.Text = reader["TitleAnime"].ToString();
flowLayoutPanel1.Controls.Add(li);
// break;
}
}
conn.Close();
}
but it gives me 16 values and thats too much then I tried putting break inside the for loop and I was able to achieve my goal and it gives me 4 values which is the same on my table but there seems to be an error called unreachable code detected..should I ignore it since I was able to get what I need? or is there another way for that
I'm pretty sure you are doing one query too much there, and you are getting NxN results because of that first query and of that for loop.
Try something like this:
using (MySqlConnection conn = new MySqlConnection(myConnection))
{
conn.Open();
MySqlCommand cmd1 = new MySqlCommand(query2, conn);
MySqlDataReader reader = cmd1.ExecuteReader();
while (reader.Read())
{
List li = new List();
li.linkLabel1.Text = reader["TitleAnime"].ToString();
flowLayoutPanel1.Controls.Add(li);
}
conn.Close();
}
If that does the job, consider in changing the name of the query1 and cmd1 to query and cmd since now you'll have only one of each
It's quite simple. You're running a for loop based on the number of entries you have in your database from the command object.
The read method will iterate four times if that's how many records you have in your database. Refer to this article for more information: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read(v=vs.110).aspx.
In short, just remove the for loop and you'll get the result you want.
Try something like this:
while (reader.Read())
{
flowLayoutPanel1.Controls
.Add(new List { linkLabel1.Text = reader["TitleAnime"].ToString()});
}

C# SQL multiple query results into diffrent textbox

So I'm having this :
Conn.Open();
SqlCommand Comm3 = new SqlCommand("SELECT answer" + " FROM answers" + " WHERE id_answer=5" , Conn);
SqlDataReader DR3 = Comm3.ExecuteReader();
And there is multiple results,how can I now move each of them in diffrent textbox (i already created textboxes? Till now i only managed to get same result into them.
this is normally how i do it....
SqlConnection cn = new SqlConnection("my connection string");
cn.Open();
string sql = "select * from table where column = whatever";
using (SqlCommand cmd = new SqlCommand(sql,cn))
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
myTextBox1.Text = (string)dr["Column1"];
myTextBox2.Text = (string)dr["Column2"];
myTextBox3.Text = (string)dr["Column3"];
}
dr.Close();
}
cn.Close();
just make sure you are aiming the right column name while looping through them, and cast correctly.
You need to loop through each of the item in the Database table. Think of a foreach loop, where you simply just go through each item and work on it similarly.
Here is a sample for that,
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
textBox.Text = reader[0];
}
}
This will add the value of reader's first column (answer) to the textBox. Now make sure you're calling correct textBox to add the value to.
http://www.codeproject.com/Articles/823854/How-to-connect-SQL-Database-to-your-Csharp-program Do give this article a read.

Categories