loop iteration doesnt work like it should - c#

Everything works fine except the labels[i]. The loop is always writing in htmlLabel1 and never in htmlLabel2 etc.
Why does the iteration doesn't work by labels[i] but at Reader.GetValue(i) just fine?
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT number FROM numbers ORDER BY RAND() LIMIT 2; ";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
HtmlLabel[] labels = new HtmlLabel[] {
htmlLabel1,
htmlLabel2,
htmlLabel3
};
for (int i = 0; i < Reader.FieldCount; i++)
{
labels[i].Text = Reader.GetValue(i).ToString();
Console.WriteLine(Reader.GetValue(i).ToString());
}
}
connection.Close();

There is only one field so Reader.FieldCount will return 1 every time.
if you want to loop through rows use the following code
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT number FROM numbers ORDER BY RAND() LIMIT 2; ";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
int i=0;
HtmlLabel[] labels = new HtmlLabel[] {
htmlLabel1,
htmlLabel2,
htmlLabel3
};
while (Reader.Read())
{
//for (int i = 0; i < Reader.FieldCount; i++)
//{
labels[i].Text = Reader[0].ToString();
Console.WriteLine(Reader[0].ToString());
//}
i +=1;
}
connection.Close();

Related

MySqlDataReader error when running the method twice

I have this code. When I execute this once, I am able to get the correct list. But when I run this method again, the reader has no data. I was thinking did I forget to close some connection before calling it again, thus leading to the null result
public IEnumerable<List<string>> retreiveList()
{
string query = "SELECT * FROM table1;";
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader reader;
reader = cmd.ExecuteReader();
while (reader.Read())
{
List<string> toReturn=new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
toReturn.Add(reader[i].ToString());
yield return toReturn;
}
reader.Close();
}

Using for loop to delete data in database

I want to delete every item in the array from the database.
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
for (int i = 0; i <= ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", val);
}
When I run this the line
string val = ids[i];
gives me an error which says:
Index was outside the bounds of the array.
What's wrong with this?
This is my whole code UPDATED
string connString = "Server=192.168.1.100;Database=product;Uid=newuser;Pwd=password";
MySqlConnection conn = new MySqlConnection(connString);
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
try
{
MySqlCommand cmd1 = new MySqlCommand();
conn.Open();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", "");
for (int i = 0; i < ids.Length; i++)
{
string val = ids[i];
cmd1.Parameters[0].Value = val;
cmd1.ExecuteNonQuery();
}
MessageBox.Show("Checkout Successful");
}
Arrays in .NET are zero based and thus the valid indexes go from zero to length - 1.
You should change your code to
for (int i = 0; i < ids.Length; i++)
As pointed by other answer you loop also fails to call cmd1.ExecuteNonQuery and it seems that you don't have associated a connection to the MySqlCommand (thus it will not work at all).
An interesting variation on your code could be to create a single string with all of your commands and submit the command just one time.
Beware that this is not recommended unless you are absolutely sure that your ID are just numbers and not coming from user input
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= ids.Length; i++)
sb.AppendFormat("Delete from tblindividualproduct where ProductID = {0};", ids[i]);
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = sb.ToString();
cmd1.Connection = connection;
cmd1.ExecuteNonQuery();
Array indexes go from 0 up to Length - 1, so you need to stop the loop before i == ids.Length. Try replacing the <= with <. Also, don't forget to call ExecuteNonQuery to execute your command.
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand(conn);
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#p1", val);
cmd1.ExecuteNonQuery();
}
You can also set up the command outside of the loop and only set the parameter and execute the command inside the loop:
MySqlCommand cmd1 = new MySqlCommand(conn);
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#p1", "");
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
cmd1.Parameters[0].Value = val;
cmd1.ExecuteNonQuery();
}
This will be much more efficient as there's only one call to the DB, plus there's no need anymore to iterate through yours ids collection.
string[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID IN (" + String.Join(",", ids) + ")";
Your index goes from 0 to your length -1 like this:
tring[] ids = dt.AsEnumerable()
.Select(row => row["ProductID"].ToString())
.ToArray();
for (int i = 0; i < ids.Length; i++) {
string val = ids[i];
MySqlCommand cmd1 = new MySqlCommand();
cmd1.CommandText = "Delete from tblindividualproduct where ProductID = #p1";
cmd1.Parameters.AddWithValue("#p1", val);
}
And Index was outside the bounds of the array. means that your accessed an element that does not exist with that index.

How do multi rows insert with MySqlCommand and prepare statement?(#C)

Mysql give example how insert rows with prepare statement and .NET:
http://dev.mysql.com/doc/refman/5.5/en/connector-net-programming-prepared.html
Its looks that its works like that,because in the end of each iteration call to:cmd.ExecuteNonQuery():
INSERT INTO VALUES()...;INSERT INTO VALUES()...;INSERT INTO VALUES()...;
Can it done with use of prepare statement like that:
INSERT INTO all values...
More explanations::
The code in mysql example (cmd.ExecuteNonQuery() in each iteration):
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = strConnection;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#number", 1);
cmd.Parameters.AddWithValue("#text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["#number"].Value = i;
cmd.Parameters["#text"].Value = "A string value";
cmd.ExecuteNonQuery();
}
}
*The code that i want to have like that(cmd.ExecuteNonQuery(); after all iterations): *
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
conn = new MySql.Data.MySqlClient.MySqlConnection();
cmd = new MySql.Data.MySqlClient.MySqlCommand();
conn.ConnectionString = strConnection;
try
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#number", 1);
cmd.Parameters.AddWithValue("#text", "One");
for (int i=1; i <= 1000; i++)
{
cmd.Parameters["#number"].Value = i;
cmd.Parameters["#text"].Value = "A string value";
}
cmd.ExecuteNonQuery();
}
Try this:
using (var connection = new MySqlConnection("your connection string"))
{
connection.Open();
// first we'll build our query string. Something like this :
// INSERT INTO myTable VALUES (NULL, #number0, #text0), (NULL, #number1, #text1)...;
StringBuilder queryBuilder = new StringBuilder("INSERT INTO myTable VALUES ");
for (int i = 0; i < 10; i++)
{
queryBuilder.AppendFormat("(NULL,#number{0},#text{0}),", i);
//once we're done looping we remove the last ',' and replace it with a ';'
if (i == 9)
{
queryBuilder.Replace(',', ';', queryBuilder.Length - 1, 1);
}
}
MySqlCommand command = new MySqlCommand(queryBuilder.ToString(), connection);
//assign each parameter its value
for (int i = 0; i < 10; i++)
{
command.Parameters.AddWithValue("#number" + i, i);
command.Parameters.AddWithValue("#text" + i, "textValue");
}
command.ExecuteNonQuery();
}

