c# asp.net check if column in database contains string - c#

In my database, the column is stored as 'Here is jurong', I want to read out the database row if the column contains the word jurong.
I tried using like but it cant work
Here is the code, please help
cmd = new SqlCommand("Select * from Thread WHERE (Delete_Status='No') AND (Thread_Location = '" + searchTB.Text + "' OR Thread_Title = '" + searchTB.Text + "' OR Thread_Description LIKE '%' + #Thread_Description + '%') ORDER BY ThreadID DESC ", con);
cmd.Parameters.Add("#Thread_Description", SqlDbType.VarChar).Value = searchTB.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
reptater.DataSource = ds;
reptater.DataBind();

Does that SQL statement return rows when you run it in the database? Also, I'd be careful of SQL injection attacks when passing values not through parameters.
Should your 'reptater' bind to a DataTable rather than a DataSet?
cmd = new SqlCommand("SELECT * FROM Thread WHERE (Delete_Status='No') AND (Thread_Location = #SearchTxt OR Thread_Title = #SearchTxt OR Thread_Description LIKE '%' + #SearchTxt + '%') ORDER BY ThreadID DESC ", con);
cmd.Parameters.Add("#SearchTxt", SqlDbType.VarChar);
cmd.Parameters["#SearchTxt"].Value = searchTB.Text;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
reptater.DataSource = ds; //ds.Tables[0]; ?
reptater.DataBind();

Related

how to convert dataAndTimePicker value to a string in c#

I need help, I am trying to write a query string that gets data according to a particular date picked in the dataAndTimePicker tool but I keep getting the same exception "Conversion failed when converting date and/or time from character string."
this is the code I tried
str = "select imId,imCustomer,imAmount,imDiscount,imTotal,imPaid,imPayType,imDate from invoiceMaster where imDate >= '" + startDate.Value.ToString("dd/MM/yyyy") + "' and imDate <= '" + endDate.Value.ToString("dd/MM/yyyy") + "'";
SqlDataAdapter da = new SqlDataAdapter(str, declerations.con);
DataTable dt = new DataTable();
da.Fill(dt);
dgvInvoice.DataSource = dt;
Always use parameters instead of putting a values directly into a sql string
str = "select imId,imCustomer,imAmount,imDiscount,imTotal,imPaid,imPayType,imDate from invoiceMaster where imDate >= #StartDate and imDate <= #EndDate";
SqlCommand cmd = new SqlCommand(str, declarations.con);
cmd.Parameters.AddWithValue("#StartDate", startDate.Value);
cmd.Parameters.AddWithValue("#EndDate", endDate.Value);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dgvInvoice.DataSource = dt;
str = "select imId,imCustomer,imAmount,imDiscount,imTotal,imPaid,imPayType,imDate from invoiceMaster where imDate >= '" + Convert.ToDateTime(startDate.Value) + "' and imDate <= '" + Convert.ToDateTime(endDate.Value) + "'";
SqlDataAdapter da = new SqlDataAdapter(str, declerations.con);
DataTable dt = new DataTable();
da.Fill(dt);
dgvInvoice.DataSource = dt;

how to query select data from table where first 3 character defined

i want to filter dropdownlist by first 3 charater on job code, this is my query
string result3 = Checked_By.ToString().Substring(0, 3);
SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama]
FROM [Job] WHERE LEFT(Kode, = '" + result3 + "') ORDER BY
Nama ASC", con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
sda.Fill(dt);
con.Close();
This is straightforward fix. First, fix SQL syntax error (SQL LEFT function takes 2 parameter, a string and a number. LEFT('abcdef', 3) returns abc), next rewrite using parameters. Something like this.
string result3 = Checked_By.ToString().Substring(0, 3);
SqlCommand cmd = new SqlCommand(" SELECT [Kode], [Nama] FROM [Job] WHERE LEFT(Kode, 3) = #result3 ORDER BY Nama", con); //ASC is OK but not required as it is default option
cmd.Parameters.Add("#result3", SqlDbType.Char, 3).Value = result3;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
//con.Open(); //not necessary. SqlDataAdapter.Fill opens connection if it needs
sda.Fill(dt);
//con.Close(); //and closed if it wasn't open before .Fill
"SELECT [Kode], [Nama]
FROM [Job] WHERE SUBSTR(Kode,1,3) = '" + result3 + "' ORDER BY
Nama ASC"

how to display date and time separately in grid view

