Insert variable from parameter into Sql Command query - asp.net

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 !

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 + "'")

my asp.net web service code is giving error

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 .

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'";

Why does it throws error like this?

I do import the data from Excel sheet to Sql database..everything is fine,when i run this code,my access engine could not find mt sheet,it throws like this error..
my error is
The Microsoft Jet database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly.
but i already checked with my designation folder,its correct..then i don't know why it's repeated
my C# code below..
public partial class _Default : System.Web.UI.Page
{
string constr = #"Data Source=VIS1-B12\SQLEXPRESS;Initial Catalog=Sql_Excel;Integrated Security=True providerName=System.Data.SqlClient" ;
protected void btn_okClick(object sender, EventArgs e)
{
string path = Fup_Excel.PostedFile.FileName;
string exconstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+path+";Extended Properties=Excel 8.0";
OleDbConnection excelcon = new OleDbConnection(exconstr);
excelcon.Open();
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", excelcon);
OleDbDataReader dbreader;
OleDbDataAdapter dap = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
//dap.Fill(ds,"sheet1");
dbreader = cmd.ExecuteReader();
SqlBulkCopy bcpy = new SqlBulkCopy(constr);
bcpy.DestinationTableName = "Excel_Details";
bcpy.WriteToServer(dbreader);
//GridView1.DataSource = ds.Tables[0].DefaultView;
//GridView1.DataBind();
excelcon.Close();
}
}
It's better you should retrieve excel sheet name using code.
Code is shown below
OleDbConnection con = new OleDbConnection(ConnString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);

Resources