DataSet、ExecuteScalar、ExecuteReader

using System;

using System.Data;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Data;

using System.Data.SqlClient;





namespace test

{

    public class Class1

    {

        public DataSet RunQuery(String QueryString)

        {



            String ConnectionString = "server=localhost;database=NorthWind;Integrated Security=SSPI";

            try

            {

                using (SqlConnection DBConnection = new SqlConnection(ConnectionString))

                {

            DBConnection.Open();

                    DataSet ResultsDataSet = new DataSet();

                    SqlDataAdapter DBAdapter = new SqlDataAdapter(QueryString, DBConnection);

                    DBAdapter.Fill(ResultsDataSet);



                }



            }

            catch (Exception ex)

            {

              ex.Message;               

            }



            return ResultsDataSet;



        }



    }

}









        string sql = "select  *  from users ";

        string stringconcetion = System.Configuration.ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;

        using (SqlConnection conn = new SqlConnection(stringconcetion))

        {

            conn.Open();

            SqlCommand cmd = new SqlCommand(sql,conn);

            string LastTime = cmd.ExecuteScalar().Tostring();

        }









String ConnectionString = "server=localhost;database=NorthWind;Integrated Security=SSPI";

string sql="select * from users";

using (SqlConnection cn = new SqlConnection(ConnectionString ))

{

SqlCommand command=new SqlCommand(sql,cn);

cn.Open()

//SqlDataReader 对象中保存查询的结果,不能new。相当于游标,先打开 再读取 最后关闭。

SqlDataReader reader=command.ExecuteReader(CommandBehavior.CloseConnection);  //CloseConnection 指定在关闭DataReader的时候,自动关闭数据库连接。

while (reader.Read())

{

//int id=(int)reader[0];  第二种写法

//int id=reader.GetInt(0); 第三种写法

int id=(int)reader["userid"];

}

reader.Close();

}

你可能感兴趣的:(execute)