如果您想让 DataGirdView 中的行反映在数据库中,您只需使用 DataAdapter 对象的方法即可。
简单地说,DataAdapter 和DataReader 对象为您提供了一种简单而有效的方式来读取和写入数据库。除此之外,他们还会在不影响实际数据库表的情况下执行所有这些操作,这意味着在您说之前,一切都不会受到影响。
对于这个例子,假设我们有一个名为 contacts 的 SQL 表,其中包含三列,即 fname、mname 和 lname em>。
首先,我们需要一个函数来从“联系人”表中获取数据。
protected DataSet GetData()
{
// our select query to obtain all the rows from the contacts table
string selectQuery = "SELECT * FROM contacts";
// Where the data from the underlying table will be stored
DataSet ds = new DataSet();
// Connect to the database and get the data from the "contacts" table
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlDataAdapter da = new SqlDataAdapter(selectQuery, conn))
{
da.Fill(ds, "contacts"); // Add the rows from the "contacts" table to our dataset
}
}
return ds;
}
然后,您可以通过执行将 DGV 绑定到存储在返回的数据集对象中的表
DGV_Items.DataSource = GetData();
在您的 form_load 事件中。
现在我们已经完成了从数据库中获取数据的方法的设置,我们现在设置了一个方法来操作我们现在拥有的所有数据。
protected void UpdateTable(DataSet ds)
{
SqlConnection conn = new SqlConnection(connString);
// Insert, update and delete queries
string updateQuery = "UPDATE contacts SET fname=@first,mname=@middle,lname=@last WHERE ID=@id";
string deleteQuery = "DELETE FROM contacts WHERE ID=@id";
string insertQuery = "INSERT INTO contacts VALUES(@first,@middle,@last)";
// Create the parameters for the queries above
SqlParameter[] insertParams = new SqlParameter[]
{
// the first parameter (e.g. @first) has to match with the declaration in the query
// the second parameter (e.g.SqlDbType.NVarChar) is the data type of the actual column in the source table
// the third paramter (e.g. 100) is the length of the data in the database table's column
// the last parameter (e.g. "fname") is the DataPropertyName of the source column which is
// basically the name of the database table column that the DGV column represents
new SqlParameter("@first", SqlDbType.NVarChar, 100, "fname"),
new SqlParameter("@middle", SqlDbType.NVarChar, 100, "mname"),
new SqlParameter("@last", SqlDbType.NVarChar, 100, "lname")
};
SqlParameter[] updateParams = new SqlParameter[]
{
new SqlParameter("@first", SqlDbType.NVarChar, 100, "fname"),
new SqlParameter("@middle", SqlDbType.NVarChar, 100, "mname"),
new SqlParameter("@last", SqlDbType.NVarChar, 100, "lname"),
new SqlParameter("@id", SqlDbType.Int, 100, "id")
};
SqlParameter[] DeleteParams = new SqlParameter[]
{
new SqlParameter("@id", SqlDbType.Int, 100, "id")
};
// Create the SqlCommand objects that will be used by the DataAdapter to modify the source table
SqlCommand insertComm = new SqlCommand(insertQuery, conn);
SqlCommand updateComm = new SqlCommand(updateQuery, conn);
SqlCommand deleteComm = new SqlCommand(deleteQuery, conn);
// Associate the parameters with the proper SqlCommand object
insertComm.Parameters.AddRange(insertParams);
updateComm.Parameters.AddRange(updateParams);
deleteComm.Parameters.AddRange(DeleteParams);
// Give the DataAdapter the commands it needs to be able to properly update your database table
SqlDataAdapter dataAdapter = new SqlDataAdapter()
{
InsertCommand = insertComm,
UpdateCommand = updateComm,
DeleteCommand = deleteComm
};
// A DataTable and a DataSet are basically the same. Except the DataSet is a collection of DataTables
// Here, you can see that we've accessed a specific DataTable in the DataSet.
// Calling the Update method executes the proper command based on the modifications to the specified
// DataTable object then commits these changes to the database
dataAdapter.Update(ds.Tables["contacts"]);
}
上述方法将处理所有数据操作。它将根据对绑定到 DGV 的 DataTable 对象所做的更改进行操作。最后,您可以调用我们在 update 按钮的事件处理程序中创建的所有方法。
private void Btn_Update_Click(object sender, EventArgs e)
{
// Grab the DGV's data source which contains the information shown in the DGV
DataSet ds = (DataSet)dgv_items.DataSource;
// Have any updates to the said dataset committed to the database
UpdateTable(ds);
// rebind the DGV
dgv_items.DataSource = GetData();
}
编辑
根据 Crowcoder 的建议,这里有一个更好的方法来编写我上面写的所有内容:
/// <summary>
/// A collection of methods for easy manipulation of the data in a given SQL table
/// </summary>
class DBOps
{
// The connection string contains parameters that dictate how we connect to the database
private string connString = ConfigurationManager.ConnectionStrings["contactsConnectionString"].ConnectionString;
// The table the instance of the class will be interacting with
private string srcTable;
// The SqlConnection Object that we will be using to connect to the database
SqlConnection conn;
// The DataAdapter object that we will be using to interact with our database
SqlDataAdapter da;
// The DataSet that we will be storing the data retrieved from the database
DataSet ds;
// The queries we would be using to manipulate and interact with the data in the database
private string selectQuery;
private string updateQuery;
private string deleteQuery;
private string insertQuery;
// The collection of parameters for the queries above
private SqlParameter[] insertParams;
private SqlParameter[] updateParams;
private SqlParameter[] DeleteParams;
// The command objects that will be used by our data adapter when
// interacting with the database
private SqlCommand insertComm;
private SqlCommand updateComm;
private SqlCommand deleteComm;
/// <summary>
/// Initialize a new instance of the DBOps class
/// </summary>
/// <param name="tableName">The name of the table that the object will be interacting with</param>
public DBOps(string tableName)
{
// Initialize the SqlConnection object
conn = new SqlConnection(connString);
// Initialize our collection of DataTables
ds = new DataSet();
srcTable = tableName;
// initialize the query strings
selectQuery = string.Format("SELECT * FROM {0}", srcTable);
insertQuery = string.Format("INSERT INTO {0}(fname, mname, lnmae) VALUES(@first, @middle, @last", srcTable);
updateQuery = string.Format("UPDATE {0} SET fname=@first, mname=@middle, lname=@last WHERE ID=@id", srcTable);
deleteQuery = string.Format("DELETE FROM {0} WHERE ID=@id", srcTable);
// Initialize the collection of parameters for each query above
insertParams = new SqlParameter[]
{
// new SqlParameter(@paramName, paramDataType, paramValueLength, DGVDataPropertyName);
new SqlParameter("@first", SqlDbType.NVarChar, 100, "fname"),
new SqlParameter("@middle", SqlDbType.NVarChar, 100, "mname"),
new SqlParameter("@last", SqlDbType.NVarChar, 100, "lname")
};
updateParams = new SqlParameter[]
{
new SqlParameter("@first", SqlDbType.NVarChar, 100, "fname"),
new SqlParameter("@middle", SqlDbType.NVarChar, 100, "mname"),
new SqlParameter("@last", SqlDbType.NVarChar, 100, "lname"),
new SqlParameter("@id", SqlDbType.Int, 100, "id")
};
DeleteParams = new SqlParameter[]
{
new SqlParameter("@id", SqlDbType.Int, 100, "id")
};
// Initialize the SqlCommand objects that will be used by the DataAdapter to modify the source table
insertComm = new SqlCommand(insertQuery, conn);
updateComm = new SqlCommand(updateQuery, conn);
deleteComm = new SqlCommand(deleteQuery, conn);
// Associate the parameters with the proper SqlCommand object
insertComm.Parameters.AddRange(insertParams);
updateComm.Parameters.AddRange(updateParams);
deleteComm.Parameters.AddRange(DeleteParams);
// Give the DataAdapter the commands it needs to be able to properly update your database table
da = new SqlDataAdapter()
{
InsertCommand = insertComm,
UpdateCommand = updateComm,
DeleteCommand = deleteComm
};
}
/// <summary>
/// Retrieve the data from the SQl table
/// </summary>
/// <returns></returns>
public DataSet GetData()
{
DataSet ds = new DataSet();
// Connect to the database and get the data from the "contacts" table
using (conn)
{
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(selectQuery, conn))
{
da.Fill(ds); // Add the rows from the "contacts" table to our dataset
}
}
return ds;
}
/// <summary>
/// Commit the changes present in the object's DataSet to the Database
/// </summary>
public void UpdateData(DataSet ds)
{
// Calling the Update method executes the proper command based on the modifications to the specified
// DataTable object
da.Update(ds.Tables[srcTable]);
}
要使用这个类,只需编写它的一个实例:
DBOps ops = new DBOps("contacts");
在更新按钮的点击事件处理程序中,您可以通过调用 UpdateData 方法提交对 DGV 底层数据源所做的所有更改。
private void Btn_Update_Click(object sender, EventArgs e)
{
// Grab the DGV's data source which contains the information shown in the DGV
DataSet ds = (DataSet)dgv_items.DataSource;
// Have any updates to the said dataset committed to the database
ops.UpdateData(ds);
// rebind the DGV
dgv_items.DataSource = ops.GetData();
}
总结一下:
-
DataAdapter 和DataReader 对象为您提供了允许您以安全、高效和简单的方式与数据库交互的方法。
-
DataTable 和 DataSet 几乎相同。除了DataTable 只是一个表,DataSet 是DataTables 的集合。另一方面,它们中的每一个也具有其他没有的特定方法。