SQL query from C# - c#

I am trying to query SQL Server database from C#
I have class
Class_A
{
public fetch((string name, string last_name))
{
SqlConnection conn = null;
double val = 0;
string server = "123.444.22.sss";
string dbase = "xyz";
string userid = "cnsk";
string password = "xxxxxx";
string connection = "Data Source=" + server + ";Initial Catalog=" + dbase
+ ";User ID=" + userid + ";Password=" + password;
conn = new SqlConnection(connection);
try
{
conn.Open();
}
catch(Exception)
{
string e = "Database error contact administrator";
MessageBox.Show(e, "Error!");
}
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from table where NAME"
+ " = name and LAST_NAME = last_name", conn);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
//do something
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return (0);
}
}
There is a problem in my query.
When I give normal query "select * from table" --- this gives me perfect results.
But when I try to give where condition it gives me error. Any suggestions, to fix this?
Thanks.

Use a parameterised query, and more usings, and stop with the generic exceptions.
something like this where somName and SomeLastName are the values that you wan t to query for.
String sql = "Select * From SomeTable Where [Name] = #Name and [Last_Name] = #LastName";
try
{
using(SqlConnection conn = new SqlConnection(connection))
{
conn.Open();
using( SqlCommand command = new SqlCommand(sql,conn))
{
command.Parameters.Add(new SqlParameter("Name", DbType.String,someName));
command.Parameters.Add(new SqlParameter("LastName", DbType.String,someLastName));
using(IDataReader myReader = command.ExecuteReader())
{
while (myReader.Read())
{
//do something
}
}
}
}
return 0; // Huh?
}
catch(SqlException sex)
{
Console.Writeline(String.Format("Error - {0}\r\n{1}",sex.Message, sex.StackTace))
}
NB not checked might be a silly in it

⚠️ WARNING This answer contains a SQL injection security vulnerability. Do not use it. Consider using a parameterized query instead, as described in some of the other answers to this question (e.g. Tony Hopkinson's answer).
Try adding quotes around the values in the where clause like this:
select * from table where NAME = 'name' and LAST_NAME = 'last_name'
In your case where you are using variables you need to add the quotes and then concatenate the values of the variables into the string. Or you could use String.Format like this:
var sql = String.Format("select * from table where [NAME] = '{0}' and LAST_NAME = '{1}'", name, last_name);
SqlCommand myCommand = new SqlCommand(sql);

Try
select * from table where NAME = 'name' and LAST_NAME = 'last_name'
instead of
select * from table where NAME = name and LAST_NAME = last_name
Edit:
If name and last_name are your parameters then try this:
SqlCommand myCommand = new SqlCommand("select * from table where NAME = #name and LAST_NAME = #last_name", conn);
myCommand.Parameters.AddWithValue( "#name", name );
myCommand.Parameters.AddWithValue( "#last_name", last_name );
Using parameterized commands means that you are invulnerable to a potential huge security hole - sql injection which is possible when command text is manually concatenated.

The text needs to be quoted as others have said--but that's not really the right answer here. Even without malice you're going to run into trouble with the Irish here, look what happens when you try to look for Mr. O'Neill. Use parameters instead.

Related

OleDb Update database.mdb

When i use the CustomButton for to save the "Full_Name" in the Database [Rooms] => Person then there is just nothing happen. Also if i use the try & catch function, there will be no Exception.
The field in the Database stays Empty.
When i show the required variable in the MessageBox (idPlus2, Full_Name) then it throws me back the right informations.
So i think the problem must be in the UPDATE Sql string but i don't know whats wrong.
private string connstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\....mdb";
//Path anonymous
string Full_Name;
[Obsolete]
private void customButton1_Click(object sender, EventArgs e)
{
conn = new OleDbConnection(connstr);
conn.Open();
strSQL = "SELECT * FROM [Guests] WHERE ID = ?";
cmd = new OleDbCommand(strSQL, conn);
da = new OleDbDataAdapter(cmd);
int id = CustomComboBox1.SelectedIndex;
int idPlus = id + 1;
cmd.Parameters.Add("?", idPlus);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Full_Name = reader["Vorname"].ToString() + ' ' + reader["Nachname"].ToString();
}
reader.Close();
string insertQuery = #"UPDATE [Rooms] SET Person = #Full_Name WHERE ID = ?";
cmd = new OleDbCommand(insertQuery, conn);
int id2 = customComboBox2.SelectedIndex;
int idPlus2 = id2 + 2;
cmd.Parameters.Add("?", idPlus2);
cmd.Parameters.Add(new OleDbParameter("#Full_Name", Full_Name));
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
conn.Close();
LoadTheme();
}
I have the answer
cmd.Parameters.Add("?", OleDbType.VarChar, 255).Value = CustomComboBox1.Texts;
cmd.Parameters.Add("?", idPlus2);
With OleDb you have to use ? for each variable or object which should be added to the database. That means that you can't specify the variable by name in the SQL string. You have to use the same order as the SQL string in C # code to insert the parameters.

