Working with C# and MySQL here (Visual Studio 12 and MySQL workbench 6.1).
I'm trying to get the entire table into a list.
This is what I have so far:
List<Object> arrList = new List<Object>();
string str = #"server=localhost;database=test;userid=root;password=asd;";
MySqlConnection con = new MySqlConnection(str);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
arrList.Add(reader["* "]);
}
When I pass SELECT * FROM emp; for query and try to get a toString of arrList, I get an indexOutOfBounds exception. (My table emp has 1 record in it.)
Thanks!
Edit: I'm trying to get the entire table (sequentially) into a list. Is this the right approach?
Edit 2: What if we don't know the number of columns in the table?
Change to:
while (reader.Read())
{
arrList.Add(reader["myColumnTitle"].ToString());
}
cause "* " isn't a valis columnname. alternative you can use an index
arrList.Add(reader[0].ToString());
for each Column:
List arrList = new List();
string str = #"server=localhost;database=test;userid=root;password=asd;";
string query = "SELECT * FROM emp";
MySqlConnection con = new MySqlConnection(str);
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.CommandText = query;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
var value = reader[i];
arrList.Add(Convert.ToString(value))
}
}
reader.Read() read your results row by row. That means inside this while statement, you need to read all columns of your query.
When you write "* ", your reader looks for a column named * which you don't have. MySqlDataReader can't understand to read all columns when you write * as you can in an sql query.
This should work.
while (reader.Read())
{
arrList.Add((string)reader[0]);
arrList.Add((string)reader[1]);
}
If you really don't know how many fields that your MySqlDataReader has, you can use SqlDataReader.FieldCount property.
Gets the number of columns in the current row.
So you code can be like;
while (reader.Read())
{
for(int i = 0; i < reader.FieldCount; i++)
{
arrList.Add((string)reader[i]);
}
}
Also use using statement to dispose your database connections and objects like;
using(MySqlConnection con = new MySqlConnection(str))
using(MySqlCommand cmd = con.CreateCommand())
{
...
...
using(MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
for(int i = 0; i < reader.FieldCount; i++)
{
arrList.Add((string)reader[i]);
}
}
}
}
Related
I am trying to store all fields from a column in my microsoft access database in an array. I am using OleDb but I don't really know how to go about doing this.
I know that I have to have a loop to go over the table the amount of times as there are rows in the table, but I don't know how to store the current field in the current index of the array.
Any help would be greatly appreciated!
Here is a snippet of some of the code:
string[] tasks;
string sql = "SELECT [Task Name] FROM Tasks";
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataReader dataReader = cmd.ExecuteReader();
if (dataReader.HasRows)
{
for (int i = 1; i <= 10; i++)
{
//tasks[i] = current field in table
}
}
Sounds like you want something like this?
string[] tasks;
string sql = "SELECT [Task Name] FROM Tasks";
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader dataReader = cmd.ExecuteReader())
{
List<object[]> list = new List<object[]>();
if (dataReader.HasRows)
{
while (dataReader.Read())
{
object[] oarray = new object[dataReader.FieldCount];
list.Add(oarray);
for (int i = 1; i <= dataReader.FieldCount; i++)
{
oarray[i] = dataReader[i];
}
}
}
}
}
con.Open();
cmd = new SqlCommand("USE PRODUCTS SELECT BOUGHT FROM " +
DropDownList1.SelectedItem.Text +
" WHERE ID = #ID", con);
cmd.Parameters.Add("ID", SqlDbType.Int).Value = DropDownList2.SelectedIndex;
int i = cmd.ExecuteReader().GetInt32(0);
con.Close();
I can't read integer values with reader like this. I get runtime error System.InvalidOperationException. What is wrong with my code ? if you can't find the mistake, can you explain how can i read integer values with reader ? By the way this part of code gives the error:
int i = cmd.ExecuteReader().GetInt32(0);
Try this:
int x=0;
using (
SqlConnection connection = new SqlConnection(strCon))
{
SqlCommand command = new SqlCommand(sql_string, connection);
connection.Open();
DataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
x = reader.GetInt32(0);
}
}
reader.Close();
}
You need to initialise a reader and then read it
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read()) // or just rdr.Read() if you know only one row is returned
{
int i = rdr.GetInt32(0);
What I have done to make things a lot easier on my end, since I mainly use SQL all over the place, is make some extensions.
eg
public static Int32 GetInt32(this SqlDataReader rdr, string column)
{
return Convert.ToInt32(rdr[column]);
}
I use ExecuteReader to select all (SELECT*) for all field like this
string query = "SELECT* FROM tb_patient_information ";
if (this.OpenConnection() == true)
{ //Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{ ... }
but I only want to select in specific column and cell like in red square.. like this picture
You can get the specific column inside the while clause.
while (dataReader.Read())
{
var _column = dataReader["Nama_Kategori"];
}
Consider using
string query = "SELECT column FROM tb_patient_information ";
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
if (dataReader.Read())
{
dataReader.ExecuteScalar();
}
}
or use dataReader["columnName"]
You can use ExecuteScalar() of MySqlCommand method to retieve single value
MySqlCommand myCommand = new MySqlCommand("SELECT Nama_Kategori FROM tb_patient_information WHERE Id_kategori = 'KI-02'", myConnection);
myCommand.Connection.Open();
myCommand.ExecuteScalar();
myConnection.Close();
SQL Query
If you want only third row data then try the below query :
Select * from (Select row_number() over (order by subssn) as rownum, * FROM
tb_patient_information)result Where rownum = 3
-This Query return the 3rd row on Result Set
In DataReader
while (dataReader.Read())
{
string Id = dataReader["Id_kategori"].ToString();
string Name = dataReader["Nama_Kategori"].ToString();
}
OR
IF You Say I only use Select * from tb_patient_information and i need 3rd row result Then try like below
int count=1;
while (dataReader.Read())
{
if(count == 3)
{
string Id = dataReader["Id_kategori"].ToString();
string Name = dataReader["Nama_Kategori"].ToString();
}
count ++;
}
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);
}
}
}
}
I tried this:
MySqlConnection con = new MySqlConnection(...);
con.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM questions;";
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
int i = 0, len = reader.FieldCount;
while (i < len)
{
Response.Write(reader.GetString(i));
i++;
}
returns only the first values from table. how get all?
thanks in advance
You have to call reader.Read() until it returns false.
I've also taken the liberty of converting your inner loop to a for loop.
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
Response.Write(reader.GetString(i));
}
}
Read this to read up on the IDataReader : http://msdn.microsoft.com/en-us/library/system.data.idatareader.read.aspx