skipping rows from table while fetching data from database asp. net C# - c#

fees_structure has 24 "A" Category rows. But when I try to fetch them and print, it only displays 20 or (21 rows sometimes)
Here is my code:
string catA = "SELECT id,fees_name,amount,fee_category FROM fees_structure where fee_category='A' ORDER BY id";
using (SqlCommand scom = new SqlCommand(catA, con))
{
using (SqlDataReader read = scom.ExecuteReader())
{
read.Read();
if (read.HasRows)
{
while (read.Read())
{
feestableA.Append("<tr>");
feestableA.Append("<td>" + read["fees_name"] + "</td>");
feestableA.Append("<td>" + read["amount"] + "</td>");
feestableA.Append("</tr>");
}
plcfeesA.Controls.Add(new Literal { Text = feestableA.ToString() });
plcfeesA.Dispose();
}
}
}

The read() before the while is suspicious. I suspect that is eating one row.
Another possibility for losing rows would be case-sensitive collations -- if the category could be 'a' (or a variant in another encoding). However, this depends on the default or explicit collations used for the column, database, and server.

I dont think this is a C# issue.
Try this
string catA = "SELECT id,fees_name,amount,fee_category FROM fees_structure where fee_category like '%A%' ORDER BY id";
Just see if your results change

Try this. Watch closely, I removed lines of code that were doing stuff you did not want to be done.
string catA = "SELECT id,fees_name,amount,fee_category FROM fees_structure where fee_category='A' ORDER BY id";
using (SqlCommand scom = new SqlCommand(catA, con))
{
using (SqlDataReader read = scom.ExecuteReader())
{
while (read.Read())
{
feestableA.Append("<tr>");
feestableA.Append("<td>" + read["fees_name"] + "</td>");
feestableA.Append("<td>" + read["amount"] + "</td>");
feestableA.Append("</tr>");
}
plcfeesA.Controls.Add(new Literal { Text = feestableA.ToString() });
}
}
}

Related

C# Retrieve ALL SQL Query Results

else if (listBox1.SelectedIndex == 1)
{
String sql2 = "SELECT FirstName, LastName FROM Players WHERE Team = 'Milwaukee Bucks'" +
"AND Number < 24";
// command statement
command = new SqlCommand(sql2, cnn);
SqlDataReader reader = command.ExecuteReader();
// Get table values
if (reader.Read())
{
textBox1.Text = reader.GetString(0).ToString() + " " + reader.GetString(1).ToString();
}
cnn.Close();
command.Dispose();
}
Above is a section of my code. I have a list box with options for the user to choose, and based on which item is selected, a display button will run a query and return the results to a textbox.
However, when I run the code I am only getting one result back. The query returns players on the Bucks who have a number less than 24. There should be multiple of them but I am only getting one in my C# application.
You need to use a while loop to read all the lines instead of reading a single line (via Read()).
Microsoft Documentation has an example of how to use the while loop.
StringBuilder sb = new StringBuilder()
while (reader.Read())
{
sb.AppendLine(reader.GetString(0).ToString() + " " + reader.GetString(1).ToString());
}
textBox1.Text = sb.ToString();

CSV - Import file to a Sql database through code