Syntax Error when executing OLEDB Select statement

When I run this query I get the following error:
Syntax error(missing operator) in query expression '[Customer] = 'O'SMILE' and [Product] = 'Casserole(20kg)
Code:
// When print button is executed database operations
// Load data from database based upon select query
String codeQuery = "SELECT count(*) FROM [sheet1$] WHERE [Customer] = '" + lblcustomername.Text + "' and [Product]='" + lblproductname.Text + "'";
OleDbConnection Connection;
Connection = new OleDbConnection(OutputDatabaseConnectionString);
OleDbCommand Command = new OleDbCommand(codeQuery, Connection);
Command.Connection = Connection;
try
{
Connection.Open();
count = (Int32)Command.ExecuteScalar();
Connection.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
The error is because of the unquoted single quote "'" in the name O'SMILE and your use of string concatenation, rather than using a parameterised query. It also indicates that you are vulnerable to SQL injection attacks.
You must use Parameters!
string sql = "SELECT count(*) FROM [sheet1$] WHERE [Customer] = #customer and [Product] = #product";
using (SqlConnection connection = new SqlConnection(/* connection info */))
using (SqlCommand command = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("customer", SqlDbType.VarChar, 100).Value = lblcustomername.Text;
cmd.Parameters.Add("product", SqlDbType.VarChar, 120).Value = lblproductname.Text;
count = (Int32)command.ExecuteScalar();
}

SQL Invalid Column name detection from Query

I've tried running the code and I have no idea what's wrong with the query. Because it keeps saying invalid column name, when I'm trying to retrieve the data from that column instead. The column name matches the one in the DB. It's well connected because it's connected to a login form where it detects the other given password and name. I'm using based on a search textbox.
private void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDetailConnectionString"].ToString());
try
{
cnn.Open();
SqlCommand command = new SqlCommand();
command.Connection = cnn;
string query = "SELECT *FROM AffiliatedRegister WHERE Username=" + txtUser.Text + "";
command.CommandText = query;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
---[Converting String from db /Insert to textboxes]---
}
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
You need to wrap the username text in quotes.
Your emitted sql script is gonna look like:
SELECT *FROM AffiliatedRegister WHERE Username=InputUserName
So SQL is trying to compare the column Username to the column InputUsername.
Once you wrap the user name in quotes, it would be:
SELECT *FROM AffiliatedRegister WHERE Username='InputUserName'
Your statement erred because you did not wrap your string in quotes so Sql interpeted it as on object and not a string. That being said there you should use parameters and not string concatenation.
Use parameters
Wrap your SqlConnection in a using block
You should specify the column order in the SELECT statement, do not use *.
Do not swallow an Exception unless you know how to recover from it
Update code
private void btnSearch_Click(object sender, EventArgs e)
{
// use ConnectionString property
// wrap in using block
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDetailConnectionString"].ConnectionString))
{
try
{
SqlCommand command = new SqlCommand();
command.Connection = cnn;
// use parameters
// avoid *, specify columns instead
string query = "SELECT * FROM AffiliatedRegister WHERE Username= #userName";
command.CommandText = query;
// use parameters, I assumed the parameter type and length - it should be updated to the type and length specified in your table schema
command.Parameters.Add(new SqlParameter("#userName", SqlDbType.VarChar, 200) {Value = txtUser.Text });
// open as late as possible
cnn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// ---[Converting String from db / Insert to textboxes]-- -
}
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
// do not swallow the exception unless you know how to recover from it
throw;
}
}
}
Well first of all your query is very dangerous so please don't use it for production purpose.
Now what you need to do :-
In your query you need single quotes around the txtUser.Text.
Like this :-
"SELECT *FROM AffiliatedRegister WHERE Username='" + txtUser.Text
+ "'";
Resulting query : SELECT *FROM AffiliatedRegister WHERE Username = 'txtUser.Text';
You can also put double quotes like :-
...Username=\"" + txtUser.Text + "\"";
its complicated ;-) Earlier one is better for the reading purpose.
Why it did not run?
Because all values except integers must be passed inside single or double quotes in a query. Like :-
SELECT * FROM TABLE_NAME WHERE TABLE_NAME.COLUMN_NAME = "VALUE";
Now one very important thing please don't use these kinds of queries for production purpose. I guess you are in development phase so answering this question is not gonna ruin your life ...!!!
You can try to replace the your string: string query = "SELECT *FROM AffiliatedRegister WHERE Username=" + txtUser.Text + "";
to: string query = "SELECT <yourcolumn> FROM AffiliatedRegister WHERE Username=" + txtUser.Text + "";
I believe it is necessary to specify the column name.
Best regards

