ADO.NET处理数据库的实现
一、功能分析
ADO.NET处理数据库的步骤:
1、连接到数据库
2、 连接到数据源
3、从数据源读取数据
4、对数据进行处理
二、两种实现方法
(1)使用Command对象和DataReader对象
static void Main(string[] args)
{
string strsql = "Server=(local);Database=sslxt;Integrated Security=True";
SqlConnection conn = new SqlConnection(strsql); //创建数据库连接对象
SqlCommand mycom = conn.CreateCommand();//创建Command对象
ADOCRUDBMycommond(conn, mycom);
}
private static void ADOCRUDBMycommond(SqlConnection conn, SqlCommand mycom)
{
try
{
conn.Open();
string sql = "select * from sc where Cno=@Cno";//查询
//"update sc set grade=85 Where Cno=@Cno"修改
//"insert into sc (Cno,Sno,grade) VALUES(301,10010202,98)"插入
//"delete from sc where Cno=@Cno"删除
mycom.CommandText = sql;
mycom.Parameters.Add("@Cno", SqlDbType.VarChar).Value = "201";//给命令添加参数即命令所需的条件
SqlDataReader myReader = mycom.ExecuteReader();
//用Command的函数执行语句,返回SqlDataReader对象myReader,myReader就是返回的结果集(也就是数据库中查询到的表数据)
while (myReader.Read())//判断是否有数据(插入数据不需要)
{
string Cno = myReader[0].ToString();
string Sno = myReader[1].ToString();
string grade = myReader[2].ToString();
Console.WriteLine("{0},{1},{2}", Cno, Sno, grade);
}
}
catch (Exception ex)//若出现错误,给出提示
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();//关闭数据库
Console.WriteLine("操作完成!");
Console.ReadLine();
}
}
(2)使用DataAdapter对象和DataSet对象
static void Main(string[] args)
{
string strsql = "Server=(local);Database=sslxt;Integrated Security=True";
DataSet myDataSet = new DataSet();
SqlConnection conn = new SqlConnection(strsql); //创建数据库连接对象
SqlCommand mycom = conn.CreateCommand();//创建Command对象
try
{
conn.Open();
string sql = "update sc set grade=94 Where Cno=@Cno";//修改 "select * from sc where Cno=@Cno";//查询
// "select * from sc where Cno=@Cno";//查询
//"insert into sc (Cno,Sno,grade) VALUES(101,10010223,88)"插入
//"delete from sc where Cno=@Cno"删除
mycom.CommandText = sql;
mycom.CommandType = CommandType.Text;
mycom.Connection = conn;
mycom.Parameters.Add("@Cno", SqlDbType.VarChar).Value = "201"; //给命令添加参数即命令所需的条件
SqlDataAdapter adapter = new SqlDataAdapter(mycom);
adapter.Fill(myDataSet, "sc");//填充数据到DataSet对象,读取数据
foreach (DataTable table in myDataSet.Tables)
{
foreach (DataRow row in table.Rows)
{
foreach (object field in row.ItemArray)
{
Console.Write(field);
Console.Write(" ");
}
//相应的行处理
}
//相应的表处理
}
}
catch (Exception ex)//若出现错误,给出提示
{
Console.WriteLine(ex.Message);
}
finally
{
conn.Close();//关闭数据库
// Console.WriteLine("操作完成!");
Console.ReadLine();
}
}