Index was outside the bounds of the array in c#

I want to insert MySqlDataReader read value into an array.but I get the exception "Index was outside the bounds of the array". Here is my code,
string[] a = new string[1000];
string myconstring = "SERVER=localhost;" + "DATABASE=alicosms;" + "UID=root;" + "PASSWORD=;";
MySqlConnection mycon = new MySqlConnection(myconstring);
string sql = "SELECT flag FROM sms_data_bankasia group by flag";
MySqlCommand comd = mycon.CreateCommand();
comd.CommandText = sql;
mycon.Open();
MySqlDataReader dtr = comd.ExecuteReader();
count = 0;
int i = 0;
while (dtr.Read())
{
a[i] = dtr.GetValue(i).ToString();
i++;
}
What can I do.Any one can help me?
Try cleaning your code a little and use a dynamically resizing List<T> to which you can add elements:
var result = new List<string>();
var myconstring = "SERVER=localhost;DATABASE=alicosms;UID=root;PASSWORD=;";
using (var con = new MySqlConnection(myconstring))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT flag FROM sms_data_bankasia group by flag";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(reader.GetString(reader.GetOrdinal("flag")));
}
}
}
string[] a = result.ToArray();
This looks suspicious to me:
a[i] = dtr.GetValue(i).ToString();
That means you're fetching column 0 of row 0, column 1 of row 1, column 2 of row 2 etc... but you've only got a single column ("flag").
I suspect you meant:
a[i] = dtr.GetValue(0).ToString();
That will still fail if there are more than 1000 rows though - it would be better to use a List<string>:
List<string> data = new List<string>();
while (dtr.Read())
{
data.Add(dtr.GetValue(0).ToString()); // Or call GetString
}

Show databases of MySql server

Does anybody know, how to show databases in C#? I know thats possible by executing a sql command show databases, but i dont know how to configure reader. Anybody please help me.
EDIT: I found a solution:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MySqlConnection con = new MySqlConnection(this.constr);
MySqlCommand cmd = con.CreateCommand();
cmd.CommandText = "show databases";
try
{
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string row = "";
for (int i = 0; i < reader.FieldCount; i++)
row += reader.GetValue(i).ToString();
listBox1.Items.Add(row);
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Number.ToString());
MessageBox.Show(ex.Message);
}
}
string myConnectionString = "SERVER=localhost;UID='root';" + "PASSWORD='root';";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SHOW DATABASES;";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string row = "";
for (int i = 0; i < Reader.FieldCount; i++)
row += Reader.GetValue(i).ToString() + ", ";
comboBox1.Items.Add(row);
}
connection.Close();
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand com = new SqlCommand ("show databases",conn);
conn.Open();
SqlDataReader reader = com.ExecuteReader();
DataTable dt = new DataTable;
dt.Load(reader);
DataRows[] rows = dt.Rows;
Think you can then view the data rows
That said, if you already have the connection string, there's no reason not to open MSqlServer or whatever and view it from there...

Categories