How to pass parameters in a oracle SQL query? - c#

For the past few days I cannot pass any fixed parameters to my SQL query.
I try all possible tutorials to pass the parameter to a query, but nothing works.
However, I have seen by putting fixed parameters directly in the query (method 1) it worked perfectly.
I do not see that in method 2 prevents the functioning of my function.
When I say that it does not work is that in the first method my reader is filled while in the method 2 my reader is empty
method 1 : works (i don't need this kind of function)
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet='demonstration'";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}
method 2 : doesn't works (I need this kind of function)
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet=:test";
cmd.Parameters.Add(new OracleParameter("test", "demonstration"));
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}

String updateCmd;
SqlCommand myCommandUpd;
updateCmd = "UPDATE RHRMVacationRequest SET [EmplId] = #Emplid WHERE RecId = #RecId";
myCommandUpd = new SqlCommand(updateCmd, DataBase.GetConnetionToBase());
myCommandUpd.Parameters.Add(new SqlParameter("#Emplid", SqlDbType.VarChar, 10));
myCommandUpd.Parameters.Add(new SqlParameter("#RecId", SqlDbType.BigInt));
myCommandUpd.Parameters["#Emplid"].Value = emplIdUpd.Text.Trim();
myCommandUpd.Parameters["#RecId"].Value = Convert.ToInt64(RecIdUpd.Value.Trim());
myCommandUpd.Connection.Open();
myCommandUpd.ExecuteNonQuery();

may be i recall the wrong way round - maybe i tried :? and it did not work and used :test - but i think i got you issue, check the code below.
public void VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select nom_projet from analyses where nom_projet=:test";
cmd.Parameters.Add(new OracleParameter(":test", "demonstration"));
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
Console.WriteLine("Data already exist");
else
Console.WriteLine("Data doesn't exist");
}

After many hours of research, i have I finally found the solution:
public Boolean VerifierVersionDejaPresnte(ParseurXML.DonneesGlobales donneGlobale)
{
string str = "demonstration";
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.BindByName = true;
cmd.CommandText = "select * from analyses where nom_projet='"+str+"'";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Console.WriteLine("Data already exist");
return true;
}
Console.WriteLine("Data doesn't already exist");
return true;
}

Related

oracle function always return null

I'm using the flowing code to call the oracle function with the return value,
but it returns null always
OracleCommand cmd = new OracleCommand();
using (OracleConnection cnn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=321352427544)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=test)));User ID=abc;Password=123;"))
{
cmd.Connection = cnn;
cmd.CommandText = "GetEmp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("P_EMP_ID", OracleDbType.Int32).Value = 4241;
cmd.Parameters.Add(new OracleParameter("return_value", OracleDbType.Int32)).Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmd.ExecuteNonQuery();
string Count = (string)cmd.Parameters["return_value"].Value;
cnn.Close();
}
the problem was solved in two ways by
add cmd.BindByName = true;
add the return parameter in the first: cmd.Parameters.Add(new OracleParameter("return_value", OracleDbType.Int32)).Direction = ParameterDirection.ReturnValue;

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

How do I get last input to column (ID)

I have this code that is suppose to get me the last registered MemberId from column but I cant get it to work, what have I got wrong?
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT top 1 * FROM Medleminfo ORDER BY MemberId desc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
last_id = Convert.ToInt32(dr["MemberId"].ToString());
}
return last_id;
Output last_id is supposed to be used in this method:
public DataTable display_tiger_info(int member_id)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT Medleminfo.MemberId, Medleminfo.Förnamn, Medleminfo.Efternamn,
Medleminfo.Adress, Medleminfo.Telefon, Tigerinfo.Tigernamn,Tigerinfo.Födelsedatum
FROM Medleminfo, Tigerinfo WHERE Medleminfo.MemberId = Tigerinfo.OwnerID ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
Why not just use the 'Max' function? This is assuming that your looking for the largest number in the sequence. The way your question is worded though would suggest that you should have a date column to search by instead. Also if you want just one result then try execute scalar instead of putting it into a data table and going through all that extra work.
int id = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand("Select Max(MemberId) from Medleminfo", connection))
{
id = (int)command.ExecuteScalar();
}
}
I think your issues is probably cmd.ExecuteNonQuery() according to the msdn SqlCommand.ExecuteNonQuery Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
You will probably be wanting to use ExecuteReader in something like the following
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//All you want is the member Id why get all the columns
cmd.CommandText = "SELECT top 1 MemberId FROM Medleminfo ORDER BY MemberId desc";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
last_id = Convert.ToInt32( reader[0]));
}
return last_id;
UPDATE: This code might solve your problem but I did not identify the issue correctly cmd.ExecuteNonQuery() should be removed it is not doing anything. adapter.Fill() should be executing the command and I do not know why you are not getting the expected response.

how two get data from 2 different table c#

