Must declare the scalar variable "#GenName" [duplicate] - c#

This question already has answers here:
Error on sql database "Must declare the scalar variable"
(2 answers)
Closed 4 years ago.
I am getting this error when trying to run the code below. Any insight on to what I am doing wrong? I am pretty new to this, and want to get this to work pretty bad. I have gotten zero help from this site so far in a previous question I asked. But decided to give this forum another shot, before giving up on stackoverflow
protected void SaveButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection =
new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=TESTdatabase;Integrated Security=True");
SqlCommand myCommand = new SqlCommand(
"INSERT into tblGenerator (GeneratorName, GeneratorAddress, GeneratorCity, GeneratorState, GeneratorZip, GeneratorPhone, GeneratorContact, GeneratorEPAID)" +
"VALUES (#GenName, #GenAdd, #GenCity, #GenState, #GenZip, #GenPhone, #GenContact, #GenEPAID), myConnection");
myCommand.Parameters.AddWithValue("#GeneratorName", GenName.Text);
myCommand.Parameters.AddWithValue("#GeneratorAddress", GenAdd.Text);
myCommand.Parameters.AddWithValue("#GeneratorCity", GenCity.Text);
myCommand.Parameters.AddWithValue("#GeneratorState", GenState.Text);
myCommand.Parameters.AddWithValue("#GeneratorZip", GenZip.Text);
myCommand.Parameters.AddWithValue("#GeneratorPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("#GeneratorContact", GenContact.Text);
myCommand.Parameters.AddWithValue("#GeneratorEPAID", GenEPAID.Text);
myConnection.Open();
myCommand.Connection = myConnection;
myCommand.ExecuteNonQuery();
myConnection.Close();
}

