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];
}
}
}
}
}
Related
I am getting this error when I insert data from a gridview, I am inserting data into order details where I want to save same order ID with every order item but could not. I am developing in C# windows. I have search the web but that couldn't solve my problem. I am stuck at this point. Any help is appreciated.
I am adding my code lines that I am doing.
Kind regards
SqlCommand cmd1 = con.CreateCommand();
cmd1.CommandType = CommandType.Text;
cmd1.CommandText = "SELECT Top 1 * FROM Purchase_Order Order By P_Order_ID desc";
cmd1.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter sda2 = new SqlDataAdapter(cmd1);
sda2.Fill(dt);
int OrderID = 0;
foreach (DataRow dr2 in dt.Rows)
{
OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());
MessageBox.Show("order id +" +OrderID);
}
SqlCommand com2 = new SqlCommand();
com2.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
foreach (DataRow dr2 in dt.Rows)
{
OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());
}
string Query;
Query = #"INSERT INTO Purchase_Order_Detail (P_Order_ID, ProductID, PSC_ID, Pack_ID, Color, Base_ID, Quantity) VALUES (#OrderID, #ProductID, #Sub_ID, #PackID, #Colors, #BaseID, #Quantity);";
// com2.Parameters.Add("#OrderID" & dataGridView1.Rows(i).ToString(), dataGridView1(i));
com2.Parameters.AddWithValue("#OrderID", OrderID);
com2.Parameters.AddWithValue("#ProductID", dataGridView1.Rows[i].Cells[4].Value);
com2.Parameters.AddWithValue("#Sub_ID", dataGridView1.Rows[i].Cells[6].Value);
com2.Parameters.AddWithValue("#PackID", dataGridView1.Rows[i].Cells[8].Value);
com2.Parameters.AddWithValue("#Colors", dataGridView1.Rows[i].Cells[9].Value);
com2.Parameters.AddWithValue("#BaseID", dataGridView1.Rows[i].Cells[11].Value);
com2.Parameters.AddWithValue("#Quantity", dataGridView1.Rows[i].Cells[13].Value);
com2.CommandText = Query;
com2.ExecuteNonQuery();
//com2.Parameters.Clear();
}
You are trying to re-add a parameter which is already added to the SqlCommand. In your case you should add the parameters (and the query) before the for() loop and then fill these parameters with the new values for execution.
SqlCommand com2 = new SqlCommand();
com2.Connection = con;
com2.CommandText = #"INSERT INTO Purchase_Order_Detail (P_Order_ID,ProductID,PSC_ID,Pack_ID,Color,Base_ID,Quantity) VALUES (#OrderID,#ProductID,#Sub_ID, #PackID,#Colors,#BaseID,#Quantity);";
com2.Parameters.Add("#OrderID", ...type...);
com2.Parameters.Add("#ProductID", ...type...);
com2.Parameters.Add("#Sub_ID", ...type...);
com2.Parameters.Add("#PackID", ...type...);
com2.Parameters.Add("#Colors", ...type...);
com2.Parameters.Add("#BaseID", ...type...);
com2.Parameters.Add("#Quantity", ...type...);
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
foreach (DataRow dr2 in dt.Rows)
{
OrderID = Convert.ToInt32(dr2["P_Order_ID"].ToString());
}
com2.Parameters["#OrderId"].Value = OrderId;
com2.Parameters["#ProductID"].Value = dataGridView1.Rows[i].Cells[4].Value;
...
com2.ExecuteNonQuery();
}
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]);
}
}
}
}
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]);
}
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