asp.net連接數據庫


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();

       }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM