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

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

Related

SQLite select where clause not working when a String value compared with database value in c#

The select query is not working in the below case.
string sssss = "InspectorADEL2018 -11-13";
con.Open();
String value1 = "select * from finalreport where rmid='"+sssss+"'; ";
SQLiteCommand cmd13 = new SQLiteCommand(value1, con);
dr13 = cmd13.ExecuteReader();
while (dr13.Read())
{
Console.WriteLine("The command executed");
}
con.Close();
But when we tried the below one the query works and get the output.
con.Open();
String value1 = "select * from finalreport where rmid='InspectorADEL2018 -11-13'; ";
SQLiteCommand cmd13 = new SQLiteCommand(value1, con);
dr13 = cmd13.ExecuteReader();
while (dr13.Read())
{
Console.WriteLine("The command executed");
}
con.Close();
How can I solve the problem when we assign the value to a string variable?
DatabaseUtils.sqlEscapeString(String)
https://developer.android.com/reference/android/database/DatabaseUtils
this worked for me
string sssss = "InspectorADEL2018 -11-13";
ssss = ssss.Replace("\n", "");

OleDb returning System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.' when using paramaterized SQL

I keep getting System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.' but i am giving it a value as you can see in my code:
private void PopWeapSel(string[] read)
{
string[] weapID = read;
string weapDam = "";
string weapPat = "";
string weapHeat = "";
string weapName = "";
OleDbConnection dbConn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BHShooterProjectDB.accdb");
string sql = "SELECT ItemWeaponType.WeaponID, ItemWeaponType.WeaponDamage, ItemWeaponType.WeaponPattern, ItemWeaponType.WeaponHeatValue, ItemWeaponType.WeaponCoolRate, ItemWeaponType.WeaponName FROM ItemWeaponType WHERE ItemWeaponTypeWeaponID = #PU;";
OleDbCommand cmd = new OleDbCommand(sql, dbConn);
foreach (string WeapID in weapID)
{
if (WeapID == "")
{
return;
}
cmd.Parameters.AddWithValue("#PU", WeapID); ///Problem Line
dbConn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
weapDam = reader[1].ToString();
weapPat = reader[2].ToString();
weapHeat = reader[3].ToString();
weapName = reader[4].ToString();
}
dbConn.Close();
this.DGV_WS.Rows.Add(weapDam, weapPat, weapHeat, weapName);
}
}
When i look at the locals in the locals in debug. WeapID has a value of "1" as it should. Have i missed something in terms of syntax?
Thanks!
Move your OleDbCommand cmd = new OleDbCommand(sql, dbConn); line inside the foreach statement.
You are using the same command over and over, and adding more parameters than the query has.

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.

Getting unknown data from SQL Server using SqlDataReader

I use this code for getting data from SQL Server:
string rootname = "[" + nameroot + "]";
string retVal = "";
string constring = "Data Source =(Local);Initial Catalog=Tajari;Integrated Security=True;";
SqlConnection conobj = new SqlConnection(constring);
string commandtext = "select distinct " + rootname + " from TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
//retVal = dr[nameroot].ToString();
}
conobj.Close();
Now I need this data inserted into a variable or textbox.
The problem is that my values are unknown
Solution 1 :
You can use Index value.
Try This:
while (dr.Read())
{
retVal = dr[0].ToString();
}
Solution 2 :
You can also use alias name.
string commandtext = "select distinct " + rootname + " as myrootname from
TBLJobsRootName where MenuId between 1 and " + countroot + "";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
retVal = dr["myrootname"].ToString();
}
Suggestion: Your Query is open to SQL Injection Attacks i would suggest you to use Parameterised Queries to avoid them.
Solution 3: Using Parameterised Queries
if you want to add all rootname values you need to add all values to List.
List<string> list = new List<string>();
string commandtext = "select distinct "+rootname+" as myrootname from
TBLJobsRootName where MenuId between 1 and #countroot";
SqlCommand comobj = new SqlCommand(commandtext, conobj);
comobj.Parameters.AddWithValue("#countroot",countroot);
conobj.Open();
SqlDataReader dr = comobj.ExecuteReader();
while (dr.Read())
{
lis.Add(dr["myrootname"].ToString());
}
//You can retunrn list

C# MySql Storing multiple database rows in 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();

Categories

Resources