How to break a line? [duplicate] - c#

This question already has answers here:
How to add line break in C# behind page
(11 answers)
Closed 8 years ago.
I have this line :
cmd.CommandText = "SELECT registeruser_id,registeruser_username, registeruser_email,registeruser_password FROM TestDB_RegisterUser where registeruser_email='" + email + "' and registeruser_password='" + pwd + "' and registeruser_rowstate<3 ";
And when I try to hit Enter on part of the string , I get a big bunch of red lines that indicates that what I did is considered as error .
How do I break it then ? thanks

Yes, because a regular string literal can't include a line break in the source code. You can include one in a verbatim string literal however:
string sql = #"SELECT FOO
FROM BAR
WHERE X=Y";
Or break it with string concatenation:
string sql = "SELECT FOO " +
"FROM BAR " +
"WHERE X=Y";
More importantly, however, you're currently building your SQL in a horribly insecure way. Never include values directly in the SQL like this. Instead, use parameterized SQL and then specify values for the parameters:
string sql = "SELECT FOO FROM BAR WHERE X=#X";
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#X", SqlDbType.NVarChar).Value = "...";
using (var reader = command.ExecuteReader())
{
...
}
}

Related

Remove a specific character from a string to make INSERT accept string with quotes [duplicate]

This question already has answers here:
Parameterized Query for MySQL with C#
(6 answers)
Closed 4 years ago.
Not sure this question has been asked before though. If it were, my apologies.
I need to remove an apostrophe character from a string.
The reason for this has to be done because it's triggering an error in the SQL query for client's name which I fetch from the local database.
The error indicates near the 'apostrophe s'.
When I remove that data field from the local database error ain't appear.
I came up with a solution for removing the apostrophe character from the client name.
I tried to use Remove() function but it only works for integers. (string to int conversion error).
My code is as follows:
while (rdr.Read())
{
int promised_date = (int)(rdr.GetValue(0));
string strClientName = (rdr.GetValue(1).ToString());
string strClientReference = (rdr.GetValue(2).ToString());
string strJobCategory = (rdr.GetValue(3).ToString());
string datCommisioned = (rdr.GetValue(4).ToString());
string datPromisedDelivery = (rdr.GetValue(5).ToString());
if (this.OpenConnection() == true)
{
string querynew = "INSERT INTO jobs_table (nJobNumber,strClientName,strClientReference,strJobCategory,datCommisioned,datPromisedDelivery) VALUES ("+promised_date+",'"+strClientName+"','"+strClientReference+"','"+strJobCategory+"','"+datCommisioned+"','"+datPromisedDelivery+"' )";//yeyyy why only few?
MySqlCommand cmd = new MySqlCommand(querynew, connection);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}
Does anyone have an idea how to remove the apostrophe from strClientName when reading the data?
You should use parameters. You can read more about here: https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html
while (rdr.Read())
{
int promised_date = (int)(rdr.GetValue(0));
string strClientName = (rdr.GetValue(1).ToString());
string strClientReference = (rdr.GetValue(2).ToString());
string strJobCategory = (rdr.GetValue(3).ToString());
string datCommisioned = (rdr.GetValue(4).ToString());
string datPromisedDelivery = (rdr.GetValue(5).ToString());
if (this.OpenConnection() == true)//closing parenthesis
{
// query using parameter names
string querynew = "INSERT INTO jobs_table "
+ "(nJobNumber,strClientName,strClientReference,strJobCategory,datCommisioned,datPromisedDelivery)"
+ "VALUES (#PromisedDate, #ClientName, #ClientReference, #JobCategory, #Commisioned, #PromisedDelivery)";
MySqlCommand cmd = new MySqlCommand(querynew, connection);
// add parameters and their value
cmd.Parameters.AddWithValue("#PromisedDate", promised_date);
cmd.Parameters.AddWithValue("#ClientName", strClientName);
cmd.Parameters.AddWithValue("#ClientReference", strClientReference);
cmd.Parameters.AddWithValue("#JobCategory", strJobCategory);
cmd.Parameters.AddWithValue("#Commissioned", datCommissioned);
cmd.Parameters.AddWithValue("#PromisedDelivery", datPromisedDelivery);
cmd.ExecuteNonQuery();
this.CloseConnection();
}
}

error in query in asp.net [duplicate]

This question already has answers here:
SQL Server Invalid column name when adding string value
(5 answers)
Closed 6 years ago.
Error is showing that invalid column name mustufain.
mustufain is the value of UserName.Text.toString()
string query = "select userid from register where username = " + UserName.Text.ToString() + " and " + "password = " + Password.Text.ToString();
SqlCommand cmd1 = new SqlCommand(query,connection);
connection.Open();
SqlDataReader rd1 = cmd1.ExecuteReader();
while(rd1.Read())
{
Session["checkuserid"] = rd1["userid"];
}
connection.Close();
Firstly, you should not be using string concatenation to build your queries as it can leave you vulnerable to things like SQL Injection attacks and it can cause issues with your queries being incorrect (as you are missing tick marks around your parameters) :
// This would attempt to state username = mustufain instead of
// username = 'mustufain' (and SQL doesn't know what mustufain is)
var query = "select userid from register where username = '" + UserName.Text + "' and " + "password = '" + Password.Text + "'";
A better approach using parameterization would look like the following, which avoids the incorrect syntax and offers you protection against any nasty injections :
// Open your connection
using(var connection = new SqlConnection("{your connection string}"))
{
// Build your query
var query = "SELECT TOP 1 userid FROM register WHERE username = #username AND password = #password";
// Build a command (to execute your query)
using(var command = new SqlCommand(query, connection))
{
// Open your connection
connection.Open();
// Add your parameters
command.Parameters.AddWithValue("#username",UserName.Text);
command.Parameters.AddWithValue("#password",Password.Text);
// Execute your query
var user = Convert.ToString(command.ExecuteScalar());
// If a user was found, then set it
if(!String.IsNullOrEmpty(user))
{
Session["checkuserid"] = user;
}
else
{
// No user was found, consider alerting the user
}
}
}
Finally, you may want to reconsider how you are storing your credentials (in clear text). ASP.NET offers a wide variety of providers that can help handle this process for you so that you don't have to do it yourself.
You are trying to concatenate strings to build an sql query and, as usual, you get errors. In your specific case you forget to enclose your string values between single quotes. But the only correct way to do this query is by the way of a parameterized query
string query = #"select userid from register
where username = #name and password = #pwd";
using(SqlCommand cmd1 = new SqlCommand(query,connection))
{
connection.Open();
cmd1.Parameters.Add("#name", SqlDbType.NVarChar).Value = UserName.Text;
cmd1.Parameters.Add("#pwd", SqlDbType.NVarChar).Value = Password.Text;
using(SqlDataReader rd1 = cmd1.ExecuteReader())
{
....
}
}
Notice also that storing passwords in clear text in your database is a very bad practice and a strong security risk. On this site there are numerous questions and answers that explain how to create an hash of your password and store that hash instead of the clear text
For example: Best way to store passwords in a database

Where clause throws error [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 7 years ago.
Improve this question
Why does this code throw an error?
using (MySqlConnection cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
{
{
MySqlCommand Command = new MySqlCommand();
Command.Connection = cn;
Command.CommandText = "UPDATE TeleworksStats SET Ja= ('" + JaTak +
"') WHERE Brugernavn = " + VarribleKeeper.Brugernavn + "' AND Dato = " +
DateTime.Today.ToString("yyyy-MM-dd") + "";
cn.Open();
Command.ExecuteNonQuery();
//Ryd op
Command.Dispose();
cn.Close();
}
}
Rather than just forgetting ' for the value of Brugernavn column and both single quotes for Dato column, I think you have more things to keep in mind.
Use using statement to dispose your Command object as you did for your connection instead of calling Close or Dispose methods manually.
Use paramterized queries instead of string concatenation. This kind of codes are open for SQL Injection attacks.
Looks like you try to save your DateTime values with their string representations. Do not do that! If you wanna keep your DateTime values to your database, you need to pass them directly. Change your Dato column to DateTime type. Read: Bad habits to kick : choosing the wrong data type
using(var cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
using(var Command = cn.CreateCommand())
{
Command.CommandText = #"UPDATE TeleworksStats SET Ja = #Ja
WHERE Brugernavn = #Brugernavn AND Dato = #Dato";
Command.Parameters.Add("#Ja", MySqlDbType.VarChar).Value = JaTak;
Command.Parameters.Add("#Ja", MySqlDbType.VarChar).Value = VarribleKeeper.Brugernavn;
Command.Parameters.Add("#Ja", MySqlDbType.DateTime).Value = DateTime.Today;
// I assumed your column types. You should write proper column types instead.
cn.Open();
Command.ExecuteNonQuery();
}
You missed one quote ' after Brugernavn = and Dato:
Brugernavn = "... '" + VarribleKeeper.Brugernavn + "' AND Dato = '" +
DateTime.Today.ToString("yyyy-MM-dd") + "'";
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection like this:
Command.CommandText =
"UPDATE TeleworksStats SET Ja = #Ja WHERE Brugernavn = #Brugernavn and ...";
Command.Parameters.AddWithValue("#Ja", JaTak);
Command.Parameters.AddWithValue("#Brugernavn", VarribleKeeper.Brugernavn);
Although specify the type directly and use the Value property is more better than AddWithValue. Check this: Can we stop using AddWithValue() already?

How can I insert Special char from textbox in to SQL table (Special char like 's , " or like ♥ ♫ )..?

string sql = "insert into tblmain values('" + txtName.Text + "','" + txtPost.Text + "','" + DropDownList1.SelectedItem + "')";
If the user inserts My name's first later is D ! in txtPost, then it gives error that 's are not allowed.
Can you please send me the code to accept this type of character from textbox in .net (C#).
You sample is the book example of SQL injection in most pure form. ' closes the previous quote and the rest of SQL command is interpreted differently from what you expect.
There is no excuses to not using parametrized queries when dealing with non-hardcoded values and SqlConnection directly.
Also check these articles for mre details. Approximate sample (need more fields and not showing exception handling):
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("insert into tblmain values(#name")", connection);
command.Parameters.Add("#name", SqlDbType.String);
command.Parameters["#name"].Value = customerID;
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
The second problem you may hit is if you pick wrong field type for the text - to be able to store characters you want you need Unicode string. Check out C#: DbType.String versus DbType.AnsiString post for details.

How to read output of Sqlcommand in C# [duplicate]

This question already has answers here:
SqlCommand read one value
(2 answers)
Closed 9 years ago.
I'm fetching date from the database and following is my command for it:
SqlCommand cmd = new SqlCommand("select dob from sample Where cardnum = '" + TextBox1.Text + "'");
How do i save the output of this command into datetime?
At the simplest:
var when = (DateTime)cmd.ExecuteScalar();
However, in the more general case you woulnd need to know about readers and parameters. Or: use a tool like dapper:
var when = conn.Query<DateTime>(
"select dob from sample Where cardnum = #num",
new { num = TextBox1.Text } // parameters, done right
).Single();
But dapper will read entire objects too (mapping properties to columns), not just single values.

Categories