c# Mysql how properly use AND with Where clause - c#

here's my code
int indextest = 0;
MySqlConnection connection = new MySqlConnection(MyConString);
connection.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select backup,Client,No_Projet,Description from historique Where id= #dataID and index= #indexID";
cmd.Parameters.AddWithValue("#dataID", soumissionId.Text);
cmd.Parameters.AddWithValue("#indexID", indextest);
cmd.Connection = connection;
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
Cant figure how format my string form having the and working.
I'm always getting error near index= 0
Can anyone help me please

My SQL uses ` characters to enclose names, you can use them in your query:
cmd.CommandText = "Select `backup`,`Client`,`No_Projet`,`Description` from `historique` Where `id` = #dataID and `index` = #indexID";

Related

Get the value of Count from database rows in ASP.NET web app

The query is correct but I want to access the number of rows and show in the front-end page. This code is throwing an error.
protected void Page_Load(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString_cw"].ConnectionString;
OracleCommand cmd = new OracleCommand();
OracleConnection con = new OracleConnection(constr);
con.Open();
cmd.Connection = con;
cmd.CommandText = #"SELECT COUNT (*) from dish";
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable("Dish");
using (OracleDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows)
{
dt.Load(sdr);
recordMsg.Text = sdr["count(*)"].ToString();
}
}
con.Close();
}
I am using Oracle as database and it is connected already.
As you need a single value there is no use of DataTable and DataReader you can simply use ExcuteScalar of command and get the values.
command.ExecuteScalar();
More Reading https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar?view=dotnet-plat-ext-5.0
or simply
recordMsg.Text=command.ExecuteScalar().ToString();
So the whole code can be written as
string constr = ConfigurationManager.ConnectionStrings["ConnectionString_cw"].ConnectionString;
OracleCommand cmd = new OracleCommand();
OracleConnection con = new OracleConnection(constr);
con.Open();
cmd.Connection = con;
cmd.CommandText = #"SELECT COUNT (*) from dish";
cmd.CommandType = CommandType.Text;
recordMsg.Text=command.ExecuteScalar().ToString();
It is also advisable to use using statement for better use of command and connection.
Use numeric index for the following line of code
recordMsg.Text = sdr["count(*)"].ToString();
Change it to...
recordMsg.Text = sdr[0].ToString();
Or:
Change the two line of code below:
cmd.CommandText = #"SELECT COUNT (*) from dish";
recordMsg.Text = sdr["count(*)"].ToString();
To read
cmd.CommandText = #"SELECT COUNT (*) as rCount from dish";
recordMsg.Text = sdr["rCount"].ToString();
Either option should work well for you.
Note: The numeric index is zero because it's a zero-based index. I trust you understand this

Received values from my SQL query are displayed incorrect in my Listbox

I'm trying to get values out of my database into my Listbox, I currently send all my results into a new object called Results
I want my listbox to show something like this:
Title(1)(enter)
Url(1)(enter)
Title(2)(enter)
Url(2)(enter)
and so on
It currently still gives an error at OleDbDataReader reader = command.ExecuteReader(); but I have no idea why.
This is the exact code
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\martijn\Dropbox\Proftaak Periode 2 Identity\Database11.accdb;
Persist Security Info=False;";
connection.Open();
OleDbCommand cmd1 = new OleDbCommand();
cmd1.Connection = connection;
cmd1.CommandText = "SELECT ZoekcriteriaID from Zoekcriteria WHERE ZoekCriteria = '" + Convert.ToString(lbzoektermen.SelectedItem) + "';";
OleDbDataReader reader1 = cmd1.ExecuteReader();
if(reader1.Read())
{
resultaatid = Convert.ToInt32(reader1["ZoekcriteriaID"]);
}
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT Titel, Webadress from Resultaat WHERE ZoekriteriaID = '"+ resultaatid +"';";
OleDbDataReader reader = command.ExecuteReader();
lbresultaten.Items.Clear();
List<Results> resultaten = new List<Results>();
while(reader.Read())
{
Results result = new Results();
result.url = Convert.ToString(reader["Webadress"]);
result.titel = Convert.ToString(reader["Webadress"]);
resultaten.Add(result);
}
foreach(Results result in resultaten )
{
lbresultaten.Items.Add(result.titel);
lbresultaten.Items.Add(result.url);
}
I hope someone could help me,
Kind Regards,
Martijn
Your problem probably lays in your where clause:
SELECT ZoekcriteriaID from Zoekcriteria WHERE **ZoekCriteria**
It should be a column name, not a table name.

MySQL select query with parameter

I am trying to use MYSQL select query with c#.
Following query for searching "ID" is working fine:
conn = new MySqlConnection(cs);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "select * from catalog_product_entity where entity_id = ?Id";
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
cmd.Parameters.Add("?Id", SqlDbType.Text).Value = ProductList[i].ProductId.ToString();
adp.Fill(MagentoProduct);
Now, I want to search exact string value in table. I am using following code and its giving empty result:
My Code:
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand("select * from catalog_category_entity_varchar where value = #Value;", conn);
cmd.Parameters.AddWithValue("#Value", "Storybooks");
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
log.WriteEntry(r.GetString("value"));
}
This is the problem:
where value = '?cname'
That's specifying ?cname as the literal value you're searching for - when you actually just want the parameter. Remove the quotes and it should be fine:
where value = ?cname
(You should use using statements for the connection and command, mind you...)
You could try SQL Reader
c = new MySqlCommand("select * from catalog_product_entity where column_nam = #Value;", conn);
c.Parameters.AddWithValue("#Value", your string);
MySqlDataReader r = c.ExecuteReader();
and then use Reader methods like reader.GetString("column_name"), ....

C# Mysql Select with Textbox Text

Im trying to select a row in mysql database using a textbox's text.
However when I use the following code I get an error.
MySqlCommand command = connection.CreateCommand(); //we create a command
command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ; //in commandtext, we write the Query
MySqlDataReader reader = command.ExecuteReader(); //execute the SELECT command, which returns the data into the reader
while (reader.Read()) //while there is data to read
{
MessageBox.Show(reader["info"].ToString());
}
It works fine with letters but when I try to use a question mark or anything like that i get the following error:
"Parameter '?' must be defined."
instead of
command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ;
Use this
command.CommandText = "SELECT * FROM info where id=#id";
command.Parameters.AddWithValue("#id",textBox1.Text);
you better use parameters in this case
command.CommandText = "SELECT * FROM info where id=#id";
then you need to set the parameter value
command.Parameters.AddWithValue(#id, textBox1.Text);
full code:
string queryString="SELECT * FROM info where id=#id";
using (MySqlConnection connection = new MySqlConnection(connectionString))
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
connection.Open();
command.Parameters.AddWithValue("#id", textBox1.Text);
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// do something ...
}
}
}
update :
change your parameter value setting line as below
command.Parameters.AddWithValue("#id", textBox1.Text);

Query using Oracle Parameter returns no result 11g

A simple select statement using variable binding gives no rows??
OracleConnection con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "select country_name from hr.countries where country_id = :country_id;
OracleParameter p_country_id = new OracleParameter();
p_country_id.OracleDbType = OracleDbType.Varchar2;
p_country_id.Value = "UK";
cmd.Parameters.Add(p_country_id);
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{} ---> no rows
tried adding parameterName ,direction,size still result is 0???
Any help??
I believe this is all correct but it is written in NotePad. At the very least it should get you on the right track.
using (OracleConnection con = new OracleConnection(constr))
{
con.Open();
using (OracleCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select country_name from hr.countries where country_id = :country_id";
cmd.Parameters.Add("country_id", "UK")
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
// You code here
}
}
}
NOTE: I put the using statements in there because this is always recommended when executing database queries. If an exception occurs the using statement will guarantee your database connection is still closed.
You forgot to give your parameter a name. Do so and it should work:
p_country_id.ParameterName = "country_id";
Thanks for responding guys, My unit test project app.config was pointing to wrong DB schema :(
Grrrrrrrrrrrrr! can't get anything stupid then this :) i will blame on my flu :)

Categories

Resources