I have one column in SQL table. which name is Intime. Its data type is nvarchar. It stores both date and time. But I want date and time separately.
I have tried this query:
select AttendanceDate,
SUBSTRING(convert(varchar,intime,113),1,11)[Intime],
SUBSTRING(convert(varchar,intime,113),13,19)[InTime],
InDeviceId,
OutTime,
OutTime,
OutDeviceId,
dbo.MinutesToDuration(duration) as Duration,
Status
from dbo.AttendanceLogs
where EmployeeId=2938
order by AttendanceDate desc
but if I pass same SQL command in grid view its not working.
public void Bind()
{
SqlCommand cmd = new SqlCommand("select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTime],SUBSTRING(convert(varchar,InTime,113),13,19) as [Intime],InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem + " and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter();
cmd.Connection = con;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
Where possibly could be the problem?
replace your code with this
public void Bind()
{
SqlCommand cmd = new SqlCommand(#"select AttendanceDate,SUBSTRING(convert(varchar,intime,113),1,11) as [InTimeD],SUBSTRING(convert(varchar,InTime,113),13,19) as [IntimeT],
InDeviceId,OutTime,OutTime,OutDeviceId, dbo.MinutesToDuration(duration) as Duration,Status from dbo.AttendanceLogs
where EmployeeId='" + empIdtxt.Text + "' and year(AttendanceDate)=" + ddlYear.SelectedItem.Value +
" and month(AttendanceDate)=" + ddlmnt.SelectedValue + " order by AttendanceDate desc", con);
SqlDataAdapter da = new SqlDataAdapter(cmd,con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.ControlStyle.Font.Size = 10;
}
this line not filter any year it return object of drop down list
year(AttendanceDate)=" + ddlYear.SelectedItem + "

accessing values of table in c# using values from other table

I have two tables named myfriends and imageslikes . In my code I am trying to access a column id2 of table myfriends and based on each value in that column I want to access records of imageslikes table. But with my code I am getting only value as output of repeater may be beacause its getting overwritten.
What could be the possible solution for accessing all the records i want to? can someone help?
Query = "select id2 from myfriends where id1 = '" + Session["id"] + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
dt = ds.Tables[0];
dr = dt.Rows[0];
foreach (DataRow row in dt.Rows)
{
string id2 = row["id2"].ToString();
Query = "select * from imageslikes where likedby = '" + id2 + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
DataList4.DataSource = ds;
DataList4.DataBind();
}
Query = "select * from imageslikes where likedby=(select id2 from myfriends where id1 = '" + Session["id"] + "') ";
Query = "select id2 from myfriends where id1 = '" + Session["id"] + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
dt = ds.Tables[0];
dr = dt.Rows[0];
foreach (DataRow row in dt.Rows)
{
string id2 = row["id2"].ToString();
Query = "select * from imageslikes where likedby = '" + id2 + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
DataList4.DataSource = ds;
DataList4.DataBind();
//Added this line
ds = new DataSet();
//if you need both records related to id1 and id2 then use
Query = "select * from imageslikes where likedby in ('" + id2 + "', '" + id1 + "')";
//Query = "select * from imageslikes where likedby = '" + id2 + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
Repeater3.DataSource = ds;
Repeater3.DataBind();
}

how to get particular record by using where condition in webservice?

I want to return a particular record from the webservice. Still what i have successfully done is, got all the records by the following code:
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
[WebMethod]
public DataSet Getmember()
{
con = new SqlConnection(#"Data Source=SQLDOTNET\MSSQLSERVER2008;Initial Catalog=doctor;Persist Security Info=True;User ID=sa;pwd=test123#;");
adap = new SqlDataAdapter("select * from tblusers", con);
ds = new DataSet();
adap.Fill(ds, "tblusers");
return ds;
}
Now i want to get a particular record by Emailid for that i have tried the following code:
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
[WebMethod]
public DataSet Getmember(String Emailid)
{
Emailid = "test#test.com";
con = new SqlConnection(#"Data Source=SQLDOTNET\MSSQLSERVER2008;Initial Catalog=doctor;Persist Security Info=True;User ID=sa;pwd=test123#;");
adap = new SqlDataAdapter("select * from tblusers where EmailAddress=" + Emailid, con);
ds = new DataSet();
adap.Fill(ds, "tblusers");
return ds;
}
But this code throwing the following error:
System.Data.SqlClient.SqlException: Invalid column name 'test#test.com'.
Please help me..
You need to enclose string literals in single quotes in SQL:
"select * from tblusers where EmailAddress = '" + Emailid + "'"
But this leaves you open to SQL injection attacks and is not recommended. (Examine what would happen if Emailid were set to "' OR 1=1 OR ''='".)
You should specify Emailid as a parameter value instead:
var cmd = new SqlCommand("select * from tblusers where EmailAddress = ?");
cmd.Parameters.Add(Emailid);
adap = new SqlDataAdapter(cmd, con);
change the
Emailid = "test#test.com";
to
Emailid = "'test#test.com'";
Note the extra single quotes arount emailid
Dont know if this would help cause I havent use C # for some time
I think your error goes on this part
select * from tblusers where EmailAddress=" + Emailid
Try changing it to
"select * from tblusers where EmailAddress='" + Emailid + "'"
At first you should use SQL parameters... not the plain SQL queries so better check SQL Parameters
adap = new SqlDataAdapter("select * from tblusers where EmailAddress=" + Emailid, con);
should be changed to
adap = new SqlDataAdapter("select * from tblusers where EmailAddress='" + Emailid + "'", con);
You miss to have "'" in you query .. Better you look at the statement syntax...

Categories