my asp.net web service code is giving error - asp.net

hello i have created the code for extracting age from table test
but instead of returning the age it is returning me the following statement
System.Data.SqlClient.SqlDataReader
here is the code
[WebMethod]
public string Getcustomername(string name)
{
SqlConnection con = new SqlConnection("Data Source=GURJOT;Initial Catalog=TEST;Integrated Security=True");
SqlCommand com = new SqlCommand();
com.Connection = con;
con.Open();
com.CommandText = "SELECT * from test WHERE Name='" + name + "'";
SqlDataReader dt = com.ExecuteReader();
dt.Read();
con.Close();
dt.Close();
return dt.ToString();
any help would be appreciated
Thanks

Instead of returning dt.ToString() you should return the value of a field:
public string GetCustomerAge(string name)
{
using (SqlConnection con = new SqlConnection("Data Source=GURJOT;Initial Catalog=TEST;Integrated Security=True"))
{
using(SqlCommand com = new SqlCommand())
{
com.Connection = con;
con.Open();
com.CommandText = "SELECT age from test WHERE Name='" + name + "'";
using (SqlDataReader dt = com.ExecuteReader())
{
if (dt.Read())
{
return System.Convert.ToString(dt.GetValue(0));
}
}
}
return "";
}
And please, use parameterized queries - http://en.wikipedia.org/wiki/SQL_injection .

Related

asp.net mvc using string id on details view

Please help me to find error on my code
public ActionResult Details(string id)
{
String connectionString = ConfigurationManager.ConnectionStrings["SAPB1"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
String sql = "Select a.[CardCode] As CCODE,a.[CardName] As Name from ocrd a where a.CardCode = " + id;
SqlCommand cmd = new SqlCommand(sql, conn);
BPModel BP = new BPModel();
using (conn)
{
conn.Open();
if (string.IsNullOrEmpty(id))
{
}
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
BP.CCODE = rdr["CCODE"].ToString();
BP.Name = rdr["Name"].ToString();
}
}
return View(BP);
}
You need to wrap your id values inside single quote ('). Try like below.
String sql = "Select a.[CardCode] As CCODE,a.[CardName] As Name from ocrd a where a.CardCode = '" + id + "'";

How do i fill up textbox from database in asp.net visual studio without id?

I am trying to get details of an account in a row using the Username instead of id. I have limited knowledge on this matter so im only stuck with the code that i learned in class.
I have tried changing variables, but probably wont help and the code i have provided below, would not retrieve any data from the database...
(Username are retrieved from previous page and yes it did show up in this page)
This is the code used on previous page: (code is placed on a button)
string username = Session["Username"].ToString();
Response.Redirect("EditAccountDetail.aspx?Username="+ username);
private DataTable GetData()
{
string constr = ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
This is the code im working on right now:
String Uname = Request.QueryString["Username"];
string constr = ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname+"'"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string id = row["Id"].ToString();
string Full_name = row["Full_name"].ToString();
string Username = row["Username"].ToString();
string Password = row["Password"].ToString();
string Email = row["Email"].ToString();
string DOB = row["DOB"].ToString();
string Gender = row["Gender"].ToString();
this.HiddenField1.Value = id;
this.TextBox_Name.Text = Full_name;
this.TextBox_Username.Text = Username;
this.TextBox_Password.Text = Password;
this.TextBox_Email.Text = Email;
this.TextBox_DOB.Text = DOB;
this.RadioButtonList_Gender.Text = Gender;
}
}
}
}
}
This is the code in the button:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
try
{
string query = "UPDATE Guest SET Full_name=#Full_name, Username=#Username, Password=#Password, Email=#Email, DOB=#DOB, Gender=#Gender WHERE Id=#id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#id", HiddenField1.Value);
cmd.Parameters.AddWithValue("#Full_name", TextBox_Name.Text);
cmd.Parameters.AddWithValue("#Username", TextBox_Username.Text);
cmd.Parameters.AddWithValue("#Password", TextBox_Password.Text);
cmd.Parameters.AddWithValue("#Email", TextBox_Email.Text);
cmd.Parameters.AddWithValue("#DOB", TextBox_DOB.Text);
cmd.Parameters.AddWithValue("#Gender", RadioButtonList_Gender.Text);
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("GuestMenu.aspx");
con.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.ToString());
}
If you are redirecting to the "GuestMenu" page, then you have to add username in the query string so that you can retrieve this on the page.
Response.Redirect("GuestMenu.aspx?Username="+TextBox_Username.Text);
By seeing your current code, you should be getting some error. Please post the error details if any.
You can try changing the query as below and check for database result
new SqlCommand("SELECT * FROM Guest WHERE Username='" + Uname + "'")

