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
}
Related
public void addintovisitor()
{
string companyname = (txtvisitor.Text.ToUpper());
DataSet result = new DataSet();
visitorcompany vc = new visitorcompany();
string Location1 = Convert.ToString(Session["location"]);
vc.checksamecompanyname(ref result, Location1);
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
}
else
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
My visitorcompany class:
public int checksamecompanyname(ref DataSet result, string Location1)
{
string strConn = Convert.ToString(
ConfigurationManager.ConnectionStrings
["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand
("select Companyname from tblVisitorcompany where Location1 ='" + Location1 + "'", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(result, "details");
conn.Close();
//Return 0 when no error occurs.
return 0;
}
I am trying to search one row at a time to check whether the sql table got the same companyname. if there is already exisiting companyname, the program will do nothing. If this is a new companyname, the program will add companyname into the sql table. However, when adding new companyname, the program will add more than once. Can someone please help me to re-edit my program such that it only add one new companyname. Many thanks.
using( var connection = new SqlConnection( "my connection string" ) ) {
using( var command = connection.CreateCommand() ) {
command.CommandText = "SELECT Column1, Column2, Column3 FROM myTable";
connection.Open();
using( var reader = command.ExecuteReader() ) {
var indexOfColumn1 = reader.GetOrdinal( "Column1" );
var indexOfColumn2 = reader.GetOrdinal( "Column2" );
var indexOfColumn3 = reader.GetOrdinal( "Column3" );
while( reader.Read() ) {
var value1 = reader.GetValue( indexOfColumn1 );
var value2 = reader.GetValue( indexOfColumn2 );
var value3 = reader.GetValue( indexOfColumn3 );
// now, do something what you want
}
}
connection.Close();
}
dont use companyname as an argument of your insert command, since it is stays the same in for loop. Use result.Tables["details"].Rows[i]["Companyname"].ToString() instead:
...
cmd.Parameters.AddWithValue("#Companyname", result.Tables["details"].Rows[i]["Companyname"].ToString());
...
Check if the value exists, then add it if not.
A simple change in your code:
bool valueFound = false;
// check if the value exists
for (int i = 0; i < result.Tables["details"].Rows.Count; i++)
{
if (companyname == result.Tables["details"].Rows[i]["Companyname"].ToString())
{
// it exists so we exit the loop
valueFound = true;
break;
}
}
// we have looped all the way without finding the value, so we can insert
if(!valueFound)
{
string strConn = Convert.ToString(ConfigurationManager.ConnectionStrings["connectionstring"]);
SqlConnection conn = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand(
"INSERT INTO tblVisitorcompany ([CompanyName], " +
"[Location1]) " +
"VALUES(#CompanyName, #Location1)", conn);
cmd.Parameters.AddWithValue("#Companyname", companyname);
cmd.Parameters.AddWithValue("#Location1", Location1);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
Off course you could check if the value exists in a more efficient way, but this should at least solve your specific problem.
i am having a hard time to display my count code to my label text. here is my code and please tell me how to solve this problem.
ordering_and_billing.dBase dBase = new ordering_and_billing.dBase();
var mydbconnection = new dBase.dbconnection();
string sql = "SELECT * FROM `order` WHERE eventdate='" + lbldte.Text + "'";
MySqlCommand cmd = new MySqlCommand(sql, mydbconnection.Connection);
mydbconnection.Connection.Open();
MySqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
while (rdr.Read())
{
Int32 count = (Int32)cmd.ExecuteScalar();
string disp = count.ToString();
lblcount.Text = disp;
}
}
just use count function:
string sql = "SELECT COUNT(*) FROM `order` WHERE eventdate='" + lbldte.Text + "'";
also don't use ExecuteReader, use ExecuteScalar function if you want a single value like a count value:
lblcount.Text =cmd.ExecuteScalar().toString();
You should use SELECT COUNT(*) if all you want is the record count.
string sql = "SELECT COUNT(*) FROM `order` WHERE eventdate='" + lbldte.Text + "'";
However, keep in mind that rdr.Read() reads a new row from the sql query. Every time you get a new row, you're trying to rerun the sql command (which I'm guessing crashes) and then assign the count label. So you're trying to assign the count label count times. Use this construct instead:
int count = 0;
while (rdr.Read())
{
count++;
}
lblcount.Text = count.ToString(); //only assigns to the Text property once
never mind guys i got my answer now.
ordering_and_billing.dBase dBase = new ordering_and_billing.dBase();
var mydbconnection = new dBase.dbconnection();
string sql = "SELECT * FROM `order` WHERE eventdate='" + lbldte.Text + "'";
MySqlCommand cmd = new MySqlCommand(sql, mydbconnection.Connection);
mydbconnection.Connection.Open();
MySqlDataReader rdr = cmd.ExecuteReader();
int count = 0;
while (rdr.Read())
{
count ++;
}
lblcount.Text = count.ToString();
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.
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();
}
I'm trying to load a SQL row of numbers into multiple text boxes. Basically the row contains numbers separated by ";". How can I get it so that each number when separated by ";" is in their own textbox?
SqlConnection conn = new SqlConnection("Data Source=LAURA-PC;Initial Catalog=Sudoku;Integrated Security=True");
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select puzzle from Puzzle";
command.CommandType = CommandType.Text;
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
textBox1.Text = reader.GetValue(0).ToString();
textBox2?
textbox3?
}
conn.Close();
Assuming that you have the same amount of (or fewer) numbers than TextBoxes , you could put your TextBoxes into an array and use the following code:
...
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
string[] tokens = reader.GetString(0).Split(';');
for(int i = 0; i < tokens.Length; i++)
{
textBoxes[i].Text = tokens[i];
}
}
...
Assuming the puzzle column has the semi-colon delimited numbers:
...
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
string[] tokens = ((string)reader[0]).Split(';');
textBox1.Text = tokens[0];
textBox2.Text = tokens[1];
// etc...
}
...