asp.net入门笔记(四):ADO.NET简介

Ado.net学习

一。.net提供了两种数据提供者

1。sql server.net数据提供者

2。oledb.net数据提供者

二。数据提供者由四个对象组成

1。Connection

2。Command

3。DataReader

4。DataAdapter


三。Connection对象

Connection对象用于连接数据源,它代表数据源和数据用户之间的实际连接。

连接字符串包含连接数据存储所需要的信息,它有三部分组成

1。第一部分指定希望使用的Provider或Driver的种类

2。第二部分指定要使用的数据库

3。最后包含安全信息,如用户名和密码

对于Access

"provider=Microsoft.Jet.OLEDB.4.0;data source=MyDriver:\\MyPath\\Myfile.mdb"

在Microsoft sql server中,用于数据库的标准OLEDB字符串是:

"provider=SQLOLEDB.1;server=MyServerName;database=Mydatabase;Initial


catalog=MyCatalog;uid=UserID;pwd=userPwd"

sql提供者连接字符串的语法

"server=MyserverName;database=Mydatabase;uid=UserID;pwd=UserPwd"


 

Connection使用

1。new Connection

2。Open

3。Close

例子:

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

SqlConnection sqlCnn = new SqlConnection(strCnn);

sqlCnn.Open();

if (sqlCnn.State==ConnectionState.Open)

{

  sqlCnn.Close();

  sqlCnn.Dispose();

}

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

SqlConnection sqlCnn = new SqlConnection();

sqlCnn.ConnectionString = strCnn;

sqlCnn.Open();

if (sqlCnn.State==ConnectionState.Open)

{

  sqlCnn.Close();

  sqlCnn.Dispose();

}

具体例子

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

                     SqlConnection sqlCnn = new SqlConnection(strCnn);

                     try

                     {

                            sqlCnn.Open();

                            Label1.Text = "connection Open sucess";

                     }

                     catch (Exception ex)

                     {

                            Label1.Text = "connection open failed";

                            Label1.Text += ex.ToString();

                     }

                     finally

                     {

                            if (sqlCnn.State==ConnectionState.Open)

                            {

                                   sqlCnn.Close();

                                   sqlCnn.Dispose();

                            }

                     }


二。Command和DataReader

例1

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

                     string strCmd = "select * from UserInfo";

                     string strInfo = "";

                     SqlConnection sqlCnn = new SqlConnection(strCnn);

                     SqlCommand sqlCmd = new SqlCommand(strCmd,sqlCnn);

                     SqlDataReader sqlReader = null;

                     try

                     {

                            sqlCnn.Open();

                            sqlReader = sqlCmd.ExecuteReader();

                            while (sqlReader.Read())

                            {

                                   strInfo += sqlReader["NID"];

                                   strInfo += "&nbsp";

                                   strInfo += sqlReader["UserID"];

                                   strInfo += "&nbsp";

                                   strInfo += sqlReader["UserPwd"];

                                   strInfo += "&nbsp";

                                   strInfo += "<br/>";

                            }

                            DivResult.InnerHtml = strInfo;   //DivResult为Div控件

                            Label2.Text = "command演示成功";

                     }

                     catch (Exception ex)

                     {

                            Label2.Text = "command演示失败";

                            Label2.Text += ex.ToString();

                     }

                     finally

                     {

                            if (sqlCnn.State==ConnectionState.Open)

                            {

                                   sqlReader.Close();

                                   sqlCnn.Close();

                                   sqlCnn.Dispose();

                            }

                     }

              }

取得数据,最终把DataReader的数据在Div控件中显示

例2

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

                     SqlConnection sqlCnn = new SqlConnection(strCnn);

                     string strSql = "select * from UserInfo";

                     SqlCommand sqlCmd = new SqlCommand(strSql,sqlCnn);

                     SqlDataReader sqlReader = null;

                    

                     try

                     {

                            sqlCnn.Open();

                            sqlReader = sqlCmd.ExecuteReader();

                            DataGrid1.DataSource = sqlReader;

                            DataGrid1.DataBind();

                     }

                     catch (Exception ex)

                     {

                            Label1.Text = ex.ToString();

                     }

                     finally

                     {

                            if (sqlCnn.State==ConnectionState.Open)

                            {

                                   sqlCnn.Close();

                                   sqlCnn.Dispose();

                                   sqlReader.Close();

                            }

                     }

把查询到结果在DataGrid上显示

//---------------------------------

DataReader能够有效的提取显示数据库中的数据,效率比较高,当然,他也有他的限制

1。只能提供只读访问,不能修改数据

2。只能前向遍历数据

//Command和DataReader还需深入研究

关于Command执行方式

1.  ExecuteReader

返回一个DataReader对象

例:

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

string strSql = "select * from UserInfo";

SqlConnection sqlCnn = new SqlConnection(strCnn);

SqlCommand sqlCmd = new SqlCommand(strSql,sqlCnn);

SqlDataReader sqlReader = null;

try

{

sqlCnn.Open();

sqlReader = sqlCmd.ExecuteReader();

while (sqlReader.Read())

{

//表结构为 NID int,UserID,varchar,UserPwd,varchar,UserLevel,int

Response.Write(sqlReader["UserID"]+"</br> ");   //返回string类型

//Response.Write(sqlReader.GetString(1)+"</br> ");    //与上等价

//Response.Write(sqlReader.GetValue(1)+"</br> ");  //返回原始类型和格式   //与上等价

Response.Write(sqlReader["UserLevel"]+"</br>");     //返回string类型, UserLevel

Response.Write(sqlReader.GetInt32(3)+"</br>");    //得到int 型的UserLevel

Response.Write(sqlReader.GetValue(3)+"</br>");  //得到int 型的UserLevel

                       //由上知道,[""] 得到的是string,GetValue得到是原始类型

}

}

