开发者

Reading and Updating Data Using SqlDataAdapter Question

I'm looking for some examples on how to best use SqlDataAdapter to access and update data in my application. Right now I have something like this:

SqlDataAdapter adapter;
DataSet myData = MyDataAccessClass.GetData("Select * from Students", ref adapter);
// change some data here and save changes
adapter.Update();

All of this occurs in code behind, and I dont really like it at all. So, I'm trying to find a way to do something like this:

DataSet myData = MyDataAccessClass.GetStudents();
// change some data and save changes
MyDataAccessClass.SaveStudents(myData);

Where SaveStudents method still uses SqlDataAdapter to update db.

Any ideas on how to make this wor开发者_JAVA技巧k or some pointers to best practices of doing something like this are highly appreciated. Thank you.


That seems like a fairly basic Data Access Layer implementation, to me. Generally, I do it something like this:

public class MyDataAccessClass
{
    private string ConnString;

    public MyDataAccessClass()
    { //Get connection string from configuration file }

    public MyDataAccessClass(string connString)
    { ConnString = connString; }

    public DataSet GetAllStudents()
    {
       //your SQL Adapter code here...
    }
}

One note that I'd make is that with so many ORM solutions (including just Entity Framework and Linq2Sql) available, you may want to consider using collections of objects instead of data-sets for your Data Representations. Then you can have a method like:

public void CreateUpdateStudent(Student student)
{
    //update database
}

That's fairly subjective, I'll admit, but I find it preferable to using straight DataSets.


If you want to get update data using the sql-data-adapter then you could use these

Using System.Data.SqlClient;

        SqlConnection con = new SqlConnection("Data Source=abcd-pc;Initial Catalog=user_info;Integrated Security=True");
        SqlDataAdapter da = new SqlDataAdapter();
        try
        {

            da.UpdateCommand = new SqlCommand("Update logindemo set password=@pswd where username=@uname",con);
            da.UpdateCommand.Parameters.Add("@pswd", SqlDbType.VarChar).Value = txtpass.Text;
            da.UpdateCommand.Parameters.Add("@uname", SqlDbType.VarChar).Value = txtusername.Text;
            con.Open();
            da.UpdateCommand.ExecuteNonQuery();
            Label1.Text = "Data Updated";
            con.Close();

        }
        catch
        {
            Label1.Text = "Unable To Connect";
        }

I hope you understand how to update the data easily. It just like the example. You can use these type of example in Inserting into the Data, and Deleting the Data with using specific the command and sql query as it required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