Using for loop to delete data in database - c#

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.

Related

loop iteration doesnt work like it should

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();

C# query and string coding error

I tried to get 4 names from first table and check how frequent 4 of the names appeared in each of another 20 groups and then update it on groupevenfrequency. However, I have encountered error on this coding. Appreciate if someone can assist. Thanks.
From this coding, why str[1] and str[2] and str[3] and str[4] is same teachername? But the sql command SELECT DISTINCT is already resulted 4 different teachers. Please advice.
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd = new SQLiteCommand();
cmd = dbConnect.CreateCommand();
cmd.CommandText = "SELECT DISTINCT Teacher_Name from " + myTeacher + " Order by Sum_Weekly_Credit desc LIMIT 4";
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
string[] str = new string[5];
for (int i = 1; i <= 4; i++)
{
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
cmd.ExecuteNonQuery();
}
}
dbConnect.Close();
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd2 = new SQLiteCommand();
cmd2 = dbConnect.CreateCommand();
cmd3 = new SQLiteCommand();
cmd3 = dbConnect.CreateCommand();
for (int j = 1; j <= 20; j++)
{
cmd2.CommandText = "SELECT Subject FROM Group_Even_" + j + " WHERE Teacher_Name = #Teacher_Name1 OR Teacher_Name = #Teacher_Name2 OR Teacher_Name = #Teacher_Name3 OR Teacher_Name = #Teacher_Name4";
cmd2.Parameters.AddWithValue("#Teacher_Name1", str[1]);
cmd2.Parameters.AddWithValue("#Teacher_Name2", str[2]);
cmd2.Parameters.AddWithValue("#Teacher_Name3", str[3]);
cmd2.Parameters.AddWithValue("#Teacher_Name4", str[4]);
DataTable dt2 = new DataTable();
SQLiteDataAdapter da2 = new SQLiteDataAdapter(cmd2);
da2.Fill(dt2);
if (dt2.Rows.Count > 0)
{
int TempCountFrequency = dt2.Rows.Count;
cmd2.CommandText = "UPDATE GroupEvenFrequency SET GroupEven_Frequency = #GroupEven_Frequency WHERE GroupEven_Name = Group_Even_" + j + "";
cmd2.Parameters.AddWithValue("#GroupEven_Frequency", TempCountFrequency);
cmd2.ExecuteNonQuery();
}
else
{
continue;
}
}
The code you have here looks wrong....
for (int i = 1; i <= 4; i++)
{
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
cmd.ExecuteNonQuery();
}
}
Surely you are expecting the dt.Rows to contain the 4 names you are interested in? So why have the outer loop.
So shouldn't it be more like...
string[] str = new string[5];
int i = 1;
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
i++;
}
But as others have pointed out your overall approach could do with a rethink. The code won't cater for the fact that you might not have 4 distinct teacher names

How to use parameters in IN Clause sql informix

How to use parameters in IN Clause sql informix
StringBuilder cmdTxt = new StringBuilder();
cmdTxt.Append(" SELECT COUNT(emp_num) ");
cmdTxt.Append(" FROM tbl1 WHERE year IS NULL AND calc_year = ? AND camp IN (,,,)");
using (var myIfxCmd = new IfxCommand(cmdTxt.ToString(), con))
{
myIfxCmd.CommandType = CommandType.Text;
myIfxCmd.Parameters.Add("calc_year", IfxType.Integer);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
myIfxCmd.Parameters[0].Value = calcYear;
res = int.Parse(myIfxCmd.ExecuteScalar().ToString());
}
I don't know how to handle passing parameters to camp IN (,,,,)//Set of numbers
I've something like this
IDbCommand cmd = connection.CreateCommand(); //connection has been instantiated
cmd.CommandTimeout = connection.ConnectionTimeout;
var query = #"SELECT COUNT(emp_num)
FROM tbl1 WHERE year IS NULL AND calc_year = #year AND camp IN ({0})";
cmd.Parameters.Add(new SqlParameter("#year", calcYear));
var sb = new StringBuilder();
//ids is a list/array of ids i want in the in clause
for (int i = 0; i < ids.Count; i++)
{
sb.AppendFormat("#p{0},", i);
cmd.Parameters.Add(new SqlParameter("#p" + i, ids[i]));
}
if (sb.Length > 0) { sb.Length -= 1; }
string cmdText = string.Format(query, sb.ToString());
cmd.CommandText = cmdText;
cmd.Connection = connection;
var reader = cmd.ExecuteReader();

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
}

Categories