I am getting these records from database MySql version 8.0.17
+-------------------------+
| TABLE_NAME |
+-------------------------+
| t_contents_s300_1_2021 |
| t_contents_s34d_1_2021 |
| t_contents_s34g_1_2021 |
| t_contents_s3sv_1_2021 |
+-------------------------+
and I used MySqlDataReader to read those records as follows
MySqlDataReader reader = cmd.ExecuteReader();
// in reader, I have records which comes from database.
while(reader.Read())
{
string [] arpp_pro = new string[] {reader["TABLE_NAME"].ToString()};
}
everything works fine...
But I need assigning these values of string [] arpp_pro in array for execute single query INSERT INTO on new table for each values from TABLE_NAME
How to solve this problem.
How can I get all records in array from TABLE_NAME?
Thanks in advance for any help
I think you want to construct a list:
MySqlDataReader reader = cmd.ExecuteReader();
List<string> arpp_pro = new List<string>(); // define a list outside of the loop
while(reader.Read())
{
// for each row from the database, add the retrieved table name to the list
arpp_pro.Add(reader["TABLE_NAME"].ToString());
}
// code to dos something with arpp_pro here.
I also recommend using the using keyword with your reader to ensure that it's closed/disposed when you are done with it. Example:
List<string> arpp_pro = new List<string>(); // define a list outside of the loop
using(MySqlDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
// for each row from the database, add the retrieved table name to the list
arpp_pro.Add(reader["TABLE_NAME"].ToString());
}
}
If you really need it as an array, you can call string[] arpp_pro_array = arpp_pro.ToArray(); to convert the list to an array. You will need using System.Linq; at the top of your code file for this to work, as ToArray is a LINQ extension method.
Related
I'm trying to find a way to have access to all the values in a row.
The following code returns one cell. If I change select id to select *, I have access to the row but how can I break it apart?
string find_user = "select id from users where userName = '" + un + "'";
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlCommand cmd = new SqlCommand(find_user, con))
{
con.Open();
user_id = cmd.ExecuteScalar().ToString();
/* use to pass the info to all the pages */
Session.Add("u_id", user_id);
}
}
You cannot access additional columns using .ExecuteScalar(), per the docs:
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
Although it is not a route that I would recommend, you can iterate through the fields by using an index on a data reader:
SqlDataReader dataReader = cmd.ExecuteReader();
// for the query's result set, this while loop will go through all the records
while (dataReader.Read())
{
// for the current record, this for loop will go through all the fields
for (int i = 0; i < dataReader.FieldCount; i++)
{
var value = dataReader[i]; // do what you need with the data here
}
}
A better approach would be to specify the field names in the SQL query instead of using SELECT *, then get the values from the data reader by the specific field names (not relying on the order of the fields in the DB).
Also, you have a SQL injection vulnerability. You should look up what this means and how to parameterize a query.
My issue is that the results are empty when executing the statement, even though when executing it in Microsoft's SQL server studio it works.
//This has two values in it (Ex: 4 and 2)
string[] arr2 = groupListValues.Split('-');
List<string> userID = new List<string>();
// Connect to the database
SqlConnection gconn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectinfohere"].ConnectionString);
gconn.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = gconn;
String sql = "SELECT ID FROM Users WHERE Group = #groupID";
command1.CommandText = sql;
command1.Parameters.Add(new SqlParameter("#groupID", ""));
SqlDataReader reader = command1.ExecuteReader();
//issue is in this loop
foreach (string str in arr2)
{
command1.Parameters["#groupID"].Value = str;
while (reader.Read())
{
userID.Add(reader["ID"].ToString());
}
}
Not sure what the issue is. The "ID" I'm getting in the SQL statement is of type bigint, could that cause an issue?
The reason I am setting the parameter inside the foreach loop is because, for each value in arr2 corresponds to a group that several users could be attached to. So I need to loop through that, get the users attached to each groupID, then add all their ID's to a list.
There are two problems with you code:
The first one is that you setting the #groupID parameter after you execute the reader. To fix it, execute the reader after you set the parameter value like this:
foreach (string str in arr2)
{
command1.Parameters["#groupID"].Value = str;
using(SqlDataReader reader = command1.ExecuteReader())
{
while (reader.Read())
{
userID.Add(reader["ID"].ToString());
}
}
}
The second problem is that Group is a reserved keyword in SQL, so you need to wrap it with square brackets like this:
String sql = "SELECT ID FROM Users WHERE [Group] = #groupID";
I'm trying to display the number of records in the data reader. Here's what I tried.
if (mybtnreader1.HasRows)
{
using (DataTable dt = new DataTable())
{
dt.Load(mybtnreader1);
int rc = dt.Rows.Count;
MessageBox.Show("Have "+rc+"records");
}
}
Though it has records it is always displaying 0. How should it be corrected or is there any other way to get the number of records in a data reader?
I'm using this code to display the data.
while(mybtnreader1.Read())
{
MessageBox.Show(mybtnreader1.GetValue(0) + " "+mybtnreader1.GetValue(1)+" ");
}
It is showing the data but when it comes to the number of records it is displaying 0.
After looping through the results of your query you can use RecordsAffected:
mybtnreader1 = command.ExecuteReader();
while(mybtnreader1.Read())
{
///do your stuff
}
mybtnreader1 .Close();
MessageBox.Show(mybtnreader1 .RecordsAffected.ToString());
A DataReader is forward-only read-only so you can't get the number of records before looping through them all. While you loop through you can count, but not before.
If you need to know the number of records ahead of time and want the performance and memory advantages of a DataReader, then change your query to run two queries.. first the same underlying query with a select count(*)... and then the actual query. Depending on the query, this will obviously affect performance. It won't be double the time due to caching, but is additional processing time. You'll have to weigh the need for having the count ahead of time vs the advantages of using a DataReader vs a DataTable.
For example, if you're querying every record from a table like this:
string sql = "SELECT * FROM MyTable";
using(var dataReader = ...)
Then you can do this instead:
string sql = #"
SELECT COUNT(*) FROM MyTable;
SELECT * FROM MyTable;
};
using(var dataReader = ...)
{
... process first result in data reader (count) ...
if (dataReader.NextResult)
{
... process the second result (records) ...
}
}
You cannot do it directly with Datareader. you can do it like below -
SqlDataReader reader = command.ExecuteReader();
DataTable dt_results = new DataTable();
dt_results.Load(reader);
int count= dt_results.Rows.Count;
if(count>0)
{
//Hey! we Have records for this query
}
else{
//Sorry! No Records Exist for this query
}
basically what I want to do is read data from the table and then add that data to the appropriate list.
For example
List<int> value;
SELECT Values_To_Add FROM table
value.add(Values_To_Add)
Obviously using the correct C# MySql syntax. How should I go about doing this?
I think something like the below might what you are looking for:
List<int> values = new List<int>();
string sql = "SELECT Values_To_Add FROM table";
command.CommandText = sql;
MySqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
values.Add(reader["Values_To_Add "]);
}
You might what to Google about setting up MySqlReader etc.
Hope this helps, it should be a start.
try
List<int> values;
var result = from value in table
select value;
foreach(var item in result) values.Add(item);
Look into using the SQLDataReader Class.
After researching you should be able to use the data reader to read in rows from your table and subsequently add them to your list :)
Tutorial: http://csharp-station.com/Tutorial/AdoDotNet/Lesson04
MSDN: http://msdn.microsoft.com/en-GB/library/system.data.sqlclient.sqldatareader.aspx
I have never learned this aspect of programming, but is there a way to get each separate result of a excel query(using OleDB) or the likes.
The only way I can think of doing this is to use the INTO keyword in the SQL statement, but this does not work for me (SELECT attribute INTO variable FROM table).
An example would be to use the select statement to retrieve the ID of Clients, and then compare these ID's to clientID's in a client ListArray, and if they match, then the clientTotal orders should be compared.
Could someone prove some reading material and/or some example code for this problem.
Thank you.
This code fetches rows from a sql procedure. Will probably work for you too with some
modifications.
using (var Conn = new SqlConnection(ConnectString))
{
Conn.Open();
try
{
using (var cmd = new SqlCommand("THEPROCEDUREQUERY", Conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
// Find Id of column in query only once at start
var Col1IdOrd = reader.GetOrdinal("ColumnName");
var Col2IdOrd = reader.GetOrdinal("ColumnName");
// loop through all the rows
while (reader.Read())
{
// get data for each row
var Col1 = reader.GetInt32(ColIdOrd);
var Col2 = reader.GetDouble(Col2IdOrd);
// Do something with data from one row for both columns here
}
}
}
finally
{
Conn.Close();
}