使用ADO.NET查询和操作数据
一.使用StringBuilder类追加和删除字符串
1.创建StringBuilder类的对象
    StringBuilder sb=new StringBuilder("初始字符串值");
   2.Append()方法拼接字符串
    sb.Append("呵呵");
    结果为:初始字符串值呵呵
   3.使用Insert()方法在指定位置插入字符串
    sb.Insert(位置,字符串);
    sb.Insert(2,"化");
    结果为:初始化字符串值呵呵
   4.使用Remove()方法删除字符串
    sb.Remove(开始位置,删除长度)
    sb.Remove(7,2);
    结果为:初始化字符串值
二.DataRader对象读取数据
   1.HasRows属性:判断是否读取到数据,如果有数据则为true,反之为false
   2.Read()方法:前进到下一行读取的数据
   3.Close()方法:关闭DataReader对象
案例:
    StringBuilder sb = new StringBuilder();
//selectcount(*)fromStudent
sb.AppendLine("SELECT ");
sb.AppendLine(" [StudentNo] ");
sb.AppendLine(" ,[StudentName] ");
sb.AppendLine(" from ");
sb.AppendLine(" Student ");
SqlCommand com = new SqlCommand(sb.ToString(), con);
SqlDataReader dr=com.ExecuteReader();
//判断DataReader对象是否返回结果,如果有返回结果HasRows的值为true,则循环读取
if (dr.HasRows)
{
while (dr.Read())
{
Console.WriteLine("姓名:" + dr["StudentName"] + "\t学号:" + dr["StudentNo"]);
}
}
//关闭DataReader对象
dr.Close();
//selectcount(*)fromStudent
sb.AppendLine("SELECT ");
sb.AppendLine(" [StudentNo] ");
sb.AppendLine(" ,[StudentName] ");
sb.AppendLine(" from ");
sb.AppendLine(" Student ");
SqlCommand com = new SqlCommand(sb.ToString(), con);
SqlDataReader dr=com.ExecuteReader();
//判断DataReader对象是否返回结果,如果有返回结果HasRows的值为true,则循环读取
if (dr.HasRows)
{
while (dr.Read())
{
Console.WriteLine("姓名:" + dr["StudentName"] + "\t学号:" + dr["StudentNo"]);
}
}
//关闭DataReader对象
dr.Close();
        三.使用Command对象的ExcuteNonQuery()方法操作数据
   ExcuteNonQuery()主要用于对数据的增加修改以及删除
   案例:添加年级信息
      StringBuilder sb = new StringBuilder();
sb.AppendLine("insert into ");
sb.AppendLine(" Grade ");
sb.AppendLine(" ([GradeName]) ");
sb.AppendLine(" values ");
sb.AppendLine(" ('"+gradeName+"')");
SqlCommand com = new SqlCommand(sb.ToString(),con);
int count=com.ExecuteNonQuery();
sb.AppendLine("insert into ");
sb.AppendLine(" Grade ");
sb.AppendLine(" ([GradeName]) ");
sb.AppendLine(" values ");
sb.AppendLine(" ('"+gradeName+"')");
SqlCommand com = new SqlCommand(sb.ToString(),con);
int count=com.ExecuteNonQuery();
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号