I need to load data from text file/csv file to a SQL Server database. I used the code shown below to load data and is loading to the database the problem is the data in second column may contain space but I use space for separate the column data.
i.e.
200007 XXXX Check XXXX yyy 50
200013 YYYY Check ZZZZ yyy 50
200022 nnnn 25Mg 30 Tabs
200042 mmmm 30 Mg 30 Tabs
I need to store the first ID number in the first column and the remaining text in second column:
string str = Properties.Settings.Default.con;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
try
{
cmd.Connection = con;
con.Open();
cmd.CommandText = "IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='TEMP_AUTO' AND xtype='U')" +
"CREATE TABLE TEMP_AUTO (" +
"ID varChar(10) NULL," +
"NAME varChar(50) NULL," +
"DATE TIMESTAMP NULL," +
")";
cmd.ExecuteNonQuery();
string query1 = "INSERT INTO [dbo].[TEMP_AUTO]([ID],[NAME]) VALUES (#num1, #num2)";
cmd.CommandText = query1;
string[] allLines = File.ReadAllLines(txtFilePath.Text);
for (int i = 0; i < allLines.Length; i++)
{
cmd.Parameters.Clear();
string[] items = allLines[i].Split(new char[] { ' ' });
cmd.Parameters.AddWithValue("#num1", items[0]);
cmd.Parameters.AddWithValue("#num2", items[1]);
cmd.ExecuteNonQuery();
}
MessageBox.Show("Successfully saved your data");
}
finally
{
cmd.Dispose();
con.Close();
}
A possible solution might be this:
string[] allLines = {
"200007 XXXX Check XXXX yyy 50",
"200013 YYYY Check ZZZZ yyy 50",
"200015 ",
"2541111"
};
for (int i = 0; i < allLines.Length; i++)
{
string param1 = null;
string param2 = null;
int spaceIndex = allLines[i].IndexOf(' ');
if (spaceIndex > 0)
{
param1 = allLines[i].Substring(0, spaceIndex);
if (spaceIndex < allLines[i].Length - 1)
{
param2 = allLines[i].Substring(spaceIndex + 1, allLines[i].Length-1 - spaceIndex);
}
}
else
{
param1 = allLines[i];
}
Console.WriteLine("param1:{0} param2:{1}", param1, param2);
}
Use SSIS to map this file as long as it has a standard structure to SQL Table.
Is this a one time thing? Have you tried getting the data organized in Excel then using the SSMS import tool to bring it in? If you right click on the Database then Tasks > Import Data the wizard will appear when given the option to choose the source, choose Excel. Flat files is an option but if you can format it in Excel first that tends to work better.
As you click through you can adjust the column types and where the breaks are, much like importing into Excel itself.
Use the String.Split(Char[], Int32) method to split on the first occurrence of ' ' only. Eg
string[] items = allLines[i].Split(new char[] { ' ' }, 2);
Refs: MSDN and previous relevant question
Use the below code.
using (StreamReader sr = File.OpenText("txtFile.txt")) // Mention the path,if the file is not in application folder.
{
string str = String.Empty;<br/>
while ((str = sr.ReadLine()) != null)
{
string[] item = str.Split(' ');
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand();
string query1 = "INSERT INTO [dbo].[TEMP_AUTO]([ID],[NAME]) VALUES ('" + item[0] + "', '" + item[1] + "')";
// Do remain part<br/>
}
}

Appending to File resulting in missing data

