2013年5月20日 星期一

ADO.NET連接DB抓取資料(C#)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data.SqlClient;

public partial class ADONET : System.Web.UI.Page
{

    String sqlCmmand = "select id,test_time,summary,author from test";
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = WebConfigurationManager.ConnectionStrings["testConnectionString2"].ConnectionString;

        //SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["testConnectionString2"].ConnectionString);
        SqlDataReader dr = null;
        SqlCommand cmd;
        cmd = new SqlCommand(sqlCmmand, conn);

        try
        {
            conn.Open();
            dr = cmd.ExecuteReader();


            while ((dr.Read()))
            {
                String test = "";
                test += dr.GetSqlString(2).ToString() + "
";
                Response.Write(test);
            }

            Response.Write("==============");

            //GridView1.DataSource = dr;
            //GridView1.DataBind();
         
            //String test = "";
            //while ((dr.Read()))
            //{
                //test = dr[0].ToString();
            //}
            //Response.Write(test);

            //Response.Write(dr[0].ToString());
            //int id = dr.GetOrdinal("id");
            //Response.Write(dr[2].ToString());

            //Response.Write(dr.GetSqlString[2] + "");
 
        }
        catch (Exception ex)
        {
            Response.Write("Error Message -->" + ex.ToString() + "
");
            throw;
        }
        finally
        {
            if (dr != null)
            {
                cmd.Cancel();
                dr.Close();
            }

            if (conn.State == System.Data.ConnectionState.Open)
            {
                conn.Close();
                conn.Dispose();
            }
        }

    }
}

沒有留言: