ADO.NET入门学习备忘

 


//连接字符串_直接写
string conStr = "Data Source=computer;Initial Catalog=AdoTest;Integrated Security=True; Persist Security Info=True;";

//连接字符串_写在Web.Config里
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["constring"].ToString();
//Web.Config里设置
<connectionStrings>
    
<add name="constring" connectionString="Data Source=visingcomputer;Initial Catalog=AdoTest;Integrated Security=True; Persist Security Info=True;"/>
  
</connectionStrings>

//连接数据库
        string conStr =System.Configuration.ConfigurationManager.ConnectionStrings[1].ToString();
        SqlConnection sqlCon 
= new SqlConnection(conStr);
        sqlCon.Open();
        
this.Label1.Text = sqlCon.State.ToString();

        
//插入数据
        string sqlIntoCmd="insert into info values('123','地理学','g')";
        SqlCommand sqlInto 
= new SqlCommand(sqlIntoCmd, sqlCon); 
        sqlInto.ExecuteNonQuery();  
//这句执行后,数据才真正插入数据库中.

        
////使用SqlDataReader显示数据
        //string sqlSelectCmd = "select * from info";
        
//SqlCommand sqlSelect = new SqlCommand(sqlSelectCmd, sqlCon);
        
//SqlDataReader sqlDr=sqlSelect.ExecuteReader();
        
//while (sqlDr.Read())
        
//{
        
//    Response.Write(sqlDr[0]);
        
//    Response.Write(sqlDr[1]);
        
//    Response.Write(sqlDr[2]);
        
//    Response.Write("<br />");
        
//}
        
//sqlDr.Close();


        
//使用SqlDataAdapter,DataSet显示数据
        string sqlSelectCmd = "select * from info";
        SqlDataAdapter da 
= new SqlDataAdapter(sqlSelectCmd, sqlCon);        
        DataSet ds 
= new DataSet();
        da.Fill(ds, 
"info");
        
if (ds.Tables[0].Rows.Count == 0)
        
{
            Response.Write(
"NOdata");
        }

        
else
        
{
            
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            
{
                Response.Write(ds.Tables[
0].Rows[i][0]);
                Response.Write(ds.Tables[
0].Rows[i][1]);
                Response.Write(ds.Tables[
0].Rows[i][2]);
                Response.Write(
"<br />");
            }
            
        }

       

        
////使用SqlDataAdapter,SqlCommandBuilder,DataSet插入数据
        //string sqlSelectCmd = "select * from info";        
        
//SqlDataAdapter da = new SqlDataAdapter(sqlSelectCmd, sqlCon);
        
//SqlCommandBuilder cb = new SqlCommandBuilder(da);
        
//DataSet ds = new DataSet();
        
//da.Fill(ds, "info");
        
//DataRow newrow = ds.Tables[0].NewRow();
        
//newrow[0] = "text";
        
//newrow[1] = "text";
        
//newrow[2] = "text";
        
//ds.Tables[0].Rows.Add(newrow);
        
//da.Update(ds, "info");

        sqlCon.Close();
posted @ 2008-09-11 14:36  紫微星  阅读(696)  评论(4编辑  收藏  举报