I have a script that is connecting to multiple databases and writing a query from each into a text file. However when I run it, I'm not getting the results expected. After some cross checking, it looks like it is writing the same results from the first database query instead of finding new results from the next connection. I inserted an IP string to verify the IPs are being grabbed by the for loop but it seems like I need some way of clearing the reader?
for (int z=0; z<2;z++) {
using (OleDbConnection connLocal = new OleDbConnection("Provider=SAOLEDB;LINKS=tcpip(host=" + ips[z] + ",PORT=2638);ServerName=EAGLESOFT;Integrated Security = True; User ID = dba; PWD = sql"))
try
{
connLocal.Open();
using (OleDbCommand cmdLocal = new OleDbCommand("SELECT tran_num, '" + ips[z] + "', provider_id, amount, tran_date, collections_go_to, impacts, type, '" + clinics[z] + "' AS Clinic FROM transactions WHERE tran_date LIKE '2015-11-23%'", connLocal))
using (StreamWriter sqlWriter = File.AppendText(#"C:\Users\Administrator\Desktop\Clinic.txt"))
{
using (OleDbDataReader readLocal = cmdLocal.ExecuteReader())
{
while (readLocal.Read())
{
sqlWriter.WriteLine("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}",
readLocal.GetValue(0).ToString(),
readLocal.GetValue(1).ToString(),
readLocal.GetValue(2).ToString(),
readLocal.GetValue(3).ToString(),
readLocal.GetValue(4).ToString(),
readLocal.GetValue(5).ToString(),
readLocal.GetValue(6).ToString(),
readLocal.GetValue(7).ToString(),
readLocal.GetValue(8).ToString());
}
readLocal.Close();
}
sqlWriter.Close();
connLocal.Close();
}
}
catch (Exception connerr) { Debug.WriteLine(connerr.Message); }
}
As always, any insight is much appreciated!

C# Odbc Query Result Incorrect

I am struggling here trying to understand (after a lot of research a futzing with this) why my MySQL query in C# is returning only one row and the values are wrong.
public static void loadCombinedPaymentExportData(Int32 iFromId = 0)
{
// VERIFIED STATE OF CONNECTION (OUTPUTS "OPEN")
Console.Write(oConn.State+"\n");
// TRIED USING PREPARED STATEMENTS FIRST
//OdbcCommand oCommand = new OdbcCommand("SELECT * FROM v_payment_export_combined_rec WHERE id > ? LIMIT 10", oConn);
//oCommand.Parameters.Add("#ID", OdbcType.Int).Value = iFromId;
// ENDED UP TRYING A MORE DIRECT APPROACH SO I COULD SEE WHAT IS HAPPENING
string sQuery = "SELECT * FROM v_payment_export_combined_rec WHERE id > " + iFromId.ToString() + " LIMIT 10";
// OUTPUTS "SELECT * FROM v_payment_export_combined_rec WHERE id > 0 LIMIT 10"
Console.WriteLine(sQuery);
OdbcCommand oCommand = new OdbcCommand(sQuery, oConn);
using (OdbcDataReader oReader = oCommand.ExecuteReader())
{
// THIS ENTERS INTO THE BLOCK AS HAVING ROWS
if (oReader.HasRows)
{
while (oReader.Read())
{
// THIS ONLY OUTPUTS ONCE AS "Data: 1"
Console.WriteLine("\nData: {0}", oReader.GetString(0));
}
}
else
{
Console.WriteLine("No rows found.\n");
}
oReader.Close();
oCommand.Dispose();
}
}
The issue here is if I run the same exact query on the database using my SQL editor, I have something like 190k+ rows come back from the view, and the lowest id is 8. In fact, I tried adding additional output like:
Console.WriteLine("\nData: {0} | {1} | {2}", oReader.GetString(0), oReader.GetString(1), oReader.GetString(2));
And every single one of them comes back as a 1, which is incorrect as the 2nd column has real text.
Curiously, I had previously done a similar test on another table using this same logic and it worked just fine.
What am I messing up?
[EDIT]
Just tried using the MySQL .NET Connector instead of ODBC and got the same result.
string sQuery = "SELECT * FROM v_payment_export_combined_rec WHERE id > " + iFromId.ToString() + " LIMIT 10;";
MySqlCommand oCommand = new MySqlCommand(sQuery, oConn);
using (MySqlDataReader oReader = oCommand.ExecuteReader())
{
if (oReader.HasRows)
{
while (oReader.Read())
{
Console.WriteLine("\nData: {0}", oReader.GetString(0));
}
}
else
{
Console.WriteLine("No rows found.\n");
}
oReader.Close();
oCommand.Dispose();
}
I will keep investigating here to see if I can figure out what is going on.

C# Fatal error encoutered during data read

I'm selecting about 20,000 records from the database and then I update them one by one.
I looked for this error and I saw that setting the CommandTimeout will help, but not in my case.
public void Initialize()
{
MySqlConnectionStringBuilder SQLConnect = new MySqlConnectionStringBuilder();
SQLConnect.Server = SQLServer;
SQLConnect.UserID = SQLUser;
SQLConnect.Password = SQLPassword;
SQLConnect.Database = SQLDatabase;
SQLConnect.Port = SQLPort;
SQLConnection = new MySqlConnection(SQLConnect.ToString());
}
public MySqlDataReader SQL_Query(string query)
{
MySqlCommand sql_command;
sql_command = SQLConnection.CreateCommand();
sql_command.CommandTimeout = int.MaxValue;
sql_command.CommandText = query;
MySqlDataReader query_result = sql_command.ExecuteReader();
return query_result;
}
public void SQL_NonQuery(string query)
{
MySqlCommand sql_command;
sql_command = SQLConnection.CreateCommand();
sql_command.CommandTimeout = int.MaxValue;
sql_command.CommandText = query;
sql_command.ExecuteNonQuery();
}
And here is my method which makes the select query:
public void CleanRecords()
{
SQLActions.Initialize();
SQLActions.SQL_Open();
MySqlDataReader cashData = SQLActions.SQL_Query("SELECT `cash`.`id`, SUM(`cash`.`income_money`) AS `income_money`, `cash_data`.`total` FROM `cash_data` JOIN `cash` ON `cash`.`cash_data_id` = `cash_data`.`id` WHERE `user`='0' AND `cash_data`.`paymentterm_id`='0' OR `cash_data`.`paymentterm_id`='1' GROUP BY `cash_data_id`");
while(cashData.Read()){
if(cashData["income_money"].ToString() == cashData["total"].ToString()){
UpdateRecords(cashData["id"].ToString());
}
}
SQLActions.SQL_Close();
}
And here is the method which makes the update:
public void UpdateRecords(string rowID)
{
SQLActions.Initialize();
SQLActions.SQL_Open();
SQLActions.SQL_NonQuery("UPDATE `cash_data` SET `end_date`='" + GetMeDate() + "', `user`='1' WHERE `id`='" + rowID + "'");
SQLActions.SQL_Close();
}
Changing the database structure is not an option for me.
I thought that setting the timeout to the maxvalue of int will solve my problem, but is looks like this wont work in my case.
Any ideas? :)
EDIT:
The error which I get is "Fatal error encoutered during data read".
UPDATE:
public void CleanRecords()
{
StringBuilder dataForUpdate = new StringBuilder();
string delimiter = "";
SQLActions.Initialize();
SQLActions.SQL_Open();
MySqlDataReader cashData = SQLActions.SQL_Query("SELECT `cash`.`id`, SUM(`cash`.`income_money`) AS `income_money`, `cash_data`.`total` FROM `cash_data` JOIN `cash` ON `cash`.`cash_data_id` = `cash_data`.`id` WHERE `user`='0' AND `cash_data`.`paymentterm_id`='0' OR `cash_data`.`paymentterm_id`='1' GROUP BY `cash_data_id`");
while (cashData.Read())
{
if (cashData["income_money"].ToString() == cashData["total"].ToString())
{
dataForUpdate.Append(delimiter);
dataForUpdate.Append("'" + cashData["id"].ToString() + "'");
delimiter = ",";
}
}
SQLActions.SQL_Close();
UpdateRecords(dataForUpdate.ToString());
}
public void UpdateRecords(string rowID)
{
SQLActions.Initialize();
SQLActions.SQL_Open();
SQLActions.SQL_NonQuery("UPDATE `cash_data` SET `end_date`='" + GetMeDate() + "', `user`='1' WHERE `id` IN (" + rowID + ")");
SQLActions.SQL_Close();
}
You may be able to use
UPDATE cash_data .... WHERE id IN (SELECT ....)
and do everything in one go. Otherwise, you could do it in two steps: first the select collects all the ids, close the connection and then do the update in obne go with all the ids.
The code for the second option might look something like this:
public void CleanRecords()
{
StringBuilder builder = new StringBuilder();
string delimiter = "";
SQLActions.Initialize();
SQLActions.SQL_Open();
MySqlDataReader cashData = SQLActions.SQL_Query("SELECT `cash`.`id`, SUM(`cash`.`income_money`) AS `income_money`, `cash_data`.`total` FROM `cash_data` JOIN `cash` ON `cash`.`cash_data_id` = `cash_data`.`id` WHERE `user`='0' AND `cash_data`.`paymentterm_id`='0' OR `cash_data`.`paymentterm_id`='1' GROUP BY `cash_data_id`");
while(cashData.Read()){
if(cashData["income_money"].ToString() == cashData["total"].ToString()){
builder.Append(delimiter);
builder.Append("'" + cashData["id"].ToString() + "'");
delimiter = ",";
}
}
SQLActions.SQL_Close();
UpdateRecords(builder.ToString());
}
public void UpdateRecords(string rowIDs)
{
SQLActions.Initialize();
SQLActions.SQL_Open();
SQLActions.SQL_NonQuery("UPDATE `cash_data` SET `end_date`='" + GetMeDate() + "', `user`='1' WHERE `id` IN (" + rowIDs + ")";
SQLActions.SQL_Close();
}
There are multiple problem:
First: You have reading information around 20K using data reader and then doing update one by one in reader itself. Reader holds the connection open until you are finished. So this is not the good way to do it. Solution: We can read the information using Data Adapter.
Second: Rather than doing one by one update, we can update in bulk in one go. There are multiple option for bulk operation. In SQL u can do either by sending information in XML format or u can use Table Valued Parameter (TVP) (http://www.codeproject.com/Articles/22205/ADO-NET-and-OPENXML-to-Perform-Bulk-Database-Opera) OR (http://dev.mysql.com/doc/refman/5.5/en/load-xml.html)

Categories