none
Syntax for ExecuteNonQuery RRS feed

  • Question

  •  

    Can someone please help me out with the syntax of ExecuteNonQuery?

    when we write cmd.ExecuteNonQuery() where does the result get stored coz I have to display the result returned. Or should I directly write cmd.ExecuteNonQuery()? I know this is a basic question but I am new to c#.

    Monday, December 8, 2008 6:22 AM

All replies

  • You should use ExecuteNonQuery method for all actions SQL statements that do not return any result back. For example you can execute INSERT, DELETE or UPDATE SQL statements because they do not return any records, but modify database. ExecuteNonQuery will return only number of affected rows by executed query and you can get it as return result of function, like

     

     

    int affectedRows = cmdExecuteNonQuery();

     

    If you need to query something, then you need to use SqlDataAdapter (assuming you are working with SQL Server). It allows loading data from database to DataSet or DataTable.

     

    Monday, December 8, 2008 11:07 AM
    Moderator
  • Please also look at msdn web site to get comprehensive info in System.Data.SqlClient namespace in order design your code to fulfill the desired purpose:

    http://msdn.microsoft.com/en-us/library/system.data.sqlclient.aspx

    There're numbers of options you can adopt, such as (not in comprehensive list):

     

    SqlCommand class

    • SqlCommand.ExecuteNonQuery to get numbers of rows affected 
    • SqlCommand.ExecuteReader to build a SqlDataReader.
    • SqlCommand.ExecuteScalar to get the first column of the first row in the result set returned by the query.

    SqlDataAdapter class

    • SqlDataAdapter.Fill method to add or refresh rows in the DataSet.
    • SqlDataAdapter.FillSchema(DataSet, SchemaType) to add a DataTable named "Table" to the specified DataSet and configures the schema to match that in the data source based on the specified SchemaType.
    • SqlDataAdapter.FillSchema(DataTable, SchemaType) to Configures the schema of the specified DataTable based on the specified SchemaType.

    Hopefully it helps...

    Tuesday, December 9, 2008 12:02 AM
    Answerer