如何在程序中使用数据库第二部分

如何在程序中使用数据库第二部分

本文旨在扩展Frinny的出色文章:

如何在程序中使用数据库 。 Frinny的文章很好地定义了使用数据库的基本概念,并且是阅读本文的前提条件。

Frinny的文章解释了如何在程序中使用SQL Server,但是也有其他数据库。 它们中的一些提供.NET连接器,但是对于那些不提供的连接器,或者如果您不想使用它们,可以使用两种协议连接到它们:

ODBCOle DB 。 请注意,下一节中说明的对象可以与它们的对应对象互换; 它们具有相同的方法和相同的行为。 ODBC
命名空间: System.Data.Odbc

ODBC代表“开放式数据库连接”。 该协议是最通用的。 ODBC依赖

DSN :“数据源名称”。 这些必须在将运行应用程序的计算机上设置:对于ASP.NET,服务器; 对于Windows应用程序,每台客户端计算机。 可以通过注册表设置DSN,但这不在本文的讨论范围之内。 通常在安装数据库或其管理工具时安装ODBC驱动程序。 例如,当您安装IBM的Client Access时,将安装IBMDA400(用于连接到AS400 / Series I)驱动程序。 需要驱动程序来添加DSN。 有用的对象: OdbcConnectionOdbcCommandOdbcDataAdapterOdbcCommandBuilder Ole DB 命名空间: System.Data.OleDb

Ole DB代表“对象链接和嵌入,数据库”。 由于连接字符串指定要使用的提供程序,因此该协议的通用性通常不如ODBC。 该提供程序必须安装在运行该应用程序的系统上,但是不需要DSN或外部连接。 使用Ole DB的“优点”之一是动态定义连接更容易。 例如,您可以使用ODBC或Ole DB连接到Excel电子表格,但是ODBC需要预定义的DSN,或者您必须编辑注册表以添加一个。 如果使用Ole DB,则可以简单地更改连接字符串的“数据源”属性。

有用的对象: OleDbConnectionOleDbCommandOleDbDataAdapterOleDbCommandBuilder 注意: 请注意,从现在开始,我将使用System.Data.OleDb命名空间中的对象作为示例。 请记住,它们可以与对应的对象完全互换。 例如,SqlConnection的行为与OleDbConnection和OdbcConnection相同,因此当您使用不同的协议时,可以将它们换出。 DataAdapters 命名空间: System.Data (用于DataSetDataTable

Frinny解释了如何使用OleDbCommand制作OleDbDataReader。 另一种自动化程度更高的方法是使用OleDbDataAdapter填充DataTable。 OleDbDataAdapters包含Fill(dataSetInstance,“ tableName”)方法,该方法将使用SELECT语句在DataSet中填充DataTable。 该DataTable可以直接绑定到诸如DataGrids和ListBoxes的控件。 您还可以使用OleDbCommandBuilders基于SELECT命令创建INSERT,UPDATE和DELETE命令。 当DataTable中的数据已被修改并且您要提交更改时,可以使用OleDbDataAdapter的Update()方法将更改保存回数据库。


//C#
//set up the connection string
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\dev\db.mdb;User Id=admin;Password=;";
//set up the select statement
string SelectCommand = "SELECT * FROM test";
//set up the connection object using the conn string
OleDbConnection Connection = new OleDbConnection(ConnectionString);
//set up the data adapter using the select statement and the connection object
OleDbDataAdapter Adapter = new OleDbDataAdapter(SelectCommand, Connection);
//a new empty dataset
DataSet ds = new DataSet();
//fill the dataset with a new datatable of all the results
Adapter.Fill(ds, "test");//string is the DataTable name, can be anything
//now, let "Table" point to the datatable with our results
DataTable Table = ds.Tables["test"];
//and you can use the table as needed
dataGridView1.DataSource = Table; 

'VB.NET
'set up the connection string
Dim ConnectionString As String
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\dev\db.mdb;User Id=admin;Password=;"
'set up the select command
Dim SelectCommand As String
SelectCommand = "SELECT * FROM test"
'set up the connection using the conn string
Dim Connection As New OleDbConnection(ConnectionString)
'set up the adapter using select command and connection object
Dim Adapter As New OleDbDataAdapter(SelectCommand, Connection)
'a new blank data set
Dim ds As New DataSet()
'fill the dataset with a datatable of our results
Adapter.Fill(ds, "test") 'test is the datatable name, can be anything
'//now, let "Table" point to the datatable with our results
Dim Table As DataTable
Table = ds.Tables("test")]
'use the data as you see fit
DataGridView1.DataSource = Table 
现在,Table指向一个DataTable,其中包含从查询中检索到的所有数据。 您还可以修改此数据,并轻松将您的更改反映回数据库。

