The multi-part identifier "sxxx#yahoo.com" could not be bound [duplicate] - c#

This question already has answers here:
The multi-part identifier "TextBox1.Text" could not be bound in C# ASP.NET?
(3 answers)
Closed 9 years ago.
if (validateEmailId(email))
{
pictureBox5.Visible = true;
SqlConnection con = new SqlConnection("conection string");
SqlCommand cmd2 = new SqlCommand("UPDATE sumant SET email=" + email + " WHERE code ='" + textBox2.Text + "' ", con);
cmd2.Connection = con;
cmd2.Connection.Open();
cmd2.ExecuteNonQuery();//line 7
con.Close();
}
validateEmailId is a function which validates the email entered(using regular expression)..
The email entered in the 'email' textbox is validated and is returned to the above function..
When the control passes to line 7 following error is encountered:
The multi-part identifier "sxxx#yahoo.com" could not be bound.
It means sxxx#yahoo.com has passed the validation test, but a problem occurred in line 7.
On the SQL end, the column 'email' has varchar(50) as its data type...I don't think that's an issue....

You should at least put single quotes around the email adress:
SqlCommand cmd2 = new SqlCommand("UPDATE sumant SET email='" + email + "' WHERE code ='" + textBox2.Text + "' ", con);
However, this is not a good way of passing in params, as you are leaving this wide open for SQL injection attacks...
A better way would be to use a parameterized query, like this:
SqlCommand cmd2 = new SqlCommand("UPDATE sumant SET email=#email WHERE code=#code", con);
cmd2.Parameters.AddWithValue("#email", email);
cmd2.Parameters.AddWithValue("#code", textBox2.Text);
Then you don't need to supply the single quotes, and you're at the same time safeguarding against SQL injection attacks...

Ouch, I smell SQL injection and lack of disposal. Try this:
using (SqlConnection con = new SqlConnection("conection string")) {
using (SqlCommand cmd2 = new SqlCommand("UPDATE sumant SET email=#Email WHERE code = #Code", con)) {
cmd2.Parameters.AddWithValue("#Email", email);
cmd2.Parameters.AddWithValue("#Code", textBox2.Text);
con.Open();
cmd2.ExecuteNonQuery();
}
}
The using directives will close the SqlConnection and SqlCommand no matter if they fail or execute properly. The SqlParameters will prevent any form of SQL injection.
Another sidenote: your passing the conn argument to the SqlCommand constructor AND are setting the connection property of the SqlCommand after that, passing the SqlConnection to the SqlCommand already sets the connection property.

Related

ADODB connection vs SqlConnection in C# use cases

I am trying to convert an old project (originally written in VB6) to C#. I came across the following snippet of code (roughly) :
Dim sSql As String
Dim adoRs As ADODB.Recordset
sSql = "EXEC " & PROC_GETEPORTPARAMETERVALUES & " " & iTemplateId & ", " & iViewId & ", " &
g_sTenantSN
Set adoRs = Nothing
' Execute the query
Set adoRs = m_odbcDVConnection.OpenRecordSet(sSql, App.EXEName, Me.Name, csPROC_NAME)
If (adoRs.RecordCount > 0) Then
Do Until (adoRs.EOF)
'Some conditional statements within this block
Loop
End If
After doing some research online, I came up with the following code conversion for C#. I have used SqlConnection here. Eventhough I found that ADODB is available to use for C# as well. But not sure which one to use.
sSql = "EXEC " + PROC_GETEPORTPARAMETERVALUES + " " + iTemplateId + ", " + iViewId + ", " +
GlobalHelper.Tenant;
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
if (conn.State != ConnectionState.Open)
{
conn.Open();
}
SqlCommand cmd = new SqlCommand(sSql);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
// Conditional statements
}
I am not entirely sure if the above is a proper converison is proper. But more importantly, I wanted to know when to use ADODB connection and when to use SqlConnection for C# projects.
From my understanding, in the above case, I think both the process executes a SQL command and reads records.
ADODB is not normally used in C#. You should always use SqlClient.
You have a number of issues with your converted code:
You are missing using blocks
No need to, nor should you, inject parameters. Pass them properly using SqlParameter
You should also use CommandType.StoredProcedure, and the command text is then just the procedure name. If you wanted to use Text it is the default, no need to set it.
There is no point checking if the connection is not open, of course it isn't as you just created it
using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]))
using (SqlCommand cmd = new SqlCommand(PROC_GETEPORTPARAMETERVALUES))
{
cmd.CommandType = CommandType.StoredProcedure;
// Specify correct parameter type, add parameter length for strings
cmd.Parameters.Add("#iTemplateId", SqlDbType.NOT_SURE_WHAT_YOU_WANT_HERE).Value = iTemplateId;
cmd.Parameters.Add("#iViewId", SqlDbType.NOT_SURE_WHAT_YOU_WANT_HERE).Value = iViewId;
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// Conditional statements
}
}
}

