Can't get a SQL command to recognise the params added - c#

I've not used basic SQL commands for a while and I'm trying to pass a param to a sproc and the run it. However when I run the code I get a "Not Supplied" error.
Code:
SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr());
SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1);
cmd1.Parameters.Add(new SqlParameter("#ID", itemId));
conn1.Open();
cmd1.ExecuteNonQuery();
I'm not really sure why this would fail. Apologies for the basic question, but I'm lost!
Thanks in advance.

You should set the CommandType to StoredProcedure, set the connection and use Parameters.AddWithValue("#ID", itemID)
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Connection = conn1;
cmd1.Parameters.AddWithValue("#ID",itemID);
conn1.Open();
cmd1.ExecuteNonQuery();
If you want to use Parameters.Add() (which is obsolete), here is how you do it (you need to pass the type too)
cmd1.Parameters.Add("#ID", SqlDbType.Int); //string maybe, I don't know
cmd1.Parameters["#ID"].Value = itemID;
This should work:
SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr());
SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#ID", itemId);
conn1.Open();
cmd1.ExecuteNonQuery();

And to make your code even better, put your SqlConnection and SqlCommand into using statements, so that they'll be freed automatically at the end of the using block:
using(SqlConnection conn1 = new SqlConnection(DAL.getConnectionStr()))
{
using(SqlCommand cmd1 = new SqlCommand("SProc_Item_GetByID", conn1))
{
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#ID", itemId);
conn1.Open();
cmd1.ExecuteNonQuery();
conn.Close();
}
}

Related

I want to insert data into two tables using sql and asp.Net

SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=MYDATASOURCE";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID, #IngredientNaam";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
I want to insert data to the tables Voorraad and Ingredient. In the tables Voorraad there must IngredientID, AantalInVoorraad, MinimumVoorraad and Categorie be in the table after instert.
In the table Ingredient there must be an new Ingredientnaam be made. When i filling in the text boxes and after hitting the button insert i get the error:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '#MinimumVoorraad'.'
Please help me!
I've edited to this:
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into [Voorraad] values(#IngredientID,
#AantalInVoorraad, #MinimumVoorraad)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into [Ingredient] values(#IngredientID,
#IngredientNaam)";
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.ID);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
Does anybody know maybe another way to insert data to multiple tables in the datbase?? I've searched the whole internet for an answer but i can't find the right solution.
Introducing ASP.NET Web Pages - Entering Database Data by Using Forms
cmd.CommandText = "Insert into [Voorraad] (IngredientID, AantalInVoorraad, MinimumVoorraad) values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)";
and
cmd.CommandText = "insert into [Ingredient] (IngredientID, IngredientNaam) values(#IngredientID, #IngredientNaam)";
Your insert statements are missing the closing bracket for the values.
Add a using Statement for the SQlConnection and SQLCommand, will make it easier to read and debug.
using (SqlConnection con = new SqlConnection(#"Data Source=MYDATASOURCE"))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(
"Insert into [Voorraad] values(#IngredientID, #AantalInVoorraad, #MinimumVoorraad)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#AantalInVoorraad", txt_aantal.Text);
cmd.Parameters.AddWithValue("#MinimumVoorraad", txt_minimum.Text);
cmd.ExecuteNonQuery();
}
using(SqlCommand cmd = new SqlCommand(
"insert into [Ingredient] values(#IngredientID, #IngredientNaam)", con))
{
cmd.Parameters.AddWithValue("#IngredientID", txt_ID.Text);
cmd.Parameters.AddWithValue("#IngredientNaam", txt_ingredient.Text);
cmd.ExecuteNonQuery();
}
}

SqlConnection and SqlCommand with using statement

I have a connection to a database set up like this to call a stored procedure. I am just wondering if this is the best way to do this.
I have two using statements one for the sqlConnection and one for the sqlCommand (which I am not really sure if its needed)
using (SqlConnection con1 = new SqlConnection(conString1))
{
using (SqlCommand cmd1 = new SqlCommand())
{
cmd1.Connection = con1;
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.CommandText = "updateVendorEstNo";
cmd1.Parameters.AddWithValue("#plantNameNew", vPlantName.Value.ToString().Trim());
var result = cmd1.Parameters.Add("#result", SqlDbType.Int);
result.Direction = ParameterDirection.Output;
var resultDesc = cmd1.Parameters.Add("#resultDesc", SqlDbType.VarChar, 100);
resultDesc.Direction = ParameterDirection.Output;
con1.Open(); // open connection
cmd1.ExecuteNonQuery();
res = result.Value.ToString().Trim();
resDesc = resultDesc.Value.ToString().Trim();
}
}
My biggest question is when I am doing :
using (SqlCommand cmd1 = new SqlCommand())
Is it fine the way it is done right now.. or should it be more like,
using (SqlCommand cmd1 = new SqlCommand("updateVendorEstNo",con1))
I think that the way you have it is fine, because the using statement will ensure that the object is disposed of either way.

Inserting data to multiple table in my sqlworkbench