//C#
//set up the command builder using the data adapter
OleDbCommandBuilder Builder = new OleDbCommandBuilder(Adapter);
//use the builder to create update, insert, and delete commands
Adapter.UpdateCommand = Builder.GetUpdateCommand();
Adapter.InsertCommand = Builder.GetInsertCommand();
Adapter.DeleteCommand = Builder.GetDeleteCommand(); 
//manipulate the data in the table
Table.Rows[0]["FirstName"] = "Jimmy"; 
//commit changes of table "test" in the dataset back to the database 
Adapter.Update(ds, "test"); 

'VB.NET
'set up the command builder using the data adapter
Dim Builder As New OleDbCommandBuilder(Adapter)
'use the builder to generate update, insert, and delete commands
Adapter.UpdateCommand = Builder.GetUpdateCommand()
Adapter.InsertCommand = Builder.GetInsertCommand()
Adapter.DeleteCommand = Builder.GetDeleteCommand() 
'manipulate the data in the table
Table.Rows(0)("FirstName") = "Jimmy" 
'commit changes of table "test" in the dataset back to the database 
Adapter.Update(ds, "test") 
注意: 您的数据将被加载到内存中,因此如果您的数据集非常大,请不要使用此方法。 执行标量
命名空间:System.Data。<协议>(OleDb,Odbc,SqlClient)
Frinny向您展示了如何执行DataReader和“ NonQuery”(UPDATE / INSERT / DELETE语句)。 还有另一种有用的方法显示: ExecuteScalar 。 ExecuteScalar()返回查询第一行的第一列作为一个对象。 当您要从数据库中选择一个值时,这很有用。 这对于count,maxsum之类的标量函数特别有用,但并不一定要是标量。

//C#
//set up select scalar command
string ScalarQuery = "SELECT COUNT(*) FROM test";
//set up command object using query and previous connection object
OleDbCommand Command = new OleDbCommand(ScalarQuery, Connection);
//a variable to hold our results:
int count = -1;
//attempt the query
try
{
    //open the connection
    Command.Connection.Open();
    //execute the query and assign the result to "count"
    count = Convert.ToInt32(Command.ExecuteScalar());
    //close the connection
    Command.Connection.Close();
}
//if it didn't work...
catch (OleDbException exc)
{
    MessageBox.Show(String.Format("OleDb Error: {0}", exc.Message));
}
finally
{
    //always double check to make sure your connection is closed
    if (Command.Connection.State != ConnectionState.Closed)
        Command.Connection.Close();
}
//show the results
MessageBox.Show(String.Format("Scalar Result: {0}", count)); 

'VB.NET
'set up select scalar command
Dim ScalarQuery As String
ScalarQuery = "SELECT COUNT(*) FROM test"
'set up command object using query and previous connection object
Dim Command As New OleDbCommand(ScalarQuery, Connection)
'a variable to hold our results:
Dim count As Integer
count = -1
'attempt the query
Try
    'open the connection
    Command.Connection.Open()
    'execute the query and store the result in count
    count = Convert.ToInt32(Command.ExecuteScalar())
    'close the connection
    Command.Connection.Close()
'if it fails...
Catch ex As OleDbException
    MessageBox.Show(String.Format("OleDb Error: {0}", ex.Message))
Finally
    'always make sure your connection is closed
    If Command.Connection.State <> ConnectionState.Closed Then
        Command.Connection.Close()
    End If
End Try
'display results:
MessageBox.Show(String.Format("Scalar Result: {0}", count)) 

From: https://bytes.com/topic/net/insights/817960-how-use-database-your-program-part-ii

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值