error sql query with c# - c#

Please how to convert this line of code:
Dim da As New SqlDataAdapter("select * from View_1 where Words_Sh like N'" & Me.txbSearch.Text & "%'", con)
in c#
SqlDataAdapter da = new SqlDataAdapter("select * from View_1 where Words_Sh like N'" + this.txbSearch..Text + "%'", con);
// this line => error

You should alwasy use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And you should remove the extra dot in this.txbSearch..Text
SqlCommand cmd = new SqlCommand("select * from View_1 where Words_Sh LIKE ' + #txbSearch + '%'", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd, con);

Related

ASP.Net login : SQL query syntax error

I am building an sql query in c# to perform login, at the end of this I get a syntax error, but I can't figure out what causes the error
SqlDataAdapter sda = new SqlDataAdapter("Select * From bruker Where Brukernavn='"
+ Textbox1.Text + "' and Passord='" + TextBox2.Text"");
You are missing a "+" and you need to pass connection string or an SqlConnection as a second parameter
SqlDataAdapter sda = new SqlDataAdapter("Select * From bruker Where Brukernavn='" + Textbox1.Text + "' and Passord='" + TextBox2.Text +"","connectionString");
or
SqlDataAdapter sda = new SqlDataAdapter("Select * From bruker Where Brukernavn='" + Textbox1.Text + "' and Passord='" + TextBox2.Text +"",con);
Since the above code is vulnerable to sql injection, please use the below code which will prevent sql injection.
try
{
SqlConnection con = new SqlConnection("connectionString");
SqlCommand commnad = new SqlCommand("Select * From bruker Where Brukernavn=#username and Passord=#password", con);
commnad.Parameters.AddWithValue("#username", Textbox1.Text.Trim);
commnad.Parameters.AddWithValue("#password", Textbox2.Text.Trim);
//rest of the code
}
catch(Exception ex)
{
//log exception and re-throw or send a generic exception message to UI
throw;
}
finally
{
//close the connection
}
Please mark it as answer if that solves your issue.

Populate multiple text boxes with SqlDataReader

