SQL Query with single quotes retrieves no record - c#

I am currently fetching a dataset from following query select * from TableName WHERE ColumnName ='values''s' query executes without any error and return dataset was empty rows. When i execute the same in SQL Worksheets it return data
Following code for ref.
string sqlQuery = "select * from TableName WHERE Name ='McNaught''s'";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlQuery;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
adapter.Fill(ds);
conn.Close();

Please try this:
string sqlQuery = 'SELECT * FROM TableName WHERE Name ="McNaught\'s"'

The Problem is you need to provide Escape Sequence before the second ' so that compiler can distinguish between the previous apostrophe. Try this.
string sqlQuery = "select * from TableName WHERE Name ='McNaught'\'s'";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlQuery;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
adapter.Fill(ds);
conn.Close();

Try this it will work with \ escape sequence.
string sqlQuery = "select * from TableName WHERE Name ='McNaught\"s'";

Related

Condition to check a specific value from table asp.net c#?

string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string selstatus = "select status from Status where c_email=#c_email";
SqlCommand cmd = new SqlCommand(selstatus, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string value = Session["user"].ToString();
DataRow[] row =dt.Select(value);
sda.Fill(ds);
sda.Fill(dt);
if(row!=null){
Label13.Text = ds.Tables[0].Rows[0]["status"].ToString();
}else{
Label13.Text = "No response from mechanic";
}
cmd.ExecuteNonQuery();
con.Close();
I have been finding way to check a specific email id exist in the table. But I can't query what is the correct format to do so. I just need that if a specific email id is available then a message should be displayed.
There is no need for the DataAdapter, DataTable etc. Simply count the number of records
select count(1) from Status where c_email=#c_email
and then on the SqlCommand just use ExecuteScalar:
string selstatus = "select count(1) from Status where c_email=#c_email";
SqlCommand cmd = new SqlCommand(selstatus, con);
cmd.Parameters.AddWithValue("#c_email", Session["user"].ToString());
var count = cmd.ExecuteScalar();
// if count=0 the email doesnt exist

Dropdownbox.selectedvalue passing to sql comment

string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "Select * from table1 order by("+ddorder+" "+ddtype+")";
//there is an error beacuse of ddtype, what am I doing wrong?
SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1, DropDownList2.SelectedValue);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();
As far as I can see, you don't need to use ( and ) in order by clause. It's syntax doesn't have any usage for ( or ).
For example;
order by id desc
will work but
order by (id desc)
won't work.
By the way, use using statement to dispose your SqlConnection, SqlCommand and SqlDataAdapter automatically instead of calling Close method manually.
Also you don't need cmd.ExecuteNonQuery(); part for a SELECT statement. It is unnecessary since it's just execute your select query. It doesn't do or return something.
A few things more;
Change your table1 to something meaningful.
Don't use SELECT *. It's quite bad.
Use Dynamic Query:
Change Here:
string ddorder = DropDownList2.SelectedValue; // column
string ddtype = DropDownList3.SelectedValue; //asc or desc
String str1 = "exec(Select * from table1 order by "+ddorder+" "+ddtype+")";
and
SqlCommand cmd = new SqlCommand(str1, con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da1 = new SqlDataAdapter();
da1.SelectCommand = cmd;
DataSet ds1 = new DataSet();
da1.Fill(ds1);
GridView2.DataSource = ds1;
GridView2.DataBind();
con.Close();
Remove the parenthesis in the "order by" clause:
String str1 = "Select * from table1 order by "+ddorder+" "+ddtype;

error when merging three tables

i'm having an error " Object reference not set to an instance of an object. "
// Define the ADO.NET objects.
SqlConnection con = new SqlConnection(connectionString);
string selectSQL = "SELECT * FROM tbl_lecturer_project";
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet dsPubs = new DataSet();
// Try to open database and read information.
try
{
con.Open();
adapter.Fill(dsPubs, "tbl_lecturer_project");
// This command is still linked to the data adapter.
cmd.CommandText = "SELECT * FROM tbl_student_project_choice";
adapter.Fill(dsPubs, "tbl_student_project_choice");
cmd.CommandText = "SELECT * FROM tbl_team";
adapter.Fill(dsPubs, "tbl_team");
DataRelation SCoiceLec = new DataRelation("SCoiceLec", dsPubs.Tables["tbl_lecturer_project"].Columns["lecturerProjectId"], dsPubs.Tables["student_project_choice"].Columns["choiceProjectId"]);
DataRelation SChoiceNTeam = new DataRelation("SChoiceNTeam",dsPubs.Tables["student_project_choice"].Columns["choiceGroupId"], dsPubs.Tables["tbl_team"].Columns["teamId"]);
please help. i want to retrieve data from all 3 tables.
There are a number of problems with your code. Here is one:
adapter.Fill(dsPubs, "tbl_lecturer_project");
should be
adapter.Fill(dsPubs);
I think what you want is this:
string selectSQL = #"SELECT * FROM tbl_lecturer_project;
SELECT * FROM tbl_student_project_choice;
SELECT * FROM tbl_team";
using(SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using(SqlCommand cmd = new SqlCommand(selectSQL, con))
{
using(SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
DataSet dsPubs = new DataSet();
adapter.Fill(dsPubs);
// use dataset.
}
}
}
The three tables will have the names Table, Table1, and Table2

Can't retrieve a specific item from a dataset

I've looked through the other questions related to this, but I'm having a different issue. I can't get a specific item to return, it only returns my column name. How do I get the item to return?
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT #FieldName FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
I've also tried
return ds.Tables[0].Rows[0][0].ToString();
I'm just getting whatever is in the field variable.
If I pass in ("CompanyName", 33), it returns "CompanyName".
Your query (in sql profiler) is
SELECT 'CompanyName' FROM Сompanies WHERE СompanyNum = 33
So it returns exactly "CompanyName" string. You cannot pass column name as sqlparameter. You should do something like
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = string.Format("SELECT {0} FROM Companies WHERE CompanyNum = #CompanyNum", field);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
But this code can be used for SQL injection.
To avoid Sql injection, you could check that fieldName in field variable is one of the table columns.
Or You could get SELECT * FROM Сompanies WHERE СompanyNum = #CompanyNum and get value of named column from datatable:
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT * FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0][field].ToString();
}

How to Convert C# Variable DateTime Into SqlDbType.DateTime

How to convert a C# DateTime variable into Enum of SqlDataType.DateTime?
How to consume that enum into a connection string?
Is doing something like this correct?
string str = "SELECT * FROM TABLE WHERE CreateDt " + <that enum>;
SqlConnection Connection = new SqlConnection (<connection setting>);
Table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);
Thank you
Your best option is to use a parameterized command:
var cmd = new SqlCommand();
cmd.Connection = conn;
DateTime MyDate = DateTime.Now;
cmd.CommandText = #"SELECT * FROM TABLE WHERE CreateDt = #MyDate";
cmd.Parameters.AddWithValue("#MyDate", #MyDate);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.FillSchema(Table, SchemaType.Source);
adapter.Fill(Table);
This is not tested, but how about:
string str = "SELECT * FROM TABLE WHERE CreateDt = #createDate";
SqlConnection Connection = new SqlConnection (<connection setting>);
Table mytable = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(str, Connection);
adapter .SelectCommand.Parameters.Add("#createDate", SqlDbType.DateTime)
adapter .SelectCommand.Parameters("#createDate").Value = <Some DateTime>
adapter.FillSchema(mytable, SchemaType.Source);
adapter.Fill(Table);

Categories