Accessing Listbox Results View in C#

Hi there guys i am sure this is quite easy i am just completely new to C#.
So I can read the SQL database and bring back results but I cant figure out how to read the returning result which should then be inserted into the Database.
Any idea how I can read the Result View because i can see the value i want in there. Value for this example is 'AS'
SqlConnection con = new SqlConnection("Data Source=###;Initial Catalog=######;Persist Security Info=True;User ID=##;Password=#######");
SqlCommand cmd = new SqlCommand("Select ISOCode from Countries Where CountryName like '" + CTRYLST.SelectedItem + "%'", con);
con.Open();
CTRYLST.Items.Clear();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
CTRYLST.Items.Add(sdr.GetString(0));
}
}
SqlCommand cmd2 = new SqlCommand("INSERT INTO CountryNoMail (ISOCode) VALUES ('" + CTRYLST.Items.ToString() + "');", con);
cmd2.ExecuteNonQuery();
con.Close();
Assuming the sql is correct and everything is fine with the reading, eventually you can inspect the values at runtime by adding a break in the line of additems
You will be able top get back your values by using
CTRYLST.Items[0].ToString;
But it is always preferrable to use a for and cycle since you cannot be sure how many items there will be in the list box. Be careful that items are zerobased, so the first element has 0 as index, the first has 1 and so on.

Error with SQLDataReader

C#, Razor
my code is:
#using (SqlConnection Praktikum2 = new SqlConnection("Data Source=Mark\\SQLEXPRESS;Initial Catalog=Connection;Integrated Security=True"))
{
using(connection)
{
SqlCommand command = new SqlCommand("SELECT KategoryID FROM Kategory WHERE Name = " + Request.Params["kategory"]);
connection.Open();
SqlDataReader reader = command.ExecuteReader(); //ERROR!!!
while (reader.Read())
{
string ID = reader["KategorieID"].ToString() ;
Console.WriteLine("ID = {0}", ID);
}
reader.Close();
};
}
i get an error that there's a wrong syntax near "=".
how can i solve this?
The problem is caused by the missing quotes around the value passed for your search. You could add a set of single quote before and after the value obtained by the Request but that would be a bigger error and the source of a problem called Sql Injection.
The only way to handle this is to use a parameter query
SqlCommand command = new SqlCommand(#"SELECT KategoryID FROM Kategory
WHERE Name = #name", connection);
command.Parameters.Add("#name", SqlDbType.NVarChar).Value = Request.Params["kategory"];
Also, as noted in another answer, your code seems to not have associated the connection to the command, I think that it is just a typo here because the error message in that case would be 'need an open connection'
You forgot to assign the connection to the command. So when you call ExecuteReader(), it does not know on which connection it should be executed.
You can assign the connection like this:
SqlCommand command = new SqlCommand(
"SELECT KategoryID FROM Kategory WHERE Name = " + Request.Params["kategory"],
connection); // provide connection as second parameter!
or use connection.CreateCommand() to create your command.
Second, you forgot the quotation marks around your string:
"SELECT KategoryID FROM Kategory WHERE Name = '" + Request.Params["kategory"] + "'"
but inserting user data directly into your query opens your code to SQL Injection. Please use parameterized queries instead.
If your kategory column is not of integer data type then you need to surround your value with (') i.e single quote characters
Then your query will be like
SqlCommand command = new SqlCommand("SELECT KategoryID FROM Kategory WHERE Name ='" + Request.Params["kategory"] + "'");
The exception is caused by how you are creating your sql statement. The fix should not be correcting the syntax but using parameters instead. This will prevent sql injection attacks.
Also
You really should not be writting sql in your views, do it in your controller method instead and return the result in the Model to be used in your view. Better yet, abstract it to a different layer and call that layer from your controller. This has to do with SoS (Separation of Concerns), your code will very difficult to maintain if you just write everything into your views.
Wrap your connections, commands, and readers in using blocks.
Modified Code
#{
using(SqlConnection Praktikum2 = new SqlConnection("Data Source=Mark\\SQLEXPRESS;Initial Catalog=Connection;Integrated Security=True"))
using(SqlCommand command = new SqlCommand("SELECT KategoryID FROM Kategory WHERE Name = #name", Praktikum2))
{
command.Parameters.Add(new SqlParameter("#name", SqlDbType.VarChar){ Value = Request.Params["kategory"]});
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string ID = reader["KategorieID"].ToString() ;
Console.WriteLine("ID = {0}", ID);
}
}
}
}

