SqlCeDataReader parameter ordinal = 1 - c#

I a Parameter ordial = 1 error on this code.
Can anyone explain it in this context? dbCon is correct as I can insert data to the database just trying out how to get it back no.
if (dbCon.State == ConnectionState.Closed)
{
dbCon.Open(); ;
}
SqlCeParameter vetidfromdropbox = new SqlCeParameter("#vetidfromdropbox", SqlDbType.Int);
vetidfromdropbox.Value = 2;
SqlCeCommand mySQLCommand = new SqlCeCommand("SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
SqlCeDataReader rdata = mySQLCommand.ExecuteReader();
if(rdata.Read()){
editNameTextbox.Text = (String)rdata["vetName"];
editSurnameTextbox.Text = (String)rdata["vetSurname"];
editCompanyNameTextbox.Text = (String)rdata["vetCompanyName"];
editPractiseAddTextBox.Text = (String)rdata["vetPractiseAddress"];
editMobileTextbox.Text = (String)rdata["vetMobile"];
editOtherTextbox.Text = (String)rdata["vetOther"];
editNotesTextbox.Text = (String)rdata["vetNotes"];
}else{
MessageBox.Show(" There has been an error with Read() ");
}
if (dbCon.State == ConnectionState.Open)
{
dbCon.Close();
}

You didn't add parameter to your SQL command:
var vetidfromdropbox = new SqlCeParameter("#vetidfromdropbox", SqlDbType.Int);
vetidfromdropbox.Value = 2;
var mySQLCommand = new SqlCeCommand(
"SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
mySQLCommand.Parameters.Add(vetidfromdropbox);
You can use AddWithValue to simplify the syntax:
var mySQLCommand = new SqlCommand(
"SELECT * FROM vets WHERE vetID = #vetidfromdropbox", dbCon);
mySQLCommand.Parameters.AddWithValue("vetidfromdropbox", 2);
Side note: use using on your sql connection and command to guarantee disposal and to simplify code.

Related

npgsql not returning rows when passed parameters in select statement

I am using the following code that was provided in the npgsql docs. I can retrieve data when my query string is Select * from public.accounts but this function will not return data when conditions are in the where clause.
I have seen other answers on SO that say to pass the command parameters in the AddWithValue function, but this doesn't return anything for me.
The query Select * from public.accounts where ext_auth0_user_id = 'github|42357689' DOES return data when I run it directly in pgAdmin, so I am assuming I have some formatting wrong.
var userId = "github|42357689";
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("Select * from public.accounts where ext_auth0_user_id = #userId", conn);
// Retrieve all rows
using (cmd)
{
cmd.Parameters.AddWithValue("#userId", userId);
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
dataTable.Load(reader);
}
}
}
}
NpgsqlParameter paramUserId = cmd.Parameters.Add("userId", NpgsqlTypes.NpgsqlDbType.Varchar, 20);
paramUserId.Direction = ParameterDirection.Input;
paramUserId.value = userId;
NpgsqlParameter paramAnotherId = cmd.Parameters.Add("anotherId", NpgsqlTypes.NpgsqlDbType.Integer);
paramAnotherId.Direction = ParameterDirection.Input;
paramAnotherId.value = anotherId;

LIKE expression does not work a query in C#

I want to search the records that have 3 or more '#'.
In MSAccess I can Write this and show me the results:
SELECT * FROM AlmLotes WHERE Lote LIKE '[#][#][#]*';
But in C# don't works.
DataTable dtResultats = new DataTable();
string strConnectionSource = MYCONNECTIONSTRING
OleDbConnection connAccess = new OleDbConnection(strConnectionSource);
connAccess.Open();
string strSQL = "SELECT * FROM AlmLotes WHERE Lote LIKE '[#][#][#]*'";
OleDbCommand cmd = new OleDbCommand(strSQL, connAccess);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd);
dtResultats = new DataTable();
try
{
myDataAdapter.Fill(dtResultats);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
for (int i = 0; i < dtResultats.Rows.Count; i++)
{
var rows = dtResultats.Rows[i];
for (int z = 0; z < dtResultats.Columns.Count; z++)
{
Console.WriteLine(dtResultats.Columns[z].ColumnName + ": " + rows[z] + Environment.NewLine);
}
}
Console.ReadKey();
The SQL Query in MSAcces show me 5 results.
THE SQL QUery in C# show me 0 results.
Try this:
string strSQL = #"SELECT * FROM AlmLotes WHERE Lote LIKE LIKE '[[#]%'";
So Ms Access use *, but C# OleDb use %. You can replace * to %.
string strSQL = #"SELECT * FROM AlmLotes WHERE Lote LIKE '###%'";
The solution are the Parameters:
string strSQL = "SELECT * FROM AlmLotes WHERE Lote LIKE #PARAM1";
OleDbCommand cmd = new OleDbCommand(strSQL, connAccess);
OleDbParameter param = cmd.CreateParameter();
param.DbType = DbType.String;
param.Direction = ParameterDirection.Input;
param.OleDbType = OleDbType.VarChar;
param.ParameterName = "PARAM1";
param.Value = "###%";
cmd.Parameters.Add(param);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd);
dtResultats = new DataTable();

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

