数据库连接

装数据库后,添加Northwind 库  course
 
 新建查询-打开:E:\一\c#练习\2012.3.30\Database-createdatabase 后,改变路径E:\一\c#练习\2012.3.30\Database,执行
-------------------------------------------------------------

IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = 'course')
 DROP DATABASE course;
GO


CREATE DATABASE course
  ON
  ( NAME = course_dat,
   FILENAME = N'E:\一\c#练习\2012.3.30\Database\北风贸易.mdf'),
  ( NAME = course_log,
   FILENAME = N'E:\一\c#练习\2012.3.30\Database\北风贸易_log.ldf')
  FOR ATTACH;
GO
CREATE DATABASE Northwind
  ON
  ( NAME = Northwind_dat,
   FILENAME = N'E:\一\c#练习\2012.3.30\Database\NORTHWND.mdf'),
  ( NAME = Northwind_log,
   FILENAME = N'E:\一\c#练习\2012.3.30\Database\NORTHWND.ldf')
  FOR ATTACH;
GO

------------------------------------------------------------

添加DateAccess.aspx.cs

 添加label  textBox: -ID textSearchCity  Button:Submit

     DropDownList  :-ID ddlCustomer    启用AutoPostBack

 添加GridView  id:gvwResult

              选择数据源

               自动套用格式

               配置数据源

               启用分页
               启用排序

               width  :100%         PageSize  :12
protected void Page_load(object sender,EventArgs e)
{
   //只有在网页第一次运行时执行
  if(!Page.IsPostBack)
  {
    //创建一个 SQL Server 数据库连接对象 //using System.Data.SqlClient;
    using (SqlConnection conn = new SqlConnection("Data Source=localhost;
    Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=111"))//复杂源代码中的字段
    {
    //创建一个命名对象
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText ="SELECT[CustomerID],[CompanyName],[City],[Country] FROM [Customers] ";

    //打开数据库连接
    conn.Open();

    //创建数据读取器
    SqlDataReader reader = cmd.ExecuteReader();

    //bool firstRow = true;
    bool firstrow = true;
      while (reader.Read())
     {
      ddlCustomer.Items.Add(new ListItem(reader[0].ToString()));
      if(firstRow)
       {
       //将选择的公司名称显示在文本框
       textCompany.Text = reader[1].ToString();
       textCity.Text = reader[2].ToString();
       textCountry.Text = reader[3].ToString();
       firstrow = false;
       }
      }   
    //关闭数据连接
    conn.Close();
    }
  }
}  

posted @ 2012-04-20 18:01  珍爱贝贝1314  阅读(147)  评论(0编辑  收藏  举报