Letting the user add values into the database

I'm running a database in SQL2012 and using Visual Studio2012 C# to build a software that interacts with the database, and I've been trying to add a button that interacts with a textbox or something similar that lets the user add/edit rows in the database.
Code:
try
{
string conString = "Data Source=MIRANDA-PC;Initial Catalog=Futebol do Rosa;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);
string selectSql = "Update Players$ SET Player Name='" + textBox3.Text + "' WHERE Player ID= 1";
SqlCommand cmd = new SqlCommand(selectSql, con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("The values have been UPDATED");
}
catch{
MessageBox.Show("not so fast ***, error found in your ******** code");
}
Ignoring the safety issues (inline SQL is bad. Very bad.) Your update has some fundamental errors. Try:
string selectSql = "Update Players SET Players.Name='" + textBox3.Text +
"' WHERE Players.ID= 1";
Your table columns need to be associated to the table with a . and the table name has to be the same as the one you are updating. I am going on the assumption here that your table name is Players
The code in your link isn't even safe.
Your SqlConnction and SqlCommand will not dispose
The end user can use SQL Injection
Throw your SqlConnection and SqlCommand in an using statement.
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("your query here", con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}
Add parameters to your SqlCommand to avoid SqlInjection
cmd.Parameters.AddWithValue("#param", value);
Create your own class for database interaction and don't put everything in one class or form.
If you let us know what the error is, we can help you more.
Also a good thing is to google your error first.

c# register form mysql insert

So im having problem gettin some data in to the database.. Im really stuck, im quite new to c# and have not learned all keywords yet, im not getting any errors just some nothing adds to my database.
textBox2.Text = myPWD;
MySqlConnection conn = new MySqlConnection("test")
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES ('values = #val')";
MySqlCommand data = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
SelectCommand.Parameters.AddWithValue("#val", this.textBox2.Text);
conn.Closed()
Manipulate the concatenation of value in passing of parameters. Don't do it inside sql statement.
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES (#val)";
// other codes
SelectCommand.Parameters.AddWithValue("#val", "values = " + this.textBox2.Text);
the reason why the parameter is not working is because it was surrounded by single quotes. Parameters are identifiers and not string literals.
The next problem is you did not call ExecuteNonQuery() which will execute the command.
Before closing the connection, call ExecuteNonQuery()
// other codes
data.ExecuteNonQuery();
conn.Close();
You should Google around and you will receive lots of content
You need to run ExecuteNonQuery
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('11','seed');", con);
cmd.ExecuteNonQuery();
cmd.Close();

Categories

Resources