How to populate ArrayList with SQL Select Statement Results - c#

I am doing an sql select statement on my web service in Visual Studio 2010. It is only from a column but there are multiple rows of data. How do I populate an arraylist with the data and return it?
[WebMethod]
public List<String> getAccType(string bankId)
{
myConnection.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("SELECT TypeName FROM AccType where BankID = '" + bankId + "'", myConnection);
myReader = myCommand.ExecuteReader();
List<String> AccType = new List<string>();
while (myReader.Read())
{
string iAccType = myReader["TypeName"].ToString();
AccType.Add(iAccType);
}
return AccType;
}
}

While you could return an ArrayList, it would be better to return a strongly-typed collection, either a List<T> or IEnumerable<T> with an underlying List<T> collection, perhaps.
Here is an example using a SqlDataReader to extract data from a column and populate such a list. Note: I haven't included any error handling.
public IEnumerable<int> GetOrderIds()
{
var ids = new List<int>();
var queryString = "SELECT OrderID FROM dbo.Orders;";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(queryString, connection))
{
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var id = reader.GetInt32(0);
ids.Add(id);
}
}
}
return ids;
}

Related

How to return list of records using stored procedure and datareader in C#

I want to return list of records using stored procedure and datareader in C#. Currently, it is giving me error
Cannot implicitly convert type 'ClsHorseTracker' to 'System.Collections.Generic.List'
Code:
public List<ClsHorseTracker> HorseTrackerList()
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();
string sSQL = "exec HorseDetails";
ds = clsUtilities.GetDataSet(sSQL);
SqlCommand cmd = new SqlCommand();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
clsHorseTracker = new ClsHorseTracker
{
HorseName = Convert.ToString(reader["HorseName"]),
HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
};
}
}
}
return clsHorseTracker;
}
clsHorseTracker is a list of ClsHorseTracker. So you need to add new object to the list in "while" loop instead of assign an object to the list
Try this
public List<ClsHorseTracker> HorseTrackerList()
{
clsUtilities clsUtilities = new clsUtilities();
DataSet ds;
List<ClsHorseTracker> clsHorseTracker = new List<ClsHorseTracker>();
string sSQL;
sSQL = "exec HorseDetails";
ds = clsUtilities.GetDataSet(sSQL);
SqlCommand cmd = new SqlCommand();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
clsHorseTracker.Add(new ClsHorseTracker
{
HorseName = Convert.ToString(reader["HorseName"]),
HorseTypeName = Convert.ToString(reader["HorseTypeName"]),
});
}
}
}
return clsHorseTracker;
}

Read SQL Server table row by row already in string type

I have a question: is it possible to select data from a table in string (without using ToString method) rows?
Without using SqlDataReader and with good performance.
For example read all table and put data to List of string type.1 element=1row
SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
conn.Open();
SqlCommand command = new SqlCommand("Select id from [table1] where name=#zip", conn);
command.Parameters.AddWithValue("#zip","india");
// don't use reader
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
//List<string> = String.Format(row properties...)
}
}
Sorry for bad explanation
Sure, you can cast it:
SELECT id = CAST(id AS varchar(20)) FROM ...;
Now you don't need to convert it at client side and can use:
var idList = new List<string>();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
idList.Add(reader.GetString(0));
}
}
For what it's worth, if you want a one-liner in future use this extension:
public static class DbExtensions
{
public static List<T> ToList<T>(this IDataReader reader, int columnOrdinal = 0)
{
var list = new List<T>();
while (reader.Read())
list.Add((T) reader[columnOrdinal]);
return list;
}
}
Now you can use this code:
idList = reader.ToList<string>();

SQLite command construct WHERE clause

How to use Combobox.SelectedValue to construct WHERE clause?
conL.Open();
cmdL.Connection = conL;
cmdL.CommandText ="SELECT Id FROM dbAllServers WHERE Server_Names='" + cmb_SQLNames.SelectedValue +"'";
SQLiteDataReader r = cmdL.ExecuteReader();
while(r.Read())
{
serID = int.Parse(r[0].ToString());
MessageBox.Show("Current Selected Server ID is:..." + serID.ToString());
}
conL.Close();
An example of parameterized query, might be helpful:
string query = "SELECT Id FROM dbAllServers WHERE Server_Names=#server_name";
string serverName = cmb_SQLNames.SelectedValue;
using (SQLiteConnection connection = new SQLiteConnection(GetConnectionString()))
{
connection.Open();
using (var cmd = new SQLiteCommand(query, connection))
{
cmd.Parameters.Add(new SQLiteParameter("#server_name", serverName));
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
// do your job here
}
}
}
}

C# use a reader in another reader solution?

