CreateDataAdapter 对象的 DbProviderFactory 方法为您提供 DbDataAdapter 对象,该对象强类型化为创建工厂时指定的基础数据提供程序。 然后,可以使用DbCommandBuilder创建命令,将DataSet中的数据插入、更新和删除到数据源中。
使用 DbDataAdapter 检索数据
此示例演示如何基于提供程序名称和连接字符串来创建强类型的 DbDataAdapter
。 该代码使用CreateConnection方法在DbProviderFactory中创建DbConnection。 接下来,代码使用CreateCommand方法通过设置DbCommand和CommandText
属性来创建Connection
以选择数据。 最后,代码使用DbDataAdapter该方法创建对象CreateDataAdapter并设置其SelectCommand
属性。
Fill
方法将DbDataAdapter
的数据加载到DataTable中。
static void CreateDataAdapter(string providerName, string connectionString)
{
try
{
// Create the DbProviderFactory and DbConnection.
DbProviderFactory factory =
DbProviderFactories.GetFactory(providerName);
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
using (connection)
{
// Define the query.
const string queryString =
"SELECT CategoryName FROM Categories";
// Create the DbCommand.
DbCommand command = factory.CreateCommand();
command.CommandText = queryString;
command.Connection = connection;
// Create the DbDataAdapter.
DbDataAdapter adapter = factory.CreateDataAdapter();
adapter.SelectCommand = command;
// Fill the DataTable.
DataTable table = new();
adapter.Fill(table);
// Display each row and column value.
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Shared Sub CreateDataAdapter(ByVal providerName As String, _
ByVal connectionString As String)
' Create the DbProviderFactory and DbConnection.
Try
Dim factory As DbProviderFactory = _
DbProviderFactories.GetFactory(providerName)
Dim connection As DbConnection = _
factory.CreateConnection()
connection.ConnectionString = connectionString
Using connection
' Define the query.
Dim queryString As String = _
"SELECT CategoryName FROM Categories"
'Create the DbCommand.
Dim command As DbCommand = _
factory.CreateCommand()
command.CommandText = queryString
command.Connection = connection
' Create the DbDataAdapter.
Dim adapter As DbDataAdapter = _
factory.CreateDataAdapter()
adapter.SelectCommand = command
' Fill the DataTable
Dim table As New DataTable
adapter.Fill(table)
'Display each row and column value.
Dim row As DataRow
Dim column As DataColumn
For Each row In table.Rows
For Each column In table.Columns
Console.WriteLine(row(column))
Next
Next
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
使用 DbDataAdapter 修改数据
此示例演示如何通过使用 DataTable
生成更新数据源的数据所需的命令,从而使用 DbDataAdapter 来修改 DbCommandBuilder 中的数据。
SelectCommand 的 DbDataAdapter
设置为从 Customers 表检索 CustomerID 和 CompanyName。 该方法 GetInsertCommand 用于设置 InsertCommand 属性, GetUpdateCommand 该方法用于设置 UpdateCommand 属性,该方法 GetDeleteCommand 用于设置 DeleteCommand 属性。 该代码将新行添加到 Customers 表并更新数据源。 然后,该代码通过搜索 CustomerID(为 Customers 表定义的主键)来查找添加的行。 代码更改 CompanyName 并更新数据源。 最后,代码将删除该行。
static void CreateDataAdapter(string providerName, string connectionString)
{
try
{
// Create the DbProviderFactory and DbConnection.
DbProviderFactory factory =
DbProviderFactories.GetFactory(providerName);
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
using (connection)
{
// Define the query.
const string queryString =
"SELECT CustomerID, CompanyName FROM Customers";
// Create the select command.
DbCommand command = factory.CreateCommand();
command.CommandText = queryString;
command.Connection = connection;
// Create the DbDataAdapter.
DbDataAdapter adapter = factory.CreateDataAdapter();
adapter.SelectCommand = command;
// Create the DbCommandBuilder.
DbCommandBuilder builder = factory.CreateCommandBuilder();
builder.DataAdapter = adapter;
// Get the insert, update and delete commands.
adapter.InsertCommand = builder.GetInsertCommand();
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.DeleteCommand = builder.GetDeleteCommand();
// Display the CommandText for each command.
Console.WriteLine($"InsertCommand: {adapter.InsertCommand.CommandText}");
Console.WriteLine($"UpdateCommand: {adapter.UpdateCommand.CommandText}");
Console.WriteLine($"DeleteCommand: {adapter.DeleteCommand.CommandText}");
// Fill the DataTable.
DataTable table = new();
adapter.Fill(table);
// Insert a new row.
DataRow newRow = table.NewRow();
newRow["CustomerID"] = "XYZZZ";
newRow["CompanyName"] = "XYZ Company";
table.Rows.Add(newRow);
adapter.Update(table);
// Display rows after insert.
Console.WriteLine();
Console.WriteLine("----List All Rows-----");
foreach (DataRow row in table.Rows)
{
Console.WriteLine($"{row[0]} {row[1]}");
}
Console.WriteLine("----After Insert-----");
// Edit an existing row.
DataRow[] editRow = table.Select("CustomerID = 'XYZZZ'");
editRow[0]["CompanyName"] = "XYZ Corporation";
adapter.Update(table);
// Display rows after update.
Console.WriteLine();
foreach (DataRow row in table.Rows)
{
Console.WriteLine($"{row[0]} {row[1]}");
}
Console.WriteLine("----After Update-----");
// Delete a row.
DataRow[] deleteRow = table.Select("CustomerID = 'XYZZZ'");
foreach (DataRow row in deleteRow)
{
row.Delete();
}
adapter.Update(table);
// Display rows after delete.
Console.WriteLine();
foreach (DataRow row in table.Rows)
{
Console.WriteLine($"{row[0]} {row[1]}");
}
Console.WriteLine("----After Delete-----");
Console.WriteLine("Customer XYZZZ was deleted.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Shared Sub CreateDataAdapter(ByVal providerName As String, _
ByVal connectionString As String)
' Create the DbProviderFactory and DbConnection.
Try
Dim factory As DbProviderFactory = _
DbProviderFactories.GetFactory(providerName)
Dim connection As DbConnection = _
factory.CreateConnection()
connection.ConnectionString = connectionString
Using connection
' Define the query.
Dim queryString As String = _
"SELECT CustomerID, CompanyName FROM Customers"
'Create the select command.
Dim command As DbCommand = _
factory.CreateCommand()
command.CommandText = queryString
command.Connection = connection
' Create the DbDataAdapter.
Dim adapter As DbDataAdapter = _
factory.CreateDataAdapter()
adapter.SelectCommand = command
' Create the DbCommandBuilder.
Dim builder As DbCommandBuilder = _
factory.CreateCommandBuilder()
builder.DataAdapter = adapter
' Get the insert, update and delete commands.
adapter.InsertCommand = builder.GetInsertCommand()
adapter.UpdateCommand = builder.GetUpdateCommand()
adapter.DeleteCommand = builder.GetDeleteCommand()
' Display the CommandText for each command.
Console.WriteLine("InsertCommand: {0}", _
adapter.InsertCommand.CommandText)
Console.WriteLine("UpdateCommand: {0}", _
adapter.UpdateCommand.CommandText)
Console.WriteLine("DeleteCommand: {0}", _
adapter.DeleteCommand.CommandText)
' Fill the DataTable
Dim table As New DataTable
adapter.Fill(table)
' Insert a new row.
Dim newRow As DataRow = table.NewRow
newRow("CustomerID") = "XYZZZ"
newRow("CompanyName") = "XYZ Company"
table.Rows.Add(newRow)
adapter.Update(table)
' Display rows after insert.
Console.WriteLine()
Console.WriteLine("----List All Rows-----")
Dim row As DataRow
For Each row In table.Rows
Console.WriteLine("{0} {1}", row(0), row(1))
Next
Console.WriteLine("----After Insert-----")
' Edit an existing row.
Dim editRow() As DataRow = _
table.Select("CustomerID = 'XYZZZ'")
editRow(0)("CompanyName") = "XYZ Corporation"
adapter.Update(table)
' Display rows after update.
Console.WriteLine()
For Each row In table.Rows
Console.WriteLine("{0} {1}", row(0), row(1))
Next
Console.WriteLine("----After Update-----")
' Delete a row.
Dim deleteRow() As DataRow = _
table.Select("CustomerID = 'XYZZZ'")
For Each row In deleteRow
row.Delete()
Next
adapter.Update(table)
table.AcceptChanges()
' Display each row and column value after delete.
Console.WriteLine()
For Each row In table.Rows
Console.WriteLine("{0} {1}", row(0), row(1))
Next
Console.WriteLine("----After Delete-----")
Console.WriteLine("Customer XYZZZ was deleted.")
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
处理参数
.NET Framework 数据提供程序以不同的方式处理命名和指定参数和参数占位符。 此语法是针对特定数据源定制的,如下表所述。
数据提供程序 | 参数命名语法 |
---|---|
SqlClient |
使用格式 @ 参数名称中的命名参数。 |
OracleClient |
使用格式 : parmname (或 parmname)中的命名参数。 |
OleDb |
使用问号 (? ) 作为位置参数标记。 |
Odbc |
使用问号 (? ) 作为位置参数标记。 |
工厂模型对创建参数化 DbCommand
和 DbDataAdapter
对象没有帮助。 你需要编写分支代码来创建针对数据提供程序定制的参数。
重要
出于安全原因,不建议使用字符串串联来构造直接 SQL 语句来完全避免提供程序特定的参数。 使用字符串串联而不是参数会使应用程序容易受到 SQL 注入攻击。