I am trying to populate 11 textboxes, using my database information.
private void button5_Click(object sender, EventArgs e)
{
SqlConnection CN = new SqlConnection();
CN.ConnectionString = cons;
try
{
CN.Open();
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "
' + comboBox1.text + '
"",
CN)
;
SqlDataReader myReader = cmd.ExecuteReader();
}
catch
{
MessageBox.Show("You failed!");
}
}
It always fails, not even able to get that right....
The error is in this line of code
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
It should be either like this
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + """, CN);
Or
SqlCommand cmd = new SqlCommand("SELECT Column1_name, column2_name FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);
As you have not selected any columns it didn't work as you expected.
And in the side note pass paramater value instead of passing the value straight from the field values. so that you can avoid SQL Injection
SqlCommand cmd = new SqlCommand("SELECT Column1_name, column2_name FROM Lista1 WHERE DescripcionNombre = #DescripcionNombre", CN);
cmd.Parameters.AddWithValue("#DescripcionNombre", comboBox1.text);
The first order of business would be to write this line properly:
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
That's not valid SQL or C#. You need to specify which columns to retrieve from the table. If want all columns then use a wildcard. The next order of business is to learn how to concatenate strings. If you want single quotes to be part of the string literal then they have to be inside the double quotes.
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);
That's quite elementary stuff. You should spend some time reading a tutorial or two.
Once that's done, you then need to actually read the data from the data reader. This can help with that. Note the use of parameters rather than string concatenation in those examples? You can learn more about that here.
SqlCommand cmd = new SqlCommand("SELECT FROM Lista1 WHERE DescripcionNombre = "' + comboBox1.text + '"", CN);
You are not selecting any columns or expressions in your SELECT
Your single and double quotes are backwards in the concatenation
You should get in the habit of using parameters instead of concatenating SQL (for several reasons, not the least of which is SQL Injection vulnerability)
A valid statement would be:
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '"
+ comboBox1.text
+ "'", CN);
You forget to mention column name which you need to fetch in query
Always use parameterized queries How does SQLParameter prevent SQL Injection
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre=#DescripcionNombre, CN);
cmd.Parameters.AddWithValue("#DescripcionNombre", comboBox1.text);
But your query should be like this
SqlCommand cmd = new SqlCommand("SELECT * FROM Lista1 WHERE DescripcionNombre = '" + comboBox1.text + "'", CN);

SqlDataAdapter error in c sharp

Hello I have an error with the data adapter in c sharp . How to fix?
SqlCommand cmd = new SqlCommand("select * from View_1 where Words_Sh LIKE ' + #txbSearch + '%'", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd, con)
;
Don't add a single quote and the plus sign before the parameter placeholder
SqlCommand cmd = new SqlCommand("select * from View_1 " +
"where Words_Sh LIKE #txbSearch + '%'", con);
Also, I prefer to concatenate the wildcard symbol directly inside the parameter value.
Not sure if it makes any difference, though, just a matter of preferences and less clutter in the query string.
SqlCommand cmd = new SqlCommand("select * from View_1 " +
"where Words_Sh LIKE #txbSearch", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text + "%");
EXAMPLE:
string commandText = "select * from View_1 " + "where Words_Sh LIKE #parameters"
cmd.Parameters.AddWithValue("#parameters", "Parameter 1");
Because of starting double quote, you should finish with double quotes before plus sign, but you can use single quote before double quote for LIKE operation.
SqlCommand cmd = new SqlCommand("select * from View_1 where Words_Sh LIKE '#txbSearch%'", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd, con);
SqlConnection con = new SqlConnection("");
SqlCommand cmd = new SqlCommand("select * from View_1 where Words_Sh LIKE ' + #txbSearch + '%'", con);
cmd.Parameters.AddWithValue("#txbSearch", this.txbSearch.Text);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;

datalist contol doesn't bind

I have to bind the datalist control as per the values inserted in the form of find frined.
here is my code:
protected void search_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Mahi\Documents\Visual Studio 2010\Projects\fc 6-4\fc\App_Data\fc.mdf;Integrated Security=True;User Instance=True");
cn.Open();
string str = "select unm='" + funm_txt.Text + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
SqlCommand cmd = new SqlCommand(str, cn);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataTable dt = new DataTable();
DataList1 .DataSource =dt;
DataList1.DataBind();
cn.Close();
}
There are few things I have noticed:
-First of all, you are highly vulnerable to sql-injection attacks as you are passing user entered values directly into the database. You can avoid this by using a parameterised query.
-Secondly, you need to filter the records in a WHERE clause. At the moment you are assigning user typed/selected values into a select query.
-And you need to use SelectedValue of dropdown list not SelectedItem
-Also you can use using() blocks to get SqlConnection and DataAdapter Disposed at the end.
Try this (Please replace col1, col2 as required and complete the query assigning all parameters):
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection("your_conn_string"))
{
string str = "Select Col1, Col2,... From profile " +
"Where unm = #unm and university= #uni and " +
"..." +
"ybatch = #ybatch";
SqlCommand cmd = new SqlCommand(str, cnn);
cmd.Parameters.AddWithValue("#unm",funm_txt.Text);
cmd.Parameters.AddWithValue("#uni",DDLuni.SelectedValue);
...
cmd.Parameters.AddWithValue("#ybatch",DDLbtch.SelectedValue);
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = cmd;
cnn.Open();
adapter.Fill(dt);
}
}
DataList1.DataSource =dt;
DataList1.DataBind();
try this,
cn.Open();
string str = "select unm='" + funm_txt.Text + "' , university='" + DDLuni.SelectedItem + "', city='"+ DDLcity .SelectedItem +"' , yjoin='" + DDLyjoin.SelectedValue + "' ,yleave= '" + DDLycom.SelectedValue + "', ybatch='" + DDLbtch.SelectedValue + "' from profile";
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataTable dt = new DataTable();
da.fill(dt);
DataList1 .DataSource =dt;
DataList1.DataBind();
cn.Close();
Add following code:
Your SqlDataAdapter and SqlCommand is not communicating.
and you haven't filled Datatable with the result.
da.SelectCommand = cmd;
da.fill(dt);

Shortening data access code... would this work?

I am querying for data, if the data does not exist, I insert it. if it does, I do something else:
SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = '" + orderNo + "';", connection);
SqlDataReader checkHeadReader = checkHead.ExecuteReader(CommandBehavior.SingleRow);
if (!checkHeadReader.HasRows)
{
checkHeadReader.Close();
addHead.ExecuteNonQuery();
}
But I wonder if there's a shorter way to code this? would the code below work?
SqlCommand checkHead = new SqlCommand("SELECT * FROM TABLE WHERE ORDER_NO = ' + orderNo + "';", connection);
if(checkHead.ExecuteReader(CommandBehavior.SingleRow).HasRows)
addHead.ExecuteNonQuery();
else //this order already exists
Server.Transfer(#"~/Views/Error.aspx");
ExecuteScalar is great for this, E.g.
using (SqlCommand cmdCheck = new SqlCommand("Select Count(*) From Table Where Order_No = '" + orderNo + "'", connection))
{
int nExists = (int)cmdCheck.ExecuteScalar();
if (nExists==0) addHead.ExecuteNonQuery();
}

Categories

Resources