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

       }

posted @ 2016-04-24 12:25  gongpipi  阅读(5329)  评论(0编辑  收藏  举报