Additional information: Incorrect syntax near 's' [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Would you please tell me where is my mistake ?!?
I cannot find any incorrect syntax near any 's' !.
Here is my Code :
public static DataTable InsertConnect(ComboBox Site , ComboBox server , ComboBox Host , ComboBox Domain , Label Price)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = Server.Connection;
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "insert into tblPrice(Site,Server,Host,Domain,Price)
values('" + Site.Text + "','" + server.Text + "','" + Host.Text + "','" + Domain.Text + "','" + Price.Text + "')'";
SqlDataAdapter da = new SqlDataAdapter(cmd.CommandText, cn);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}

The reason because you don't using SqlParameter for passing values to the query.
If you have used parameters then you will not have such a problem as some extra ' character in your query.
Always use SqlParameters.
public static DataTable InsertConnect(ComboBox Site , ComboBox server , ComboBox Host , ComboBox Domain , Label Price)
{
using (var cn = new SqlConnection(Server.Connection))
{
cn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = cn;
cmd.CommandText = "insert into tblPrice(Site,Server,Host,Domain,Price) values (#Site, #Server, #Host, #Domain, #Price)";
var parameters = new[]
{
new SqlParameter { ParameterName = "#Site", .SqlDbType = SqlDbType.VarChar, .Value = Site.text },
new SqlParameter { ParameterName = "#Server", .SqlDbType = SqlDbType.VarChar, .Value = server.text },
new SqlParameter { ParameterName = "#Host", .SqlDbType = SqlDbType.VarChar, .Value = Host.Text },
new SqlParameter { ParameterName = "#Domain", .SqlDbType = SqlDbType.VarChar, .Value = Domain.Text },
new SqlParameter { ParameterName = "#Price", .SqlDbType = SqlDbType.VarChar, .Value = Price.Text }
}
cmd.Parameters.AddRange(parameters);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
Then you can use constructor of SqlDataAdapter which takes SqlCommand as parameter, because your cmd contain all needed information for running query.

The problem is probably in one of the parameters which contains an apostrophe ('). Try to print out cmd.CommandText and you will see that it is not a valid SQL command.
On a related note, that is the foundation of SQL injection. Solution is not to construct SQL commands by concatenating values, especially strings. Instead, use command parameters and construct parameterized commands.
You can learn more on MSDN: How to: Execute a Parameterized Query

Related

'ExecuteReader: Connection property has not been initialized.' [duplicate]

This question already has answers here:
ExecuteReader: Connection property has not been initialized
(7 answers)
Closed 1 year ago.
I am new to C# and I have been trying to create a login using ADO.NET and WinForm but when I try logging in I get this error;
System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.'
I don't seem to know what is wrong.
private void bteAdminLog_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=DESKTOP-RCPAL7F;Initial Catalog=iCubeDB;Integrated Security=True";
con.Open();
String txtUser = txtUsername.Text;
String txtPass = txtPassword.Text;
string query = "SELECT * FROM AdminLogin WHERE Username =#user AND Password = #Pass";
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add(new SqlParameter("#user", txtUser));
cmd.Parameters.Add(new SqlParameter(" #Pass", txtPass));
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows == true)
{
MessageBox.Show("Done");
}
else
{
MessageBox.Show("not done");
}
}
Your SqlCommand didn't pass in with the query and conn
You should do it as:
SqlCommand cmd = new SqlCommand(query, con);
And for the Parameters part, you set the parameter with a respective datatype includes length/size (match with your database column) and then assign the value for each parameter:
cmd.Parameters.Add("#user", SqlDbType.Varchar, 10).Value = txtUser;
cmd.Parameters.Add("#Pass", SqlDbType.NVarchar, 50).Value = /* hashed txtPass */;
The third parameter in cmd.Parameters.Add() is for datatype's size/length.
UPDATED:
[1st edit version]
As confirmed with Post Owner that the passwords stored are hashed in the database. Thus I remove the previous remark.
[2nd edit version]
Thanks for #Charlie 's concern, so I edit the answer to include the data type's length/size.
References:
SqlCommand
Reason not to apply AddWithValue()

System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.' on Datatable and object

I've looked at a lot of similar questions on this site and elsewhere but none of them have helped me.
I'm trying to make a database connection with a query but I get the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
on 2 different lines of code. I've tried to use spaces in the query around the = but that doesn't help.
Code 1 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = #attackCategory WHERE TaughtOn = #taughtOn";
using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
The exception is thrown on the sda.Fill(dt); line of code. This code works if no parameters are used in the query:
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
And code 2 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = #attackCategory WHERE ID = #ID";
connection.Open();
object name = select.ExecuteScalar();
connection.Close();
return name;
The exception fires on the object name = select.ExecuteScalar(); line of code. This code works if 1 parameter is used in the query:
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=#ID";
You cannot provide table name has parameter, parameter applies in where clause with columns value.
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
but, we need to simplify to use parameter in this query.
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
In the above tsql query, string concatenation applies and table name is included in the string, which will work.
Edit:-
I get it why you the sqlDataAdapter is not Recognizing the parameter.
Reason is you have not provided it. Yes, That's right you have provided the CommandText and not the Command Object which is of select variable.
I have corrected your code.
select.Parameters.Add("#taughtOn", SqlDbType.VarChar, 50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope this helps !!
You can't bind object names like that. For object names, you'll have to resort to some sort of string concatenation. E.g.:
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM " + attackCategory + " WHERE TaughtOn=#taughtOn";
Note:
This is an over-simplified solution that does nothing to mitigate the risk of SQL-Injection attacks. You'll need to sanitize attackCategory before using it like this.

Procedure or function 'spAddEmployee' expects parameter '#name', which was not supplied [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
My create form need to get access from stored procedure, when I ran the application I am getting this error:
Procedure or function 'spAddEmployee' expects parameter '#name', which was not supplied
C# code:
string connectionstring = ConfigurationManager.ConnectionStrings["AddEmployee"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand("dbo.spAddEmployee", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlParameter paramname = new SqlParameter();
paramname.ParameterName = "#Name";
paramname.Value = employee.Name;
cmd.Parameters.Add(paramname);
SqlParameter paramgender = new SqlParameter();
paramname.ParameterName = "#gender";
paramname.Value = employee.Gender;
cmd.Parameters.Add(paramgender);
SqlParameter paramcity = new SqlParameter();
paramname.ParameterName = "#city";
paramname.Value = employee.City;
cmd.Parameters.Add(paramcity);
SqlParameter paramdateofbirth = new SqlParameter();
paramdateofbirth.ParameterName = "#dateofbirth";
paramname.Value = employee.Dateofbirth;
cmd.Parameters.Add(paramdateofbirth);
cmd.ExecuteNonQuery();
con.Close();
}
my procedure code is given in snapshot
Please help me
You are using the same SqlParameter object(paramname) which you used for Name for Gender and City. So it is basically overwriting the value with first Gender and then City. So i assume your City value is null hence it is throwing an error.
This should work
using (var con = new SqlConnection(connectionstring))
{
var cmd = new SqlCommand("dbo.spAddEmployee", con) {
CommandType = CommandType.StoredProcedure};
con.Open();
var paramname = new SqlParameter
{
ParameterName = "#Name",
Value = employee.Name
};
cmd.Parameters.Add(paramname);
var paramgender = new SqlParameter
{
ParameterName = "#gender",
Value = employee.Gender
};
cmd.Parameters.Add(paramgender);
var paramcity = new SqlParameter
{
ParameterName = "#city",
Value = employee.City
};
cmd.Parameters.Add(paramcity);
var paramdateofbirth = new SqlParameter
{
ParameterName = "#dateofbirth",
Value = employee.Dateofbirth
};
cmd.Parameters.Add(paramdateofbirth);
cmd.ExecuteNonQuery();
}

Update table record from sqlcommand

I have this situation: in DataEntryForm I have a dropdownlist, where user selects a letter number, and according to that inserts other related data.
I plan to change letter's status in other table by choosing in dropdownlist automatically.
I am using this code:
SqlParameter answertoparam = new SqlParameter("answerto", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID ='2' where income_number=('" + ansTo + "' )";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
comm.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
Unfortunately, the result is nothing.
Server is not giving error, and it simply refreshes the page that is it.
In your posted code, you are passing the SqlParameter as well as passing the value as raw data. Do either of one and preferably pass it as SqlParameter like
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
Moreover, you have two SqlCommand object in place and calling two ExecuteNonQuery() on them. correct that ... see below
SqlCommand findincomelett = new SqlCommand(commandText, conn); --1
comm.Parameters.Add(answertoparam); --2
conn.Open();
findincomelett.ExecuteNonQuery(); --1
comm.ExecuteNonQuery(); --2
As far as I understand, the issue is that the correct IncomeLetters.docState_ID is not updated to '2'.
You may want to debug and see what value you are getting in :
string ansTo = ddlAnswerTo.SelectedItem.Value;
The record in the database that you are expecting to be updated may not have the record that satisfies the where clause 'income_number = #answertoparam'
I would like to bring you here full code of the page.
Idea is: I have page for enrollment. I am passing data to DB through stored procedure (DataInserter).
Problem is here: during enrollment, user selects from dropdownlist number of the letter he would like to answer to, and in the end, the status of the letter on other table of DB (IncomeLetters.tbl), would change from "pending"('1') to "issued" ('2').
I guess, I could clear my point to you and thank you for your support!
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MaktubhoConnectionString2"].ConnectionString);
using (SqlCommand comm = new SqlCommand("DataInserter", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
SqlParameter employeeparam = new SqlParameter("EmployeeSentIndex", int.Parse(ddlemployee.SelectedItem.Value));
SqlParameter doctypeparam = new SqlParameter("doctype_ID", int.Parse(ddldoctype.SelectedItem.Value));
SqlParameter doccharparam = new SqlParameter("docchar_ID", int.Parse(ddldocchar.SelectedItem.Value));
SqlParameter authorityparam = new SqlParameter("authority", txtauthority.Text);
SqlParameter subjectparam = new SqlParameter("subject", txtsubject.Text);
DateTime dt = DateTime.Now;
string todasdate = dt.ToString("d", CultureInfo.CreateSpecificCulture("de-DE"));
SqlParameter entrydateparam = new SqlParameter("entrydate", todasdate);
string Pathname = "UploadImages/" + Path.GetFileName(FileUpload1.PostedFile.FileName);
SqlParameter imagepathparam = new SqlParameter("image_path", Pathname);
SqlParameter loginparam = new SqlParameter("login", "jsomon");
comm.Parameters.Add(employeeparam);
comm.Parameters.Add(doctypeparam);
comm.Parameters.Add(doccharparam);
comm.Parameters.Add(authorityparam);
comm.Parameters.Add(subjectparam);
comm.Parameters.Add(entrydateparam);
comm.Parameters.Add(imagepathparam);
comm.Parameters.Add(loginparam);
comm.Parameters.Add("#forlabel", SqlDbType.VarChar, 100);
comm.Parameters["#forlabel"].Direction = ParameterDirection.Output;
FileUpload1.SaveAs(Server.MapPath("~/UploadImages/" + FileUpload1.FileName));
string ansTo = ddlAnswerTo.SelectedItem.Value;
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
lblresult.Visible = true;
Image1.Visible = true;
lblresult.Text = "Document number:";
lblnumber.Visible = true;
lblnumber.Text = (string)comm.Parameters["#forlabel"].Value; ;
conn.Close();
}
txtauthority.Text = "";
txtsubject.Text = "";
}

Updating and persisting dataset problem

I think I'm missing sth. trivial here : I want to update a dataset and push it back to the database where it came from, but I am keep getting a :
Concurrency violation: the
UpdateCommand affected 0 of the
expected 1 records.
Here's some code producing this error :
public static void UpdateNorthWindWithDataset()
{
string connString =
#"Data Source=localhost;Initial Catalog=NorthWind;Integrated Security=SSPI;";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Declaring a DataAdapter and initiating it with a Select and updateCommand
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand selectCmd = new SqlCommand("SELECT CustomerId, City, Region " +
"FROM Customers"
, conn
);
da.SelectCommand = selectCmd;
SqlCommand updateCmd = new SqlCommand(
#"UPDATE Customers SET City='#City', Region='#Region'" +
#"WHERE CustomerID = '#CustomerID'",
conn
);
updateCmd.Parameters.AddRange(
new SqlParameter[]
{
new SqlParameter()
{
ParameterName = "#CustomerID",
SourceColumn = "customerid"
},
new SqlParameter()
{
ParameterName = "#City",
SourceColumn = "city",
SqlDbType = SqlDbType.VarChar
},
new SqlParameter()
{
ParameterName = "#Region",
SourceColumn = "region",
SqlDbType = SqlDbType.VarChar
}
}
);
da.UpdateCommand = updateCmd;
// filling dataset
DataSet ds = new DataSet();
da.Fill(ds, "srcCustomers");
// declaring and editing datatable
DataTable tblCustomers = ds.Tables["srcCustomers"];
foreach (DataRow row in tblCustomers.Rows)
{
row["City"] = "justUpdated";
row["Region"] = "justUpdated too";
}
da.Update(ds, "srcCustomers");
}
}
Now, my endgoal is using this kind of code with MsAccess throug OLEdb, but because I wanted it as clear as possible, I tried MSSQL (still 2k here) with native .net support but still got the error...
The update is failing because it can't find a record that matches the customer ID supplied and I think that that is because the parameter value is not being defaulted - there are additional values for the SQL parameters that will allow you to do this.
If you're looking at OLEDB you need to be aware that the parameters are not named (you can and probably should name them, but they will be used in the order they are entered and not according to their names - this also means you can't use the same parameter twice which can be a bit tedious).

Categories