I have two table.I need to get calorificValue from the food table and daily_gained from the calorie_tracker table to then make some calculations.I've written this code, I know it not efficent. It retrieves daily_gained but failed to get calorificValue.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
MySqlCommand cmd2 = new MySqlCommand("SELECT sportsman_id,daily_gained FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
cmd2.Connection.Open();
MySqlDataReader rd = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
int burned = 0;
if (rd.HasRows) // if entered username and password have the data
{
while (rd.Read()) // while the reader can read
{
if (rd["sportsman_id"].ToString() == Login.userID) // True for admin
{
burned += int.Parse(rd["daily_gained"].ToString());
}
}
}
cmd2.Connection.Close();
cmd.Connection.Open();
MySqlDataReader rd2 = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (rd2.HasRows) // if entered username and password have data
{
while (rd2.Read()) // while the reader can read
{
if (rd2["name"].ToString() == s)
{
burned += int.Parse(rd2["calorificValue"].ToString());
}
}
}
MessageBox.Show(burned+"");
DataTable tablo = new DataTable();
string showTable = "SELECT * from myfitsecret.calorie_tracker where sportsman_id=#sportsman_id";
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand showCommand = new MySqlCommand();
showCommand.Connection = cnn;
showCommand.CommandText = showTable;
showCommand.CommandType = CommandType.Text;
showCommand.Parameters.AddWithValue("#sportsman_id", Login.userID);
adapter.SelectCommand = showCommand;
adapter.Fill(tablo);
dataGridView1.DataSource = tablo;
cnn.Close();
Why don't you just use the scalar function SUM and let the database do its job instead of writing a lot of code?
int burned = 0;
string s = comboBox1.SelectedItem.ToString();
cnn.Open();
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
cmdText = #"SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
object result = cmd.ExecuteScalar();
burned += (result != null ? Convert.ToInt32(result) : 0);
}
Not visible from your code, but also the connection should be created inside a using statement (very important with MySql that is very restrictive with simultaneous open connections)
We could also use a different approach putting the two commands together and separating them with a semicolon. This is called batch commands and they are both executed with just one trip to the database. Of course we need to fallback using the MySqlDataReader to get the two results passing from the first one to the second one using the NextResult() method (see here MSDN for Sql Server)
string cmdText = #"SELECT SUM(calorificValue)
FROM myfitsecret.food
WHERE name=#name;
SELECT SUM(daily_gained)
FROM myfitsecret.calorie_tracker
WHERE sportsman_id=#sportsman_id";
using(MySqlCommand cmd = new MySqlCommand(cmdText, cnn))
{
// Add both parameters to the same command
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#sportsman_id", MySqlDbType.Int32).Value = Login.userID;
cnn.Open();
using(MySqlDataReader reader = cmd.ExecuteReader())
{
// get sum from the first result
if(reader.Read()) burned += Convert.ToInt32(reader[0]);
// if there is a second resultset, go there
if(reader.NextResult())
if(reader.Read())
burned += Convert.ToInt32(reader[0]);
}
}
Your issues could be around closing a connection and then trying to open it again. Either way it's fairly inefficient to be closing and opening connections.
MySqlCommand cmd = new MySqlCommand("SELECT name,calorificValue FROM myfitsecret.food where name=#name", cnn);
string s = (comboBox1.SelectedItem).ToString();
cmd.Parameters.AddWithValue("#name",s);
MySqlCommand cmd2 = new MySqlCommand("SELECT SUM(daily_gained) FROM myfitsecret.calorie_tracker where sportsman_id=#sportsman_id", cnn);
cmd2.Parameters.AddWithValue("#sportsman_id", Login.userID);
cnn.Open();
MySqlDataReader rd = cmd.ExecuteReader();
if (rd.HasRows) // if entered username and password have data
{
while (rd.Read()) // while the reader can read
{
burned += int.Parse(rd["calorificValue"].ToString());
}
}
burned = cmd2.ExecuteScalar();
MessageBox.Show(burned+"");
cnn.Close();

Why is this insert not working?`

Actually my code was suppose to check that is there any value in the course_choice_teacher table. If there is not, then it will insert some values into the table. Now this time there is no value in the table. So dr2.Read() should return false and do the else portion. But it is doing the reverse thing. I'll be very happy if you help me in this purpose.
string oradb = "Data Source=localhost;User Id=system;Password=cse;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd2 = new OracleCommand();
cmd2.Connection = conn;
cmd2.CommandText = "select * from course_choice_teacher where teacher_id='"+teacher_home.st+"' and choice_no=1";
cmd2.CommandType = CommandType.Text;
OracleDataReader dr2 = cmd2.ExecuteReader();
if (dr2.Read())
{
MessageBox.Show("Already Given");
}
else
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into course_choice_teacher values('" + teacher_home.st + "','" + dataGridView1.CurrentRow.Cells["course_id"].Value.ToString() + "',1)";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
}
conn.Dispose();
The datareader has property .HasRows to check if the result has some rows. This would be a proper way to check what you intend to do.
if (dr2.HasRows)
{
MessageBox.Show("Already Given");
}
else
{
.........
}

Categories

Resources