I'm a new coder trying to code C# to insert data into sqlworkbench database. Having alot of problems. Looking for any help. Thanks.
private void enterbutton_Click(object sender, EventArgs e)
{
MySql.Data.MySqlClient.MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=mydb;";
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into garden(idGarden) VALUES (#idGarden)");
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#idGarden", gardentextBox.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
SqlCommand cmd1 = new SqlCommand("insert into rainfall(aveRainfall) VALUES (#aveRainfall)");
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue("#aveRainfall", aveRaintextBox.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("insert into seat(idSeat) VALUES (#idSeat)");
cmd2.Connection = conn;
cmd2.Parameters.AddWithValue("#idSeat", seatIDtextBox.Text);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
SqlCommand cmd3 = new SqlCommand("insert into temperature(currentTemp) VALUES (#currentTemp)");
cmd3.Connection = conn;
cmd3.Parameters.AddWithValue("#currentTemp", currentTemptextBox.Text);
cmd3.ExecuteNonQuery();
cmd3.Parameters.Clear();
conn.Close();
}
You didn't connect your SqlCommand's with your MySqlConnection. And I think they should MySQLSqlCommand instead of SqlCommand.
You can assing their .Connection properties to your MySqlConnection. Like;
cmd.Connection = conn;
cmd2.Connection = conn;
cmd3.Connection = conn;
cmd4.Connection = conn;
And you try to execute your cmd only. I think you should execute your all others commands like cmd2, cmd3 and cmd4..
cmd.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
cmd3.ExecuteNonQuery();
cmd4.ExecuteNonQuery();
And could be better to use using statement to dispose your database connections..
using(MySqlConnection conn = new MySqlConnection(myConnectionString))
using(MySQLCommand cmd = conn.CreateCommand())
{
//
}
Also always prefer to use Add() instead of AddWithValue().
Read: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

Call stored procedure and cursor parameter with OleDb

I'm developing an application in C# that connects to an Oracle 10g database.
I'm using Oledb like this:
OleDbConnection conn = ConnectionUtil.CreateConexion();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = SP_AUTENTICAR_USUARIO;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_SED_USUARIO", OleDbType.VarChar).Value = strUsuario;
cmd.Parameters.Add("p_SED_PASS", OleDbType.VarChar).Value = strPass;
cmd.Parameters.Add("p_cursor", OleDbType.Cursor).Direction = ParameterDirection.Output;//I dont know what to put here
conn.Open();
cmd.ExecuteNonQuery();
OleDbDataReader objReader = (OleDbDataReader)cmd.Parameters["p_cursor"].Value;
if (objReader.Read())
{...
I need to call a stored procedure and read a cursor with OleDbDataReader.
Any idea how to do that?
Thanks,
Please Check this sample code.this is using OracleDataReader
oraConn.Open();
OracleCommand cursCmd = new OracleCommand("CURSPKG.OPEN_TWO_CURSORS", oraConn);
cursCmd.CommandType = CommandType.StoredProcedure;
cursCmd.Parameters.Add("EMPCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
cursCmd.Parameters.Add("DEPTCURSOR", OracleType.Cursor).Direction = ParameterDirection.Output;
OracleDataReader rdr = cursCmd.ExecuteReader();
Console.WriteLine("\nEmp ID\tName");
while (rdr.Read())
Console.WriteLine("{0}\t{1}, {2}", rdr.GetOracleNumber(0), rdr.GetString(1), rdr.GetString(2));
rdr.NextResult();
Console.WriteLine("\nDept ID\tName");
while (rdr.Read())
Console.WriteLine("{0}\t{1}", rdr.GetOracleNumber(0), rdr.GetString(1));
rdr.Close();
oraConn.Close();

Object reference not set to an instance of an object (don't know what I should do)

Here is the error:
Exception Details: System.NullReferenceException: Object reference not
set to an instance of an object.
and it stops here: con.Open();
and here is the code:
SqlConnection con = new SqlConnection(DBHelper.connection);
SqlCommand com = new SqlCommand();
con = com.Connection;
con.Open();
com.CommandType = CommandType.Text;
com.CommandText = "select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue ;
SqlDataReader dr= com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drr;
drr=dt.Rows[0];
con.Close();
the error:
Line 19: SqlCommand com = new SqlCommand();
Line 20: con = com.Connection;
Line 21: con.Open(); // here the error
Line 22: com.CommandType = CommandType.Text;
Line 23: com.CommandText = "select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue
Third line is wrong. It should be
com.Connection = con;
You need to change this line (com.Connection is null at that point):
con = com.Connection;
to this:
com.Connection = con;
You're assigning the connection in the wrong order. You should be assigning the connection you create on the first line to the SqlCommand, not assigning the connection of the SqlCommand (which hasn't been created yet) to the SqlConnection variable con you created earlier.
SqlConnection con = new SqlConnection(DBHelper.connection);
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con
You should also check your connection state to make sure it opened successfully before executing your command.
Try this:
SqlConnection con = new SqlConnection(DBHelper.connection);
SqlCommand com = con.CreateCommand();
con.Open();
com.CommandType = CommandType.Text;
com.CommandText = "select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue ;
SqlDataReader dr= com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drr;
drr=dt.Rows[0];
con.Close();
You were actually trying to create a connection from a command - the command needs to be assigned a connection, not vice versa.
I would also suggest the "using" syntax which I like, that also takes care of disposal for the command and the connection.
using (SqlConnection con = new SqlConnection(DBHelper.connection))
{
using(SqlCommand com = con.CreateCommand())
{
con.Open();
com.CommandType = CommandType.Text;
com.CommandText = "select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue ;
SqlDataReader dr= com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
DataRow drr;
drr=dt.Rows[0];
}
}
"select catname,catdescription,photo from category where catid=" + catselectddl.SelectedValue
On a side note:
This type of SQL Script, if turned into a habit, WILL open doors to SQL-Injection; and I assume no developer likes this type of flaw...

Categories