Insert variable from parameter into Sql Command query

This is my code in class file:
public class terminarzLiga
{
public static List<terminarz> wyswietlTerminarz(string liga)
{
List<terminarz> wyswietlTerminarz = new List<terminarz>();
string CS = ConfigurationManager.ConnectionStrings["ligiConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand com = new SqlCommand("Select * from TerminarzLaLiga", con);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
while (rdr.Read())
[.... rest of code .....]
My intention is use variable in Sql Command query, like this:
Code behind:
private void ZaladujGridView()
{
GridView2.DataSource = EuroPilka.terminarzLiga.wyswietlTerminarz("TerminarzLaLiga");
GridView2.DataBind();
}
Class file code:
public class terminarzLiga
{
public static List<terminarz> wyswietlTerminarz(string liga)
{
List<terminarz> wyswietlTerminarz = new List<terminarz>();
string CS = ConfigurationManager.ConnectionStrings["ligiConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand com = new SqlCommand("Select * from '" + liga +"'", con);
con.Open();
SqlDataReader rdr = com.ExecuteReader();
while (rdr.Read())
[.... rest of code .....]
but i'am receiving error while reader is executing
SqlDataReader rdr = com.ExecuteReader();
Many thanks for any advise !

Data list where clause

i am using a datalist to display videos but i am trying to get it working now with the where clasue ...where the name is equal to wrd.mp4 i am getting the following error,
$exception {"The multi-part identifier \"wrd.mp4\" could not be bound."} System.Exception {System.Data.SqlClient.SqlException}
private void BindGrid()
{
string strConnString = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, Name from tblFiles where Name=wrd.mp4";
cmd.Connection = con;
con.Open();
DataList1.DataSource = cmd.ExecuteReader();
DataList1.DataBind();
con.Close();
}
}
}
}
You need to use quotes:
cmd.CommandText = "select Id, Name from tblFiles where Name='wrd.mp4'";

can't retrieve the wanted data out from database

I have created an ASP.NET application in Visual Studio 2010. I am having trouble in retrieving the data i wanted from the two dates i selected from the date picker. once i select the 2 dates, it just keep displaying all the data out and not the dates that i have selected.
This is my code:
protected void Page_Load(object sender, EventArgs e)
{
string startdate = (string)Session["startdate"];
string enddate = (string)Session["enddate"];
DateTime one = Convert.ToDateTime(startdate);
DateTime two = Convert.ToDateTime(enddate);
if (DateTime.Compare(two, one)>=0)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True");
conn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN '" + startdate + "' AND '" + enddate + "')", conn);
SqlDataAdapter da = new SqlDataAdapter(sqlcmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.Visible = true;
GridView1.DataBind();
conn.Close();
}
else
{
GridView1.Visible = false;
string strMsg = " Data not found for the choosen dates.";
Response.Write("<script>alert('" + strMsg + "')</script>");
}
}
My initial observation is that there is a ) in your SQL with no matching ( - I wonder if your command is simply throwing an exception...?
The first thing I would try is parameterizing it; in addition to being a really really good idea anyway, it could avoid formatting (dd/MM vs MM/dd) issues in the dates:
if(two >= one)
{
DataSet ds = new DataSet();
using(var conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True"))
using(var sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN #start AND #end", conn))
using(var da = new SqlDataAdapter(sqlcmd))
{
sqlcmd.Parameters.AddWithValue("start", one);
sqlcmd.Parameters.AddWithValue("end", two);
conn.Open();
da.Fill(ds);
}
}
using(SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=ncpsdbb;Integrated Security=True"))
{
conn.Open();
SqlCommand sqlcmd = new SqlCommand("SELECT * FROM StudentTransactions WHERE TimeDate BETWEEN #startDate AND #endDate", conn);
sqlcmd.Parameters.AddWithValue("startDate" <Your start date>);
sqlcmd.Parameters.AddWithValue("endDate" <Your end date>);
...
Also notice the error with parantheses in your command string.

Resources