C# MySql Storing multiple database rows in C# - c#

I'm struggling a bit with this. I want to get the list of ids from the database where a certain value is equal to a certain value in the row. This call will likely return multiple ids. I want to store the value in the ids returned in a list or arraylist in the c# code but I am finding this troublesome. I have the code up to here:
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers + "";
connection.Open();
reader = command.ExecuteReader();
Any help would be much appreciated

string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
List<string> array = new List<string>();
using (MySqlCommand cmd = new MySqlCommand("SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers, connection))
{
try
{
using (MySqlDataReader Reader = cmd.ExecuteReader())
{
while (Reader.Read())
{
array.Add(Reader["idprojects"].ToString());
}
}
}
catch (Exception ex)
{
throw;
}
}
string[] ret= array.ToArray();

Related

Display into textbox using if sentence

I'm displaying some data from the database into textboxes on my windows form and I have to add something else but it depends on the account type (that information is saved on my Databse). Meaning it is either DM (domestic) or CM(comercial). I want for it to charge an extra amount if it's CM.
I would appreciate any help, thank you.
OracleDataReader myReader = null;
OracleCommand myCommand = new OracleCommand("SELECT SUM(IMPORTE) AS corriente FROM MOVIMIENTOS WHERE CUENTA='"+txtIngreseCuenta3.Text + "'AND CONCEPTO=10", connectionString);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtCorriente.Text = (myReader["corriente"].ToString());
}
I'm using this code to display into the textbox but I want it to get the account type from another table and IF it's CM then add a certain amount into a textbox.
In your case I suggest that you use Execute Scalar instead of reader since you are returning only one value from the database. but in your case if you want this code to work you need to Cast the returned value into the correct dot net type and then populate the TextBox.
Example Using ExecuteReader
//txtCorriente.Text = ((int)myReader["corriente"]).ToString();
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtCorriente.Text = ((int)reader["corriente"]).ToString();
txtAnother.Text = ((decimal)reader["another"]).ToString();
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Example Using ExecuteScalar
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}

Exception: Invalid attempt to Read when reader is closed

I am trying to update my database while reading data from it, but the reader gets closed and it throws the exception that it can''t read wen reader is closed. Is the update.ExecuteNonQuery() closing the reader method?
If i get rid of linescon.Close(); con.Open(); i get There is already an open DataReader associated with this Connection which must be closed first.
So how can i update my database records while keep the reading opened?
{
public class MySqlReadUpdate
{
public int Id { get; set; }
public string Notes { get; set; }
}
static void Main()
{
List<MySqlReadUpdate> dbData = new List<MySqlReadUpdate>();
var config = "server=localhost;user id=root; database=restaurants; pooling=false;SslMode=none;Pooling=True";
MySqlConnection con = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT id, notes FROM customers";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
MySqlReadUpdate newMySqlReadUpdate = new MySqlReadUpdate();
newMySqlReadUpdate.Id = (int)reader["id"];
newMySqlReadUpdate.Notes = (string)reader["notes"];
string note = newMySqlReadUpdate.Notes;
var notesplit = note.Split(' ', '\n')[1];
dbData.Add(newMySqlReadUpdate);
Console.WriteLine(newMySqlReadUpdate.Id);
Console.WriteLine(newMySqlReadUpdate.Notes);
Console.WriteLine(note);
Console.WriteLine(notesplit);
con.Close();
con.Open();
string query2 = "UPDATE customers SET notes='" + notesplit + "' WHERE id='" + newMySqlReadUpdate.Id + "';";
MySqlCommand update = new MySqlCommand(query2, con);
update.ExecuteNonQuery();
}
con.Close();
Console.WriteLine("Finished!");
Console.Read();
}
}
}
You cannot close a connection like you are, because the data reader depends on it. Once you call con.Close you break it. That's why you see an exception the next time it gets to reader.Read().
What you want is to add MultipleActiveResultSets=True in the configuration string; however, as we discussed in the comments it's apparently still not supported in MySQL. Therefore, the answer is two connection instances.
List<MySqlReadUpdate> dbData = new List<MySqlReadUpdate>();
var config = "server=localhost;user id=root;database=restaurants;pooling=false;SslMode=none";
MySqlConnection con = new MySqlConnection(config);
MySqlConnection cmdCon = new MySqlConnection(config);
MySqlDataReader reader = null;
string query = "SELECT id, notes FROM customers";
MySqlCommand command = new MySqlCommand(query, con);
con.Open();
cmdCon.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
MySqlReadUpdate newMySqlReadUpdate = new MySqlReadUpdate();
newMySqlReadUpdate.Id = (int)reader["id"];
newMySqlReadUpdate.Notes = (string)reader["notes"];
string note = newMySqlReadUpdate.Notes;
var notesplit = note.Split(' ', '\n')[1];
dbData.Add(newMySqlReadUpdate);
Console.WriteLine(newMySqlReadUpdate.Id);
Console.WriteLine(newMySqlReadUpdate.Notes);
Console.WriteLine(note);
Console.WriteLine(notesplit);
string query2 = "UPDATE customers SET notes='" + notesplit + "' WHERE id='" + newMySqlReadUpdate.Id + "';";
MySqlCommand update = new MySqlCommand(query2, cmdCon);
update.ExecuteNonQuery();
}
con.Close();
cmdCon.Close();
Console.WriteLine("Finished!");
Console.Read();
I would recommend that you also modify your code to use using statements or wrap things in try-finally blocks.

