ADO.NET之数据库访问

.net连接数据库后台代码-------------返回数据集

方式一:

string conStr = "Data Source=地址(localhost);Initial Catalog=数据库名称;User ID=用户名;Password=密码;";
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = con.CreateCommand();
com.CommandText = "SQL语句";
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter sad = new SqlDataAdapter(com);
sad.Fill(ds);
DataTable dt = ds.Tables[0];
con.Close();

方式二:

SqlCommand com = new SqlCommand(sql, conn); 
SqlDataAdapter sda = new SqlDataAdapter(com);
sda.Fill(ds1);

方式三:SqlDataReader

SqlDataReader reder = com.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("mobile",typeof(string));
dt.Columns.Add("age", typeof(int));
while (reder.Read())
{
    DataRow dr = dt.NewRow();
    dr["name"] = reder["name"];
    dr["mobile"] = reder["mobile"];
    dr["age"] = reder["age"];
    dt.Rows.Add(dr);
 }
com.ExecuteNonQuery();返回受影响的行数,进行插入更新操作时使用

猜你喜欢

转载自blog.csdn.net/PLF_1994/article/details/80661760