Reputation: 7
I have a table named-"dbo.COM_ConnectionLogRfmDevices"
in sql server 2008.
The table contains 7 columns named as follows:-
CL_ID,CL_UnitNumber,CL_RemoteIP,CL_RemotePort,CL_RecDateTime,CL_GPRS,CL_COM.
CL_UnitNumber
contains unitnumber as follows:-
352964054838728
352964054868972
352964054839296
352964054868881
I want to store the content of only column-2 i.e CL_UnitNumber value in string[] array
.
Connection string:-
string _ConnectionString = "Data Source=192.168.1.60;" +
"Initial Catalog=OLTP_MTEL_DEVICES; User ID=sa; Password=pass,123;";
Upvotes: 0
Views: 75
Reputation: 14470
var arr = new List<string>();
var connectionString= "YOUR CONNECTION";
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT CL_UnitNumber FROM COM_ConnectionLogRfmDevices", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
arr.Add(reader["CL_UnitNumber"] != DBNull.Value
? reader["CL_UnitNumber"].ToString()
: "");
}
}
}
return arr.ToArray();
Upvotes: 0
Reputation: 9725
If you need to dynamically size an array I would use a List instead...
List<string> unitNumbers = new List<string>();
using (SqlConnection con = new SqlConnection(_ConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT CL_UnitNumber FROM COM_ConnectionLogRfmDevices", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
unitNumbers.Add(reader.GetInt32(0)); // Or maybe reader.GetString(0)
}
}
}
Upvotes: 1
Reputation: 5063
Since you mentioned SQL, I guess you are wanting to handle this using raw SQL commands. Something like below should get you started.
string[] allRecords = null;
string sql = @"SELECT CL_UnitNumber
FROM some table";
using (var command = new SqlCommand(sql, connection))
{
con.Open();
using (var reader = command.ExecuteReader())
{
var list = new List<string>();
while (reader.Read())
list.Add(reader.GetString(0));
allRecords = list.ToArray();
}
}
Upvotes: 0
Reputation: 5307
Check this post out. Drop Entity Framework into your app and you can connect to you database and extract out your data in minutes. Very painless.
Entity Framework - Get Started
Upvotes: 0