c# debugging getting scalar variable error - c#

I need your assistance. I have created form and insert some data into SQL Server. But I always get an error. I think I made a mistake when creating the SQL Server connection.
code is below
OleDbConnection con = new OleDbConnection("Provider=sqloledb;SERVER=NEVZAT-PC;DATABASE=DENEME;User ID=11;password=1111;");
OleDbCommand cmd = new OleDbCommand("insert into isemri (isemrino,isyeri,isalani,isemridet,bastar,bittar)values(#isemrino,#isyeri,#isalani,#isemridet,#bastar,#bittar)", con);
cmd.Parameters.AddWithValue("#isemrino", Convert.ToInt32(textBox1.Text));
cmd.Parameters.AddWithValue("#isyeri", comboBox1.Text);
cmd.Parameters.AddWithValue("#isalani", comboBox2.Text);
cmd.Parameters.AddWithValue("#isemridet", richTextBox1.Text);
cmd.Parameters.AddWithValue("#bastar", dateTimePicker1.Value);
cmd.Parameters.AddWithValue("#bittar", dateTimePicker2.Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
and I get this error:
enter image description here

From what it seems to me the issue is that you're using undeclared variables in your query, you have to either declare the variables before insert, or use other methodes that don't use variables.

You are receiving "Must declare the scalar variable" error.
OleDb does not support named parameters. I presume this is what is
causing the errors. Instead, within the SQL query, use ? instead of
the param name, and ensure the order of parameters added matches the
order they appear in the query.
Apply ? sign in insert query
Tried with using statement
[Optional step : ] Applied all parameter, also used DBNull.Value in case of the table field is nullable
Please check below code:
OleDbConnection con = new OleDbConnection("Provider=sqloledb;SERVER=NEVZAT-PC;DATABASE=DENEME;User ID=11;password=1111;");
using(OleDbCommand cmd = new OleDbCommand("insert into isemri (isemrino,isyeri,isalani,isemridet,bastar,bittar) values (?, ?, ?, ?, ?, ?)", conn))
{
cmd.Parameters.AddWithValue("#isemrino", Convert.ToInt32(textBox1.Text));
cmd.Parameters.AddWithValue("#isyeri", comboBox1.Text ?? DBNull.Value);
cmd.Parameters.AddWithValue("#isalani", comboBox2.Text ?? DBNull.Value);
cmd.Parameters.AddWithValue("#isemridet", richTextBox1.Text ?? DBNull.Value);
cmd.Parameters.AddWithValue("#bastar", dateTimePicker1.Value ?? DBNull.Value);
cmd.Parameters.AddWithValue("#bittar", dateTimePicker2.Value ?? DBNull.Value);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}

Related

Adding to database using Oledb Syntax error in INSERT INTO statement

when i hit the add button to insert a new book, i get an error at cmd.ExecuteNonQuery(); Syntax error in INSERT INTO statement. Am i missing anything?
protected void btnAddBook_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Bookdb.accdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO Books (Title, Author, Price, Edition) VALUES (#Title, #Author, #Price, #Edition)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Title", TextBox1.Text);
cmd.Parameters.AddWithValue("#Author", TextBox2.Text);
cmd.Parameters.AddWithValue("#Price", TextBox3.Text);
cmd.Parameters.AddWithValue("#Edition", TextBox4.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The only reason that I can find as a possible failure for your code is if the Price field is a numeric field in your database table. You are creating a parameter with AddWithValue and this method creates a parameter whose datatype is derived from the datatype of the value passed. You pass a string (TextBox3.Text) and so AddWithValue creates a string parameter.
You could try to force the AddWithValue to create a numeric parameter with
cmd.Parameters.AddWithValue("#Price", Convert.ToDecimal(TextBox3.Text));
(Of course assuming a decimal Price column)
Right before you call conn.Open(), you need to call cmd.Prepare(), so that all the parameters you set are actually loaded into the SQL statement.

INSERT error ASP.NET

Hey I get an error saying there is something wrong with my code when inserting into a database, can't quite find it. The error suggests it is something in the INSERT statement, but appears on the line "cmd.ExecuteNonQuery();". I'm using an access database.
Error: Syntax error in INSERT INTO statement.
con.Open();
string mysql;
mysql = "INSERT INTO [User](FirstName,Surname,Age,HouseNumber,PostCode,Username,Password)
VALUES (?,?,?,?,?,?,?)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddWithValue("#p1", tbFirstName.Text);
cmd.Parameters.AddWithValue("#p2", tbSurname.Text);
cmd.Parameters.AddWithValue("#p3", int.Parse(tbAge.Text));
cmd.Parameters.AddWithValue("#p4", tbAddress1.Text);
cmd.Parameters.AddWithValue("#p5", tbPostCode.Text);
cmd.Parameters.AddWithValue("#p6", tbUsername.Text);
cmd.Parameters.AddWithValue("#p7", tbPassword.Text);
cmd.ExecuteNonQuery();
con.Close();
when you add parameters with value you need to convert it to matching type, if age is number then
cmd.Parameters.AddWithValue("#p3", int.Parse(tbAge.Text));
and also User is key word you can try with
"INSERT INTO [User] ([FirstName], [Surname], [Age], [HouseNumber], [PostCode], [Username], [Password]) VALUES (?,?,?,?,?,?,?)";
Have you tried replacing the ? with your parameters?
Correction: I believe you have to add OleDBParameters like so:
con.Open();
string mysql;
mysql = "INSERT INTO User(FirstName,Surname,Age,HouseNumber,PostCode,Username,Password)
VALUES (#p1,#p2,#p3,#p4,#p5,#p6,#p7)";
OleDbCommand cmd = new OleDbCommand(mysql, con);
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#p1", tbFirstName.Text),
new OleDbParameter("#p2", tbSurname.Text),
...
});
cmd.ExecuteNonQuery();
con.Close();

DataAdapter.UpdateCommand not working c#?

I am using this code to update "SOME" columns in a table in my database. But everytime I try to do so an error is given.
No value given for one or more required parameters.
con.Open();
SlipDA = new OleDbDataAdapter();
string sqlUpdate = "Update tbl_Slip SET RaiseBasic=#RaiseBasic, OtherDed=#OtherDed, Arrears=#Arrears, Notes=#Notes WHERE SlipNo=#SlipNo";
SlipDA.UpdateCommand = new OleDbCommand(sqlUpdate, con);
SlipDA.UpdateCommand.Parameters.AddWithValue("#RaiseBasic", Convert.ToInt32(dRow[4].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#OtherDed", Convert.ToInt32(dRow[5].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#Arrears", Convert.ToInt32(dRow[7].ToString()));
SlipDA.UpdateCommand.Parameters.AddWithValue("#Notes", dRow[8].ToString());
SlipDA.UpdateCommand.Parameters.AddWithValue("#SlipNo", dRow[0].ToString());
SlipDA.UpdateCommand.ExecuteNonQuery();
con.Close();
The table contains 9 columns but I only want to update a few.
This Could be the problem :
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. For example: SELECT * FROM
Customers WHERE CustomerID = ?
source : this
so basically your query should be like this :
string sqlUpdate = "Update tbl_Slip SET RaiseBasic= ?, OtherDed= ?, Arrears= ?, Notes= ? WHERE SlipNo= ?";
try this
string sqlUpdate = "Update tbl_Slip SET RaiseBasic=#RaiseBasic, OtherDed=#OtherDed, Arrears=#Arrears, Notes=#Notes WHERE SlipNo=#SlipNo";
OleDbCommand UpdateCommand = new OleDbCommand(sqlUpdate, con);
UpdateCommand.Parameters.AddWithValue("#RaiseBasic", Convert.ToInt32(dRow[4].ToString()));
UpdateCommand.Parameters.AddWithValue("#OtherDed", Convert.ToInt32(dRow[5].ToString()));
UpdateCommand.Parameters.AddWithValue("#Arrears", Convert.ToInt32(dRow[7].ToString()));
UpdateCommand.Parameters.AddWithValue("#Notes", dRow[8].ToString());
UpdateCommand.Parameters.AddWithValue("#SlipNo", dRow[0].ToString());
con.Open();
UpdateCommand.ExecuteNonQuery();
con.Close();

how do i update data in access database using c# 2010

OleDbConnection vcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\SummerJob\DataBase.accdb");
string cmdtxt = "UPDATE Students SET S_Name = ?, S_Surname = ?, S_E-Mail = ? WHERE ID = ?";
OleDbCommand cmd = new OleDbCommand(cmdtxt, vcon);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("S_Name", EditName.Text);
cmd.Parameters.AddWithValue("S_Surname", editSurname.Text);
cmd.Parameters.AddWithValue("S_E-Mail", editMail.Text);
vcon.Open();
cmd.ExecuteNonQuery();
vcon.Close();
//i use this code but it says syntax error in update statement
Where is the last parameter ???
ID=?
Not sure, but I will bet that without that parameter your query doesn't look right to the parser.
You need to pass ID? via SqlParameter like this cmd.Parameters.AddWithValue("ID", Id.Text);
Also make sure that the parameters are added in the same order they occur

SQL - OleDbCommand not updating DB

I am using an OleBdCommand To Insert A record into a Db, but the update never persists.
Here is the Code
public void InsertCandidate(XElement element, ref OleDbDataAdapter adapter, OleDbConnection sqlConnStr)
{
if (sqlConnStr.State == ConnectionState.Broken || sqlConnStr.State == ConnectionState.Closed)
sqlConnStr.Open();
try
{
string query = "Insert Into Candidate Values(#priKey, #Name, #LName, #Phone, #Add)";
OleDbCommand InsertCandidate = new OleDbCommand(query, sqlConnStr);
InsertCandidate.Parameters.AddWithValue("priKey", element.Attribute("CAND_NUM").Value);
InsertCandidate.Parameters.AddWithValue("Name", element.Attribute("CAND_FNAME").Value);
InsertCandidate.Parameters.AddWithValue("LName", element.Attribute("CAND_LNAME").Value);
InsertCandidate.Parameters.AddWithValue("Phone", element.Attribute("CAND_PHONE").Value);
InsertCandidate.Parameters.AddWithValue("Add", element.Attribute("CAND_ADDRESS").Value);
InsertCandidate.ExecuteNonQuery();
}
catch (OleDbException ex)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + ex.Message);
}
}
NO exceptions, errors or anomalies are generated!
Any Advice
M
I even tried this.
//InsertCandidate.ExecuteNonQuery();
adapter.InsertCommand = InsertCandidate;
adapter.InsertCommand.ExecuteNonQuery();
*Thanks Every One *
Aiden's Code Worked, but i should have read Tony's Post Better hence i accepted his answer (he said it first)
Kind Regards
And Thanks Once Again!
Have you executed your SQL statement in isolation from your code to make sure it works?
As you have not posted the table definition it could be because you are not specifying the fields in your insert statement.
I'm not an OLEDB expert but all the examples I can find on the net use question marks in place of parameters. Try the SQL statement like this:
string query = "Insert Into Candidate Values(?, ?, ?, ?, ?)";
Update
Looking at the documentation for the OleDBCommand it will only throw an InvalidOperationException and not an OleDbException in the event of an error. You should add this exception handler and see if that gives you any more information.
Alternatively change your exception hanndler to catch the generic Exception type to see if you even get an exception.
string query = "Insert Into Candidate Values(?, ?, ?, ?, ?)";
OleDbCommand InsertCandidate = new OleDbCommand(query, sqlConnStr);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_NUM").Value);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_FNAME").Value);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_LNAME").Value);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_PHONE").Value);
InsertCandidate.Parameters.AddWithValue("#?", element.Attribute("CAND_ADDRESS").Value);
//InsertCandidate.ExecuteNonQuery();
adapter.InsertCommand = InsertCandidate;
adapter.InsertCommand.ExecuteNonQuery();
this will work!

Categories