C # sql method of execution

When writing sqlCommand, in the end the use that to execute this command ??

Long time no write all their own throughout a program, include sqlCommand and how to bind to the gridview, it took a little time to check a bunch of pages, the record does not always feel up my brain capacity to forget about tomorrow.


There are three main Asp.net SQL execution methods, ExecuteNonQuery (), the ExecuteScalar (), the ExecuteReader ()

ExecuteNonQuery( ):

Mainly used to execute INSERT, UPDATE, DELETE, and others did not return worth SQL commands.

ExecuteScalar( ):

Returns the result set to: a first row and first column.

Often used to execute the SQL COUNT, AVG, MIN, MAX, and SUM functions.

PS: ExecuteScalar returns an Object type, you must set strong transition.

EX:

object objResult = objCMD.ExecuteScalar ()
is assumed to want to transition String 
String Result = cmd.ExecuteScalar () the ToString ().;

ExecuteReader( ):

Fast query the database and get results.

It returns DataReader object, if the call SqlCommand object, returns SqlDataReader.

Each call to SqlDataReader.Read Returns a row from the result.


Q&A:

Q1: What if my data is not only one line, the line is much better how to use  ExecuteReader () to read all of it ??

A1: Because ExecuteReader () it is returned in a row, so we have to let her action has been read repeatedly until no less than what so far

We pick up executeReader through SqlDataReader () object is returned, and through sqlDataReader .Read () it has been read

But afraid to read a blank line, so to add a special condition to determine sqlDataReader is not a blank line (DBnull.Value)

SqlConnection conn = openMSsqlConnection(); //连线
SqlCommand cmd = new SqlCommand(SQLString, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
   //防止为空白行
  if (!dr[0].Equals(DBNull.Value))
  {
     //do something               
  }
}
           

2018/05/25 update

I still do not really write remember how to write, write a detailed point. This should more clearly friends ~ ~

string SQLString = "SELECT USERSNAME,USERID FROM USERS WHERE USERID LIKE '06%'";

SqlConnection conn = openMSsqlConnection(); //连线
SqlCommand cmd = new SqlCommand(SQLString, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
   //防止为空白行
  if (!dr[0].Equals(DBNull.Value))
  {
                  
      string USERSNAME = dr["USERSNAME"].ToString();
      string USERID = dr["USERID"].ToString();
      //do something  
  }
}
        

Reference data

1.ASP.NET C # 3 Ge method to execute SQL instructions

Original: Large column  C # sql method of execution


Guess you like

Origin www.cnblogs.com/chinatrump/p/11490967.html