I need to get some mysql data into another mysql reader request anyway to workaround that I apparently can't have 2 readers open at the same time it will all end up in a datagrid
public void DBSelectPraktikanter(object sender)
{
string Command = "SELECT * FROM forlob WHERE firmaid = N'" + firmaid + "'";
MySqlConnection sqlConnection1 = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(Command, sqlConnection1);
sqlConnection1.Open();
MySqlDataReader reader = command.ExecuteReader();
var items = new List<praktikanter>();
if (reader.HasRows)
{
while (reader.Read())
{
string praktikantid = String.Format("{0}", reader["praktikantid"]);
string Command2 = "SELECT * FROM praktikanter WHERE id = N'" + praktikantid + "'";
MySqlCommand command2 = new MySqlCommand(Command, sqlConnection1);
MySqlDataReader reader2 = command.ExecuteReader();
if (reader.HasRows)
{
while (reader2.Read())
{
Praktikant = String.Format("{0}", reader["Navn"]);
}
}
string Fra = String.Format("{0}", reader["fra"]);
string Til = String.Format("{0}", reader["til"]);
items.Add(new praktikanter(Praktikant, Fra, Til));
}
}
sqlConnection1.Close();
var grid = sender as DataGrid;
grid.ItemsSource = items;
}
Instead of nesting MySqlCommands and looping the first resultset to query again the database to collect all of your data you should really use one query. Also use the using-statement to ensure that the connection gets closed even on error and use sql-parameters to avoid sql-injection issues:
var items = new List<praktikanter>();
string sql = #"SELECT p.*, f. Navn
FROM praktikanter p INNER JOIN forlob f ON p.id = f.praktikantid
WHERE f.firmaid = #firmaid";
using (var con = new MySqlConnection(connectionString))
using (var command = new MySqlCommand(sql, con))
{
command.Parameters.Add(new MySqlParameter("#firmaid", MySqlDbType.VarChar).Value = firmaid);
con.Open();
using (var rd = command.ExecuteReader())
{
while (rd.Read())
{
string praktikant = rd.GetString("Navn");
string fra = rd.GetString("Fra");
string til = rd.GetString("Til");
items.Add(new praktikanter(praktikant, fra, til));
}
}
}

How to generate List<String> from SQL query?

If I have a DbCommand defined to execute something like:
SELECT Column1 FROM Table1
What is the best way to generate a List<String> of the returned records?
No Linq etc. as I am using VS2005.
I think this is what you're looking for.
List<String> columnData = new List<String>();
using(SqlConnection connection = new SqlConnection("conn_string"))
{
connection.Open();
string query = "SELECT Column1 FROM Table1";
using(SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
columnData.Add(reader.GetString(0));
}
}
}
}
Not tested, but this should work fine.
Loop through the Items and Add to the Collection. You can use the Add method
List<string>items=new List<string>();
using (var con= new SqlConnection("yourConnectionStringHere")
{
string qry="SELECT Column1 FROM Table1";
var cmd= new SqlCommand(qry, con);
cmd.CommandType = CommandType.Text;
con.Open();
using (SqlDataReader objReader = cmd.ExecuteReader())
{
if (objReader.HasRows)
{
while (objReader.Read())
{
//I would also check for DB.Null here before reading the value.
string item= objReader.GetString(objReader.GetOrdinal("Column1"));
items.Add(item);
}
}
}
}
Or a nested List (okay, the OP was for a single column and this is for multiple columns..):
//Base list is a list of fields, ie a data record
//Enclosing list is then a list of those records, ie the Result set
List<List<String>> ResultSet = new List<List<String>>();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(qString, connection);
// Create and execute the DataReader..
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var rec = new List<string>();
for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
{
rec.Add(reader.GetString(i));
}
ResultSet.Add(rec);
}
}
If you would like to query all columns
List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
cn.Open();
MySqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
list_users.Add(new Users(dr));
}
}
catch { /* error */ }
finally { cn.Close(); }
The User's constructor would do all the "dr.GetString(i)"
Where the data returned is a string; you could cast to a different data type:
(from DataRow row in dataTable.Rows select row["columnName"].ToString()).ToList();
This version has the same purpose of #Dave Martin but it's cleaner, getting all column, and easy to manipulate the data if you wan't to put it on Email, View, etc.
List<string> ResultSet = new List<string>();
using (SqlConnection connection = DBUtils.GetDBConnection())
{
connection.Open();
string query = "SELECT * FROM DATABASE";
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var rec = new List<string>();
for (int i = 0; i <= reader.FieldCount - 1; i++)
{
rec.Add(reader.GetString(i));
}
string combined = string.Join("|", rec);
ResultSet.Add(combined);
}
}
}
}

Categories

Resources