ASP.NET - read data  ASP.NET - read data

Asked By punya narayan
07-May-10 06:36 AM

 

protected void Button1_Click(object sender, EventArgs e)

 

{

 

string strcon = @"Data Source=RAJA;Initial Catalog=frame;User Id=;Password=;Trusted_Connection=True; ";

 

 

//string strcon = "Server=RAJA\SQLEXPRESS;Database=ram;Trusted_Connection=True;";

 

 

SqlCommand cmdinserted = new SqlCommand();

 

 

SqlConnection con = new SqlConnection(strcon);

 

 

cmdinserted.CommandText =

"select*from jms";

 

cmdinserted.CommandTimeout = 0;

cmdinserted.CommandType =

CommandType.Text;

 

cmdinserted.Connection = con;

 

try

 

{

con.Open();

cmdinserted.ExecuteNonQuery();

con.Close();

}

 

catch (Exception ex)

 

{

Label1.Text = ex.Message.ToString();

}



sir i want to read data from database so correct my code plz...
  Mash B replied to punya narayan
07-May-10 06:42 AM
use the below code

try

 

{

con.Open();

SqlDataReader reader =   cmdinserted.ExecuteReader();  // here is ur result set

con.Close();

}

  Sagar P replied to punya narayan
07-May-10 06:44 AM
There are few modification in your code;

string strcon = @"Data Source=RAJA;Initial Catalog=frame;User Id=;Password=;Trusted_Connection=True; "
//string strcon = "Server=RAJA\SQLEXPRESS;Database=ram;Trusted_Connection=True;"; 
SqlCommand cmdinserted = new SqlCommand(); 
SqlConnection con = new SqlConnection(strcon); 

cmdinserted.CommandText = "select * from jms"; //Keep space between select and *  
//cmdinserted.CommandTimeout = 0; //No need to specify timeout...........
cmdinserted.CommandType =
CommandType.Text; 
cmdinserted.Connection = con;
try 
{
    con.Open();
    //cmdinserted.ExecuteNonQuery(); //No need to ExecuteNonQuery...
    //Normally we use ExecuteNonQuery when you do the operations like Insert or Update.... For select you can either use;
    //DataAdpter, Dataset OR DataReader... like;
    SqlDataAdapter da = new SqlDataAdapter(cmdinserted);
    DataSet ds = new DataSet();
    da.Fill(ds); 
    //Here you can use DS then you display data like
    Label1.Text=ds.Tables[0].Rows[0][0].ToString();
    con.Close();
}
catch (Exception ex) 
{
    Label1.Text = ex.Message.ToString();
}

  punya narayan replied to Mash B
07-May-10 06:47 AM
sorry sir data not retrive in database plz correct my code...
  Phivos Stylianides replied to punya narayan
07-May-10 06:48 AM
First of all if you need to do a SELECT you need to use command.ExecuteReader(). You would use command.ExecuteNonQuery() when doing INSERT,UPDATE,DELETE statements. But i see you named your command instance cmdInserted, so what is it of the two? Also make sure you put spaces between select * from because otherwise it will cause a syntax error.
  Mash B replied to punya narayan
07-May-10 06:49 AM
For more info below are the sql methods descriptions

ExecuteNonQuery :  Used to execute a SQL statement against a Connection object.
As the name suggests, this method is used when the statement
returns no rows, such as an INSERT, DELETE or UPDATE query.

ExecuteReader : Executes the CommandText against the Connection and returns
a SQLDataReader. This method is used when the Command is
expected to return a set of data.

ExecuteScalar : Used to execute a query and return the first column of the
first row in the result set returned by the query. All other
column/
row information is discarded.
  punya narayan replied to Sagar P
07-May-10 06:58 AM
i am doing but not read data from database plz check this code..
  punya narayan replied to Mash B
07-May-10 07:05 AM
sir plz correct my code...
  Anoop S replied to punya narayan
07-May-10 07:05 AM
Actually what is your requirement? in the code you simply reading from the database only, not displaying it or not transfer data to any other parameter? can you explain your requirement?
  Anoop S replied to punya narayan
07-May-10 07:16 AM
SqlCommand cmdinserted = new SqlCommand(); -> if you are reading data from database use cmdselect
your command text = "select*from jms";
and you are using cmdinserted.ExecuteNonQuery(); for select statement, instead of that use  ExecuteReader()

ExecuteReader() - Executes a select query against a database and returns a DataReader object.
ExecuteScalar()   - Executes a select query against a database and return one single value.
ExecuteNonQuery() - It executes a query against a database, like update, delete and insert.
  punya narayan replied to Anoop S
07-May-10 07:16 AM
sir i want to retrive data from database and show the page......
  Anoop S replied to punya narayan
07-May-10 07:18 AM
SqlCommand cmdinserted = new SqlCommand(); -> if you are reading data from database use cmdselect
your command text = "select*from jms";
and you are using cmdinserted.ExecuteNonQuery(); for select statement, instead of that use  ExecuteReader()

ExecuteReader() - Executes a select query against a database and returns a DataReader object.
ExecuteScalar()   - Executes a select query against a database and return one single value.
ExecuteNonQuery() - It executes a query against a database, like update, delete and insert.
  Phivos Stylianides replied to punya narayan
07-May-10 07:38 AM
It seems like you don't wanna put any effort yourself so here is the all your method corrected:

protected void Button1_Click(object sender, EventArgs e)
{
string strcon = @"Data Source=RAJA;Initial Catalog=frame;Integrated Security=SSPI;";
SqlCommand cmdinserted = new SqlCommand();
SqlConnection con = new SqlConnection(strcon);
cmdinserted.CommandText = "select * from jms";
cmdinserted.CommandTimeout = 0;
cmdinserted.CommandType = CommandType.Text;
cmdinserted.Connection = con;

try

{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = cmdinserted;

con.Open();
cmdinserted.ExecuteReader();
con.Close();

DataTable table = new Datatable();
adapter.Fill(table);

gridView1.DataSource = table;
gridView1.DataBind();
}

catch (Exception ex)
{
Label1.Text = ex.Message.ToString();
}
  punya narayan replied to Anoop S
07-May-10 07:39 AM
sir i want to do show data from database on the page so i make one button and one label and i written code on button and i want to see data on page..
  Anoop S replied to punya narayan
07-May-10 07:51 AM
ok then its better to use FormView control to display the data, refer this examples

http://www.asp.net/data-access/tutorials/using-the-formview-s-templates-cs
http://www.vbdotnetheaven.com/UploadFile/manishkdwivedi/displayinformview04172007043545AM/displayinformview.aspx
  Web Star replied to punya narayan
07-May-10 08:36 AM
first of all i think u did not study of basics.
if u want get data from database and show on label control than use executereader instead of executenonquery.
so change your code as follows

protected void Button1_Click(object sender, EventArgs e)

 {

 string strcon = @"Data Source=RAJA;Initial Catalog=frame;User Id=;Password=;Trusted_Connection=True; ";

 SqlCommand cmdinserted = new SqlCommand();

 SqlConnection con = new SqlConnection(strcon);

 cmdinserted.CommandText = "select*from jms";

 cmdinserted.CommandTimeout = 0;

cmdinserted.CommandType = CommandType.Text;

 cmdinserted.Connection = con;

 try

 {

con.Open();

SqlDataReader dr = cmdinserted.ExecuteReader();

//here u get data fon datareader and u need to show data on label control as follows

if(dr.Read())
 {
    lblName.Text = dr["columnname"].ToString();
// this will show vlaue of that columnname u specify here and make sure that columname must be selected in your query than u will be see value on that label control
}

con.Close();

}

 

catch (Exception ex)

 

{

Label1.Text = ex.Message.ToString();

}

Create New Account
help
partial class EditGroupCompInfo : System.Web.UI.Page { clsExecute cls = new clsExecute(); clsConnection clsDb = new clsConnection(); SqlCommand cmd = new SqlCommand(); SqlConnection con; SqlDataReader dr; SqlDataAdapter da = new SqlDataAdapter(); DataSet ds = new DataSet(); string strQry; object intCode, intCustCode, intMaxCode, objLogoName; string strRdo, strRdo1; string private void logoUpload() { / / / / string path; / / / / / / object max = cls.getMaxCode("mstCompany", "cmpCode"); / / / / / / clsConnection clsDb = new clsConnection(); / / / / / / SqlConnection con; / / / / / / SqlCommand cmd = new SqlCommand(); / / / / if (strName ! = "") / / / / { / / / / path = fuLogo.PostedFile.FileName; / / / / } / / / / else / / / / { / / / / path = ""; / / / / } / / / / resize(path, intCode); / / / / fileExtention
true" ShowDeleteButton = "true" / > < / Columns> < / asp:GridView> .cs code- Function to bind Grid private void getdata() { SqlConnection con = new SqlConnection("Data Source = 10.0.2.8;Initial Catalog = JitendraDB;User ID = sa;password = change_123"); SqlDataAdapter da; string mySQL = "SELECT empid, empname, dept FROM emp "; da = new SqlDataAdapter(mySQL, con); con.Open(); DataSet ds = new DataSet(); da.Fill(ds); GridView2.DataSource = ds; GridView2 RowIndex].Cells[1].Text; / / FOR GETTING ENPID string deleteQuery = "delete from emp where empid = ' " + strEmpId + " ' "; SqlConnection cn = new SqlConnection("CONNECTION STRING"); cn.Open(); SqlCommand cmd = new SqlCommand(deleteQuery, cn); cmd.ExecuteNonQuery(); cn.Close(); GridView1.EditIndex = -1; Response.Write("<script> alert('Record Deleted
GridViewRow ; Label lid = ( Label )row.FindControl( "lblid" ); int id = Convert .ToInt16(lid.Text); cmd = new SqlCommand ( "select *from tbl_hoteldetails where id = '" + id + "'" , con); dr = cmd.ExecuteReader(); dr.Read(); if (dr.HasRows e) in d: \ maddy \ editupdate \ Default.aspx.cs:line 199 this is error cmd = new SqlCommand ( "select *from tbl_hoteldetails where id = '" + id + "'" , con); dr = cmd.ExecuteReader(); dr.Read(); if (dr.HasRows GridViewRow ; Label lid = ( Label )row.FindControl( "lblid" ); int id = Convert .ToInt16(lid.Text); cmd = new SqlCommand ( "select *from tbl_hoteldetails where id = '" + id + "'" , con); dr = cmd.ExecuteReader(); dr.Read(); if (dr.HasRows) { DropDownList1.SelectedIndex = Convert .ToInt16(dr[1].ToString()); txthotelname.Text = dr[3].ToString(); / / adap = new SqlDataAdapter("select *from tbl_city where stateid = '" + DropDownList1.SelectedItem.Value + "'", con1); / / ds = new DataSet(); / / adap.Fill(ds Count) DropDownList2.SelectedIndex = Convert .ToInt16(dr[2].ToString()); ); this coding is not executing: cmd = new SqlCommand ( "select *from tbl_hoteldetails where id = '" + id + "'" , con); dr = cmd.ExecuteReader(); dr.Read(); if (dr.HasRows should return any integer value. . . i am not getting this value correctly here ? cmd = new SqlCommand ( "select *from tbl_hoteldetails where id = '" +id+ "'" , con); dr = cmd.ExecuteReader(); dr.Read(); if (dr.HasRows) { DropDownList1.SelectedIndex = Convert .ToInt16(dr[1].ToString()); txthotelname.Text = dr[3].ToString(); adap = new SqlDataAdapter ( "select *from tbl_city where stateid = '" + DropDownList1.SelectedItem.Value + "'" , con1); ds = new DataSet (); adap.Fill(ds using System.Data.SqlClient; using System.IO; public partial class _Default : System.Web.UI. Page { SqlConnection con = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "newhotel" ].ConnectionString); SqlConnection con1 = new SqlConnection ( ConfigurationManager .ConnectionStrings[ "newhotel" ].ConnectionString
SqlHelper()" private SqlHelper() {} / / / <summary> / / / This method is used to attach array of SqlParameters to a SqlCommand. / / / / / / This method will assign a value of DbNull to any parameter with a direction of commandParameters"> An array of SqlParameters to be added to command< / param> private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters) { if( command = = null ) throw new ArgumentNullException( "command" ); if( commandParameters ! = null ) { foreach (SqlParameter connection, transaction, command type and parameters / / / to the provided command / / / < / summary> / / / <param name = "command"> The SqlCommand to be prepared< / param> / / / <param name = "connection"> A valid SqlConnection, on which to execute this command< / param> / / / <param name = "transaction"> A valid SqlTransaction, or 'null the connection was opened by the method, otherwose is false.< / param> private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection ) { if( command = = null are provided if (commandParameters ! = null) { AttachParameters(command, commandParameters); } return; } #endregion private utility methods & constructors #region ExecuteNonQuery / / / <summary> / / / Execute a SqlCommand (that returns no resultset and takes no parameters) against the database specified in / / / the connection
Sqlcommand Hi All I am new to .Net. Some one tell me how to use SqlCommand to insert, update, delete, select with neat example. Thanks In Advance. A SqlCommand object allows you to specify what type of interaction you want to perform with a select, insert, modify, and delete commands on rows of data in a database table. The SqlCommand object can be used to support disconnected data management scenarios, but in this lesson we will only use the SqlCommand object alone. A later lesson on the SqlDataAdapter will explain how to implement an application that uses disconnected data. This lesson will also value from a database, such as the number of records in a table. Creating a SqlCommand Object Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration, as follows: SqlCommand cmd = new SqlCommand("select CategoryName from