asp.net串連資料庫

來源:互聯網
上載者:User

標籤:

Asp.net web串連資料庫步驟。

一、      建立一個web工程。

      1.檔案->添加->建立網站->asp.net web網站Winform表單。

     2.建立好的網站最下面有個web.config檔案,在個檔案裡面找到資料庫連接字串,如下:

<connectionStrings>

      <add name="DefaultConnection" connectionString="

Data Source=PC-20160403SKQW\SQLEXPRESS;Initial Catalog=CAD;uid=sa;pwd=123456;Integrated Security=True" providerName="System.Data.SqlClient" />

</connectionStrings>

     3.其中Data Source是資料庫執行個體名稱,如果是網路資料庫則Data Source=ip,連接埠;例如Data Source= 192.1608.68.12,2000;

如果是本機使用者的話,Data Source=資料庫執行個體名稱;例如Data Source= PC-20160403SKQW\SQLEXPRESS;可以在登陸資料資料庫的時候看到執行個體名稱,如:

 

 

            4. Initial Catalog=資料庫名稱;uid=登陸賬戶;pwd=密碼;Integrated Security=True

 

 

二、      代碼實現讀取。

 

建立一個winform表單test.aspx,在test.aspx.cs裡面編寫代碼

using System.Configuration;

using System.Data.SqlClient;

protected void Page_Load(object sender, EventArgs e)

        {

            //1.擷取設定檔裡面配置的資料庫連接字串

            String connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();

            SqlConnection connection =new SqlConnection(connectionString);

            // Create the Command and Parameter objects.

           

                           //2.sql語句

            string queryString =

            "SELECT * from Solution";

           

          

            SqlCommand command = new SqlCommand(queryString, connection);

            // Open the connection in a try/catch block.

            // Create and execute the DataReader, writing the result

            // set to the console window.

          //3.開啟串連

                connection.Open();

           //4.執行sql語句

                SqlDataReader reader = command.ExecuteReader();

 

           //5.查看返回結果

                while (reader.Read())

                {

                    //Console.WriteLine("\t{0}\t{1}\t{2}",

                    //    reader[0], reader[1], reader[2]);

                    String a = reader[0].ToString();

                    Console.WriteLine(a);

                }

             //6.關閉串連

                reader.Close();

       }

asp.net串連資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.