First, Stackoverflow is very helpful :) Don't give up on this platform.
Now for your question:
The parameters your SQL statement is expecting are:
(#GenName, #GenAdd, #GenCity, #GenState, #GenZip, #GenPhone, #GenContact, #GenEPAID)
While you later assign them with different names.
It should be:
myCommand.Parameters.AddWithValue("#GenName", GenName.Text);
myCommand.Parameters.AddWithValue("#GenAdd", GenAdd.Text);
myCommand.Parameters.AddWithValue("#GenCity", GenCity.Text);
myCommand.Parameters.AddWithValue("#GenState", GenState.Text);
myCommand.Parameters.AddWithValue("#GenZip", GenZip.Text);
myCommand.Parameters.AddWithValue("#GenPhone", GenPhone.Text);
myCommand.Parameters.AddWithValue("#GenContact", GenContact.Text);
myCommand.Parameters.AddWithValue("#GenEPAID", GenEPAID.Text);
When using #parameter , you must assign a value to a parameter with the same exact name.

Related

How to solve SqlException: Must declare the scalar variable "#RegNo" in ASP.Net [duplicate]

This question already has answers here:
Must declare scalar variable #Id?
(3 answers)
Closed 5 years ago.
SqlCommand cmd = new SqlCommand("insert into Student(#RegNo,#Name,#Address,#CreatedTime) values(#RegNo,#Name,#Address,Getdate())");
here it display an error like SqlException:
Must declare the scalar variable "#RegNo".
what to do? Thanks
protected void Add_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
try {
using (SqlConnection con = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand("insert into Student(RegNo,Name,Address,CreatedTime)values(#RegNo,#Name,#Address,Getdate())", con)) {
cmd.Parameters.AddWithValue("#RegNo", RegNo.Text);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.Parameters.AddWithValue("#Address", Address.Text);
con.Open();
cmd.ExecuteNonQuery();
}
} catch (Exception ex) {
//handle exception..
throw;
}
}
It displays an error:
No mapping exists from object type System.Web.UI.WebControls.TextBox
to a known managed provider native type.
Sql insert query has basically 2 parts.
1) Table ColumnNames for inserting values into
2) Actual values being inserted or #parameters having values.
Your SQL is mixing 1 with 2.
So instead of
SqlCommand cmd = new SqlCommand("insert into Student(#RegNo,#Name,#Address,#CreatedTime) values(#RegNo,#Name,#Address,Getdate())");
It should be
SqlCommand cmd = new SqlCommand("insert into Student(RegNo,-[Name],Address,CreatedTime) values(#RegNo,#Name,#Address,Getdate())");
After this you only need to add all #variables in the SqlCommand object. I can see others have already suggested you code for that.
Let me explain why did you get the error.
Your sql command is this: SqlCommand cmd = new SqlCommand("insert into Student(#RegNo,#Name,#Address,#CreatedTime) values(#RegNo,#Name,#Address,Getdate())");
This means you are telling sql to execute query that is equivalent to this:
insert into Student(#RegNo,#Name,#Address,#CreatedTime) values(1234,'name value','address value',GetDate()) -- i've put some vlaues for example
As you can see this is not correct.
When executing insert query, you want to specify column names and values, names goes into first bracket and values into second after Values keyword, so logically there is no column name "#RegNo" or "#Name" instead use real column names as specified in database "RegNo", "Name", so the query should look like this:
insert into Student(RegNo,Name,Address,CreatedTime) values(1234,'name value','address value',GetDate())
Why the error message?
In sql variables are declared with # prefix for example: declare #a int=5; so, when trying to execute your query insert into Student(#RegNo,....... sql recognizes #RegNo as variable, since declaration can't be found you get an error message
Must declare the scalar variable #RegNo.
You should use '#' only to specify parameters not for column names
Try this in your c# code:
SqlCommand cmd = new SqlCommand("insert into Student(RegNo,Name,Address,CreatedTime) values(#RegNo,#Name,#Address,#CreatedTime)");
cmd.Parameters.AddWithValue("#RegNo", "object value");
cmd.Parameters.AddWithValue("#Name", "object value");
cmd.Parameters.AddWithValue("#Address", "object value");
cmd.Parameters.AddWithValue("#RegNo", "object value");
cmd.Parameters.AddWithValue("#CreatedTime", DateTime.Now); //replaced GetDate with DateTime.Now
!Note: When using SqlCommand you can always execute query in sql first, to see that you didn't made some mistake

Fields not inserting into my SQL Server [duplicate]

This question already has answers here:
SqlCommand INSERT INTO query does not execute
(3 answers)
Closed 7 years ago.
I am using visual studio, i have a connection to an SQL server and im trying to update a table in the database.
I am not recieving any errors nor am i updating anything
Below is the code i have used
protected void Btn1_Click(object sender, EventArgs e)
{
//SQL for insert here.
string MyConnectionString = ConfigurationManager.ConnectionStrings
["testconnect"].ConnectionString;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = MyConnectionString;
myConnection.Open();
SqlCommand cmd = new SqlCommand("insert into Don_Test (ID, Test) values ('" + IDTxt.Text + "','" + TESTTxt.Text + "')", myConnection);
//Call refresh
refreshPage();
myConnection.Close();
}
Actually, you are not executing your query, but just opening connection and closing it later.
Add line of code cmd.ExecuteNonQuery(); before refreshPage().
Also notice - concatenating query text is very bad idea since it leads to SQL injection attack.
Use parameterized query instead.

SQL System.NullReferenceException [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I wrote a c# function to populate a ext.net store. It works fine in one application, but the same code does not work in another. I am getting a System.NullReferenceException on line 26. This is line 26:
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is my c# function:
protected void fillStore(Ext.Net.Store store, string query)
{
SqlDataReader MyReader;
SqlConnection MyConnection = new SqlConnection();
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
SqlCommand fillCommand = new SqlCommand();
fillCommand.CommandText = "select id, name from b2b_group";
fillCommand.CommandType = CommandType.Text;
fillCommand.Connection = MyConnection;
fillCommand.Connection.Open();
MyReader = fillCommand.ExecuteReader(CommandBehavior.CloseConnection);
store.DataSource = MyReader;
store.DataBind();
fillCommand.Dispose();
MyConnection.Dispose();
}
For simplification, I replaces the query string that would be passed through by a hard-coded one of "select id, name from b2b_group".
I can not seem to figure out why it is giving a nullReferenceException, especially seeing as I have the same code working in another project.
I know that there is some little thing I am overseeing, could anyone spot it?
Thank you so much!
The connection string 'MyConnectionString' is not present in your configuration file. Check connectionStrings section.

Error when trying to insert a variable from C# into MySQL [duplicate]

This question already has answers here:
Parameterized Query for MySQL with C#
(6 answers)
Closed 8 years ago.
Here is my code that I'm using to insert values into my database.
public void callSQL(string partNumber, string total, string numOfPacks, string dunsNumber, string serialNumber, string laneNumber)
{
MySqlConnection myConnection = new MySqlConnection("SERVER=localhost;DATABASE=testing;UID=root;PASSWORD=********;");
try
{
myConnection.Open();
Console.WriteLine(laneNumber);
MySqlCommand myCommand = new MySqlCommand("INSERT INTO test (Part_Number, total, number_of_packs, dunsNumber, serialNumber, truck_number) VALUES (" + partNumber +","+total+","+numOfPacks+","+dunsNumber+","+serialNumber+","+laneNumber+")", myConnection);
myCommand.ExecuteNonQuery();
Console.Write("Done");
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Its really weird what happens. The problem I am getting is with the laneNumber variable. It is a string that I read from the console.
Console.WriteLine("Please enter the date and lane number like so: ddmmyylanenumber.");
string lanenum = Console.ReadLine();
However it only gets inputted into the database when it is all numbers. The moment there is a character in there, I am not able to input anything into the database. It works when I manually change the variable to a string, but not when I use the variable with characters inside. The error I get is this:
"MySQL.Data.MySqlClient.MySqlExectipn (0x8004005): Unknown column 'whatever_i_entered_into_console' in 'field list'
The line that the compiler complains about is the myCommand.ExectueNonQuery(); line.
Hope this is enough information.
Thanks for the help in advance.
EDIT
truck_number is a VARCHAR.
from your comments you mentioned that truck_number column is a VARCHAR type.
Problem : You are not enclosing the string value lane_number within a single quotes.
Solution : You need to enclose the string values for VARCHAR types within single quotes to send them properly :
Try This: (I don't Suggest this)
MySqlCommand myCommand = new MySqlCommand("INSERT INTO test (Part_Number, total, number_of_packs, dunsNumber, serialNumber, truck_number) VALUES (" + partNumber +","+total+","+numOfPacks+","+dunsNumber+","+serialNumber+",'"+laneNumber+"')", myConnection);
Suggestion : Your INSERT INTO statement is open to SQL Injection Attacks. so i would suggest you to use Parameterised queries to avoid them.
when you use parameterised queries respective types willbe sent properly,so you don't even need to use single quotes while sending string values.
using Parameterised Queries :
MySqlCommand myCommand = new MySqlCommand("INSERT INTO test (Part_Number, total, number_of_packs, dunsNumber, serialNumber, truck_number) VALUES (#Part_Number,#total,#number_of_packs,#dunsNumber,#serialNumber,#truck_number)", myConnection);
myCommand.Parameters.AddWithValue("#Part_Number",partNumber);
myCommand.Parameters.AddWithValue("#total",total);
myCommand.Parameters.AddWithValue("#number_of_packs",numOfPacks);
myCommand.Parameters.AddWithValue("#dunsNumber",dunsNumber);
myCommand.Parameters.AddWithValue("#serialNumber",serialNumber);
myCommand.Parameters.AddWithValue("#truck_number",laneNumber);
myCommand.ExecuteNonQuery();
Make sure that columnNames are correct
Try like ths
MySqlCommand myCommand = new MySqlCommand("INSERT INTO test VALUES('" + partNumber +"','"+total+"','"+numOfPacks+"','"+dunsNumber+"','"+serialNumber+"','"+laneNumber+"')", myConnection);

problems writing sql and insert statement [duplicate]

This question already has answers here:
add selected value to users profile
(2 answers)
Closed 9 years ago.
I am trying to write an insert statement where the job is to take selected item the user has selected then insert it into their profile.
I am using Profile provider.
There is a new column I have made in UserProfile table (that stores stuff like username, age and so forth) and I have called it Rented.
e.g.:
User Tom45
rented Pirates of The caribbean
age 23
Could someone let me know if I am doing it right as I can't seem to get it to work.
My Insert and SQL:
protected void Button3_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\ASPNetDB.mdb;Persist Security Info=True");
{
da.InsertCommand = new OleDbCommand("INSERT INTO UserProfile (Rented) VALUES (#Rented) WHERE [UserName] = ?", conn);
string dvdrent = DG_Latest.SelectedRow.Cells[1].Text;
OleDbParameter rented = new OleDbParameter();
{
da.InsertCommand.Parameters.AddWithValue("#Rented", DG_Latest.SelectedRow.Cells[2].Text);
}
conn.Open();
da.InsertCommand.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
I have this table:
And each user has a profile:
Once they're logged in they can choose to rent dvds:
The problem is I do not think my query does this, as it does not work.
instead #Render write question mark.
you need add second parameter for the User criteria, and set it.
so:
protected void Button3_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\ASPNetDB.mdb;Persist Security Info=True");
{
da.InsertCommand = new OleDbCommand("INSERT INTO UserProfile (Rented) VALUES (?) WHERE [UserName] = ? ;", conn);
da.InsertCommand.Parameters.AddWithValue("#Rented", DG_Latest.SelectedRow.Cells[2].Text);
da.InsertCommand.Parameters.AddWithValue("#User", XXXXXXXXX);
conn.Open();
da.InsertCommand.ExecuteNonQuery();
conn.Close();
conn.Dispose();
}
}
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
source: msdn

Categories

Resources