named pipes provider, error: 40 c#

I keep getting this error when I try to get a result from a query as a list. I can connect to the database if I try to get 1 result.
The code is:
string connectionString = "server=ip;uid=root;pwd=pass;database=database;";
string queryString = "SELECT pass_name FROM passStore";
List<string> tempList = new List<string>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
tempList.Add(reader[0].ToString() + " " + reader[1].ToString());
}
}
reader.Close();
}

Populate a number of DropDownLists with MySQL reader

I have 10 DropDownLists (ddlQuestion1IDs, ddlQuestion2IDs, ddlQuestion3IDs...) that I want to populate with data from a database. However, the following code only populates ddlQuestion1IDs. Why is this and what's the most efficient way to populate all 10 with the same data?
protected void getQuestionIDs()
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
MySqlDataReader reader;
string cmdText = "SELECT * FROM questions WHERE module_id=#ModuleID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = ddlModules.SelectedValue;
try
{
conn.Open();
reader = cmd.ExecuteReader();
for (int i = 1; i <= 10; i++)
{
var ddlQuestion = (DropDownList)FindControl("ddlQuestion" + i.ToString() + "IDs");
ddlQuestion.DataSource = reader;
ddlQuestion.DataValueField = "question_id";
ddlQuestion.DataTextField = "question_id";
ddlQuestion.DataBind();
ddlQuestion.Items.Insert(0, new ListItem(string.Empty, "blank"));
}
reader.Close();
}
catch
{
lblError.Text = "Database connection error - failed to get question IDs.";
}
finally
{
conn.Close();
}
}
My wild-ass-guess is that the reader is stream-based, forward-only and the first bind successfully iterates over the data while the subsequent binds find the data stream to be at the end.
I would try copying the data into an array and try binding to the array. Here's a question that might be helpful.
Can I reset and loop again through MySqlDataReader?

How can I get the value of 2 columns, not only one?

I want the result of two columns and not only one. I tried:
MessageBox.Show(reader.GetString("traceid", "idref"));
But it does not work. I am a beginner with C#, can anyone please help?
String str = #"server=localhost;database=asianimport;userid=tera;password=******;";
MySqlConnection con = null;
try
{
con = new MySqlConnection(str);
con.Open(); //open the connection
MessageBox.Show("connect " );
String cmdText = "SELECT * FROM tracerecord limit 3";
MySqlCommand cmd = new MySqlCommand(cmdText, con);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader.GetString("traceid", "idref"));
}
}
Do a GetString() twice, one per field:
while (reader.Read())
{
String traceID = reader.GetString("traceid");
String idRef = reader.GetString("idref");
MessageBox.Show(traceID + " - " + idRef);
}
reader.GetString() returns the result from only one column of your current record. Use them separatly for each colunm with concatanation:
MessageBox.Show(reader.GetString("traceid")+ " "+reader.GetString("idref"));

Categories

Resources