ASP.NET , C# how to write this sql command

How can I write this code in asp.net c# code behinds?
Wwhat I'm trying to do is to select all rows in invoicetable with orderno that is equal to current session and deduct the inventory of my inventorytable from `invoicetable qty that matches their itemid's.
SqlCommand cmd =
new SqlCommand("UPDATE inventorytable
JOIN invoicetable ON inventorytable.ItemID = invoicetable.ItemID
SET inventorytable.inventory = inventorytable.inventory-invoice.QTY
WHERE invoicetable.No='" + Convert.ToInt32(Session["invoiceno"]) + "'"
, con);
InsertUpdateData(cmd);
Your update query is not formed correctly, and you should be using parameterized SQL. Try using something like this
var sqlQuery =
#"UPDATE inventorytable
SET inventorytable.inventory = inventorytable.inventory-invoice.QTY
FROM inventorytable
INNER JOIN invoicetable ON inventorytable.ItemID = invoicetable.ItemID
WHERE invoicetable.No=#invNo";
using (var conn = new SqlConnection(CONN_STR))
{
var sqlCmd = new SqlCommand(sqlQuery, conn);
sqlCmd.Parameters.AddWithValue("#invNo", Session["invoiceno"].ToString());
sqlCmd.ExecuteNonQuery();
}
I typed this without VS in front of me, so let me know if there are any syntax issues
var n = Session["invoiceno"] != null ? Convert.ToInt32(Session["invoiceno"]) : 0;
using (var conn = new SqlConnection(CONN_STR))
{
conn.Open();
var sql = "SELECT * FROM invoicetable WHERE orderno = #n";
var cmd = new SqlCommand(sql);
cmd.Connection = conn ;
cmd.Parameters.AddWithValue("#n", n);
using(var dr = cmd.ExecuteReader())
{
while(dr.Read())
{
//loop through DataReader
}
dr.Close();
}
}

ASP.Net C# - Setting a MySQL query and parameters based on a condition

How do I go about setting a MySQL query and parameters based on a condition?
I want different queries based on 'questionSource' as shown below.
However, in my code below, 'cmd' does not exist in the current context.
Alternatively, I could have two different functions for each condition and call the necessary function as required but I imagine there must be a way to have conditions within a connection.
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
declare cmd before if
MySqlCommand cmd = new MySqlCommand("",connStr);
and in each part of if
cmd.CommandText=cmdText;
other suggestion: add
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
always before if because it is used in the same way in if and else part
You just have to move the declaration of the cmd outside the if block:
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
string questionSource = Session["QuestionSource"].ToString();
string cmdText = "";
MySqlCommand cmd; // <-- here
if (questionSource.Equals("S"))
{
cmdText += #"SELECT COUNT(*) FROM questions Q
JOIN users U
ON Q.author_id=U.user_id
WHERE approved='Y'
AND role=1
AND module_id=#ModuleID";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
}
else if (questionSource.Equals("U"))
{
cmdText += "SELECT COUNT(*) FROM questions WHERE approved='Y' AND module_id=#ModuleID AND author_id=#AuthorID;";
cmd = new MySqlCommand(cmdText, conn); // remove MySqlCommand here
cmd.Parameters.Add("#ModuleID", MySqlDbType.Int32);
cmd.Parameters["#ModuleID"].Value = Convert.ToInt32(Session["TestModuleID"]);
cmd.Parameters.Add("#AuthorID", MySqlDbType.Int32);
cmd.Parameters["#AuthorID"].Value = Convert.ToInt32(Session["UserID"]);
}
int noOfQuestionsAvailable = 0;
int noOfQuestionsWanted = Convert.ToInt32(ddlNoOfQuestions.SelectedValue);
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
if (noOfQuestionsAvailable < noOfQuestionsWanted)
{
lblError.Text = "There are not enough questions available to create a test.";
}
else
{
Session["TestName"] = txtName.Text;
Session["NoOfQuestions"] = ddlNoOfQuestions.SelectedValue;
Session["QuestionSource"] = rblQuestionSource.SelectedValue;
Session["TestModuleID"] = ddlModules.SelectedValue;
Response.Redirect("~/create_test_b.aspx");
}
}
catch
{
lblError.Text = "Database connection error - failed to get module details.";
}
finally
{
conn.Close();
}
}
Just move the declaration of the MySqlCommand outside the if/else blocks so you could use it in the final try where you execute the command
//validation checks
else
{
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using(MySqlConnection conn = new MySqlConnection(connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
// Don't need to associate the command to the connection
// Already done by the CreateCommand above, just need to set
// the parameters and the command text
if (questionSource.Equals("S"))
{
cmdText = #"....."
cmd.CommandText = cmdText;
....
}
else if (questionSource.Equals("U"))
{
cmdText = "........."
cmd.CommandText = cmdText;
....
}
try
{
conn.Open();
noOfQuestionsAvailable = Convert.ToInt32(cmd.ExecuteScalar());
....
}
}
}
Notice also that you should use the using statement to be sure that your connection and your command are propertly closed and disposed.

Categories

Resources