catch (SqlException ex)

         {

               Label2.Text = ex.Message.ToString();

          }

finally

      {

       sqlReader.Close();

      if (sqlCnn.State==ConnectionState.Open)

         {

           sqlCnn.Close();

           sqlCnn.Dispose();

         }

     }

2.  ExecuteScalar

   仅仅返回查询结果集中的第一行第一列,而忽略了其它的行和列,而且返回的是一个object类型,在使用之前必须先将它强制转换为所需类型

例:

表名为Test

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

string strSql = "select count(*) from UserInfo";

SqlConnection sqlCnn = new SqlConnection(strCnn);

SqlCommand sqlCmd = new SqlCommand(strSql,sqlCnn);

try

{

     int nCount = 0;

     sqlCnn.Open();

     nCount = (int)sqlCmd.ExecuteScalar();  //返回的是Object类型

     Label2.Text = "count: "+nCount.ToString();

}

catch (SqlException ex)

     {

          Label2.Text = ex.Message.ToString();

     }

finally

     {

       if (sqlCnn.State==ConnectionState.Open)

         {

          sqlCnn.Close();

          sqlCnn.Dispose();

         }

}

3.  ExecuteNonQuery

执行没有返回值的Sql语句。返回一个int类型的值,即在执行之后在数据库中所影响的行数。

例:

执行插入操作

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

string strSql = "Insert into UserInfo(UserID,UserPwd,UserLevel)values('insert','insertPwd',5)";

SqlConnection sqlCnn = new SqlConnection(strCnn);

SqlCommand sqlCmd = new SqlCommand(strSql,sqlCnn);

try

{

     sqlCnn.Open();

     sqlCmd.ExecuteNonQuery();

}

catch (SqlException ex)

{

Label2.Text = ex.Message.ToString();

}

finally

{

     if (sqlCnn.State==ConnectionState.Open)

      {

       sqlCnn.Close();

       sqlCnn.Dispose();

      }

}

4.  ExecuteXmlReader

用于XML操作,返回一个XmlReader对象

三。DataSet和DataTable对象

1。DataSet:包含多表,以及建立他们之间的关系

2。DataTable:表,有行和列

3。DataAdapter:用于将结果从Connection传递到DataSet

4。DataView:它表示放在DataSet中的DataTable的特定视图,存放的是用户希望从DataSet中获取的记录


和列。

例子:

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

                     string strSql = "select * from UserInfo";

                     SqlConnection sqlCnn = new SqlConnection(strCnn);

                     SqlDataAdapter sqlAdapter = new SqlDataAdapter(strSql,sqlCnn);

                     DataSet dbSet = new DataSet();

                     try

                     {

                            //不用Open connection

                            sqlAdapter.Fill(dbSet,"UserInfo");

                            DataView dbView = new DataView(dbSet.Tables["UserInfo"]);

                            DataGrid1.DataSource = dbView;

                            DataGrid1.DataBind();

                            Label4.Text = "success";

                     }

                     catch (SqlException ex)

                     {

                            Label4.Text = "failed   ";

                            Label4.Text += "msg:";

                            Label4.Text += ex.Message;

                     }

四.错误捕获

使用try。。。catch捕获错误

try

{
}

catch (Exception ex)

{

//ex.Message;
}

第十三章.操纵数据源

一.DataSet和DataTable

DataSet包含一个或多个DataTable

DataTable包含行和列

二.DataRow

行的改变添加和删除(这与数据源无关的)

1.  行添加

关键代码:

DataTable dbTable = dbSet.Tables["UserInfo"];

DataRow dbRow = dbTable.NewRow();

//该表本来是还有一个自动增加的UID,这里没赋值,结果是DataGid2中没显示,

//也就是说DataSet没该功能,与数据库没关系的

dbRow["UserID"] = "flypigluoluo";

dbRow["UserPwd"] = "luoluoluo";

dbTable.Rows.Add(dbRow);

全部代码:

string strCnn = "server=localhost;database=Test;uid=sa;pwd=sa";

string strSql = "select * from UserInfo";

SqlConnection sqlCnn = new SqlConnection(strCnn);

SqlDataAdapter sqlAdapter = new SqlDataAdapter(strSql,sqlCnn);

DataSet dbSet = new DataSet();

try

{

//不用Open connection

sqlAdapter.Fill(dbSet,"UserInfo");

         //DataView dbView = new DataView(dbSet.Tables["UserInfo"]);

         DataTable dbTable = dbSet.Tables["UserInfo"];

         DataRow dbRow = dbTable.NewRow();

         //该表本来是还有一个自动增加的UID,这里没赋值,结果是DataGid2中没显示,

         //也就是说DataSet没该功能,与数据库没关系的

         dbRow["UserID"] = "flypigluoluo";

        dbRow["UserPwd"] = "luoluoluo";

         dbTable.Rows.Add(dbRow);

         DataGrid2.DataSource = dbTable.DefaultView;

         DataGrid2.DataBind();

         Label4.Text = "success";

         }

             catch (SqlException ex)

             {

                Label4.Text = "failed   ";

                Label4.Text += "msg:";

                Label4.Text += ex.Message;

             }

2.   行编辑

关键代码:

DataTable dbTable = dbSet.Tables["UserInfo"];

DataRow[] dbRowArray = dbTable.Select("UserID='luo'");  //通过DataTable的select可以得到你要得//到的row

dbRowArray[0]["UserID"] = "ModifyLuo";

3.  行删除

关键代码:

DataTable dbTable = dbSet.Tables["UserInfo"];

dbTable.Rows[4].Delete();

//以上只是操作DataSet,和数据源无关的。

posted @ 2007-07-25 12:01  星空竹月  阅读(381)  评论(0编辑  收藏  举报