How to load data into text-box from sql database table

I have problem I can't able to load data into textboxes that the query fetch from database in windows form. The while loop cannot execute. how to solve this issue. or not have any error or exception. The inner commands cannot execute the debugger move to catch and finish.
private void btnCheck_Click(object sender, EventArgs e)
{
try
{
// query = "SELECT Id, Emplname, CNIC, City, MobileNo, Address, Salary, DailyWage, CompanyId, Status FROM Employees where id = '" + labCompyId.Text + "'";
query = "SELECT CNIC, City, MobileNo, Address, Salary, DailyWage, Status FROM Employees WHERE (EmployId = '"+txtEmployId+"') AND (Emplname = '"+txtEmplyName+"')";
SqlCommand command1 = DBConnectivity.getCommandForQuery(query, connection);
SqlDataReader reader1 = command1.ExecuteReader();
while(reader1.Read())
{
this.txtCNIC.Text = (reader1["CNIC"].ToString());
this.txtEmplyCity.Text = (reader1["City"].ToString());
this.txtEmplyAddress.Text = (reader1["Address"].ToString());
this.txtSalary.Text = (reader1["Salary"].ToString());
this.txtDailyWage.Text = (reader1["DailyWage"].ToString());
reader1.Close();
}
}
catch (Exception ex)
{
}
}
Oh what.Stop!!! Use Parameterized query to avoid SQL Injection
Mention you conncection string in connection
I hope the problem is you have missesd txtEmployId.Text value and txtEmplyName.Text value in your select query
SqlConnection connection= new SqlConnection(your Connection string);
string query = "SELECT CNIC, City, MobileNo, Address, Salary, DailyWage, Status
FROM Employees WHERE EmployId =#EmpID AND Emplname = #Emplname ";
SqlCommand command1 = new SqlCommand(query, connection);
connection.Open();
command1.Parameters.AddWithValue("#EmpID",txtEmployId.Text);
command1.Parameters.AddWithValue("#Emplname",txtEmplyName.Text);
SqlDataReader reader1 = command1.ExecuteReader();
while(reader1.Read())
{
this.txtCNIC.Text = (reader1["CNIC"].ToString());
this.txtEmplyCity.Text = (reader1["City"].ToString());
this.txtEmplyAddress.Text = (reader1["Address"].ToString());
this.txtSalary.Text = (reader1["Salary"].ToString());
this.txtDailyWage.Text = (reader1["DailyWage"].ToString());
reader1.Close();
}
Where is your connectionstring? If it is not in the page, include one.
Open the connection like Con.open()
Use parameterized query to avoid sql injection but that is just a suggestion.
The problem of the code is the connection string in my opinion.Open the connection inside the try block.

SQL Parameters in C# aren't working as expected

I think I'm making a fairly amateur mistake somewhere here, but I can't get SQL Parameters to reliably work in C#. Consider the following code:
protected string[] Query(string dataToFind, string tableName, string fieldToCheck, string fieldToReturn)
{
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
SqlDataReader dataReader = null;
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT " + fieldToReturn + " FROM " + tableName + " WHERE " + fieldToCheck " = '" + dataToFind "'";
try
{
connection.Open();
dataReader = command.ExecuteReader();
etc...
This executes as you would expect, returning the fieldToReturn from the table tableName. However, I understand that this is vulnerably to SQL injections, and that the correct way to avoid this is to use parameters. So I change my code to the following:
protected string[] Query(string dataToFind, string tableName, string fieldToCheck, string fieldToReturn)
{
SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
SqlParameter[] parameters = new SqlParameter[4];
parameters[0] = new SqlParameter("#dataToFind", dataToFind);
parameters[1] = new SqlParameter("#name", tableName);
parameters[2] = new SqlParameter("#fieldToCheck", fieldToCheck);
parameters[3] = new SqlParameter("#fieldToReturn", fieldToReturn);
SqlDataReader dataReader = null;
SqlCommand command = connection.CreateCommand();
command.Parameters.AddRange(parameters);
command.CommandText = "SELECT #fieldToReturn FROM #tableName WHERE #fieldToCheck = #dataToReturn";
try
{
connection.Open();
dataReader = command.ExecuteReader();
etc...
If I have 3 matches in my database, the first code example returns 3 matches. The second code returns 0 results?!
Am I being stupid and missing something obvious?
Your parameters are:
#dataToFind
#name
#fieldToCheck
#fieldToReturn
Your Query's CommandText has:
#fieldToReturn
#tableName
#fieldToCheck
#dataToReturn
These do not match. They must match in order to be properly applied.

Categories

Resources