65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 ADO.NET 进行数据库操作入门

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.07/5 (37投票s)

2005年1月17日

5分钟阅读

viewsIcon

159833

downloadIcon

4753

使用 ADO.NET 和 C# 实现的个人通讯录

Sample Image

引言

这是《使用 ADO.NET 入门》的第二部分。这是一个简单的个人地址簿程序,可以从数据库表中检索结果,将输出写入文本框,并使用按钮(**首页**、**上一条**、**下一条**、**末页**)进行记录导航。

您还可以通过点击工具栏按钮来操作数据,即**添加/新建记录**、**保存新记录**、**删除当前记录**和**编辑/更新记录**。

我选择了 Microsoft Access 数据库(正如 ADO.NET OleDb 对象所示),因为它易于使用,并且不需要运行 Microsoft SQL Server。但是,当您处理 Microsoft SQL Server 数据库时(正如 ADO.NET SQL 对象所示),ADO.NET 的性能会得到高度优化。

它是如何工作的?

连接到 MS Access 数据库后,所有记录都会显示在文本框中。为了在记录之间导航,您可以使用**下一条**、**上一条**、**首页**、**末页**按钮。您可以在第一部分中找到关于导航按钮使用的详细解释:使用 ADO.NET 入门

插入新记录

如果您点击工具栏上的**新建**按钮,将调用以下方法:

  • fnEnableToolbarButtons(true, "Save") 启用“**保存**”按钮
  • fnEnableToolbarButtons(false, "Delete") 禁用“**删除**”按钮
  • fnEnableToolbarButtons(false, "Edit") 禁用“**编辑**”按钮
  • fnEnableButtonsNextPreviousLastFirst(false) 禁用导航按钮
  • fnClearAllTextBox() 清空所有 textbox
  • fnEnableDisableTextBox(true) 启用 textbox 进行编辑

以下是为**新建**按钮使用的方法的代码片段:

根据调用的方法的两个参数,我们可以启用或禁用 ToolbarButton。例如:fnEnableToolbarButtons(true, "Save"); 表示我们检查参数是否为“Save”和“true”,然后启用“**保存**”按钮。如果我们使用“false”而不是“true”,则会禁用“**保存**”按钮。

private void fnEnableToolbarButtons(bool b, string s1) 
{ 
    if (s1=="New") 
      this.toolBarButtonNew.Enabled=b; 
    else if (s1=="Save")
      this.toolBarButtonSave.Enabled=b;
    else if (s1=="Delete")
      this.toolBarButtonDelete.Enabled=b;
    else if (s1=="Edit")
      this.toolBarButtonEdit.Enabled=b;
    else if (s1=="Refresh")
      this.toolBarButtonRefresh.Enabled=b; 
}

方法 "fnEnableButtonsNextPreviousLastFirst" 只有一个 bool 参数。在 foreach 循环中,我们遍历窗体上的所有控件,检查它是否为 Button,然后使用 bool 参数启用或禁用它。

public void fnEnableButtonsNextPreviousLastFirst(bool flag) 
{ 
    string str; 
    foreach(Control ctrl in this.Controls) 
    { 
       str = Convert.ToString(ctrl.GetType()); 
       if(str == "System.Windows.Forms.Button")             
          ctrl.Enabled = flag;
    }
}

在方法 "fnClearAllTextBox()" 中,我们遍历窗体上的所有控件,检查它是否为 TextBox,然后清空 TextBox 的内容。

private void fnClearAllTextBox() 
{ 
   string str; 
   foreach(Control ctrl in this.Controls)
   { 
     str=Convert.ToString(ctrl.GetType()); 
     if(str=="System.Windows.Forms.TextBox")             
        ctrl.Text = "";
   }
}

public void fnEnableDisableTextBox(bool flag) 
{
   string str; 
   foreach(Control ctrl in this.Controls) 
   { 
      str = Convert.ToString(ctrl.GetType()); 
      if(str == "System.Windows.Forms.TextBox") 
        ctrl.Enabled = flag; 
   }
}

保存新记录

如果您点击**新建**按钮插入一条新记录,**保存**按钮将被启用,以便您可以保存新记录。

此处显示了**保存新记录**方法的代码片段。

private void fnSaveNewRecord() 
{
  try
  {
     string strInsert;
     strInsert = "insert into PersonTable" + 
        "(FirstName, LastName, Title, City,Country)" 
        + " values('" + this.textboxFirstname.Text + "', '"
        + this.textboxLastname.Text + "', '"
        + this.textboxTitle.Text + "', '"
        + this.textboxCity.Text + "', '"
        + this.textboxCountry.Text + "')";
     if (this.textboxFirstname.Text !="" && 
           this.textboxLastname.Text !=""&& 
           this.textboxTitle.Text !="" && 
           this.textboxCity.Text !="" 
           && this.textboxCountry.Text !="") 
     { 
         this.oleDbDataAdapter1.InsertCommand.CommandText = strInsert;
         //do the insert
         this.oleDbDataAdapter1.InsertCommand.ExecuteNonQuery();
         //Get the last PersonID from the table and display it in TextBox
         fnGetLastPersonID(); 
         fnEnableButtonsNextPreviousLastFirst(true);
         fnEnableToolbarButtons(true, "Edit"); 
         fnEnableToolbarButtons(true, "Delete"); 
         fnEnableToolbarButtons(false, "Save");
         this.fnEnableDisableTextBox(false); 
     }else 
     {
         MessageBox.Show("You have to fill the TextBoxes...", 
                 "WARNING", MessageBoxButtons.OK,MessageBoxIcon.Warning);
                  this.textboxFirstname.Focus();
     }
  }
  catch (Exception ex)
  {
     MessageBox.Show("Error in inserting new record : " + 
        ex.Message, "Insert Error", MessageBoxButtons.OK, 
        MessageBoxIcon.Information);
     fnRefreshDataSet();
  } //try-catch
}

如您所见,“fnSaveNewRecord()”方法中调用了一些方法。其中之一是“fnGetLastPersonID()”,它从表中获取最后一个 PersonID 并将其显示在 TextBox "textboxPersonID" 中。在新记录插入并执行 INSERT 命令后,我会获取新插入记录的 PersonID

这里,您应该注意如何解决了表中 "PersonTable" 的 DataType AutoNumber 问题。我为 AutoNumber 问题选择了一种不同的方法。

首先,您需要仅为 PersonID 列创建 SELECT 命令。然后

  • 使用连接和 string 命令(strCom)执行 DataReader 和命令。
  • 运行 while 循环并获取列 0(GetValue(0))的所有值(内容)。
  • 将其存储在 object 变量中,直到列(0)的所有值结束为止,将其转换为整数。

while 循环结束后,您将在第一个(0)GetValue(0) 列的 while 循环外部获得最后一个值。将 PersonID 加 1 并将其显示在 TextBox "textboxPersonID" 中。

这是方法 "fnGetLastPersonID()" 的代码。

private void fnGetLastPersonID() 
{
    string strCom = "Select Max(PersonID) from PersonTable" ; 
    OleDbCommand cmd =new OleDbCommand(strCom,this.oleDbConnection1);
    OleDbDataReader reader;
    reader =cmd.ExecuteReader() ;
    int i=0 ; //how many records in the table?, only for test
    int iPersonid=0; //the integer value of the first column(0) contents
    while(reader.Read()) 
    {
       i++ ;
       // GetValue(0) means: The contents
       // of the first column(0)(PersonID) in the table
       object obValue = reader.GetValue(0);
       iPersonid = Convert.ToInt32(obValue.ToString());
    }
    i++ ; 
    this.textboxPersonID.Text=iPersonid.ToString(); //display it in TextBox
    reader.Close(); //close the DataReader otherwise error
    MessageBox.Show("Record with new PersonID: "+iPersonid.ToString()+ 
           " inserted successfully", "Save New", MessageBoxButtons.OK, 
           MessageBoxIcon.Information); //inform the user
}

删除当前记录

当前记录通过 "fnDeleteCurrentRecord()" 方法被删除。如果点击**删除**按钮,系统会询问您是否要删除该记录。如果回答是**是**,则执行 DELETE 命令并调用 "fnRefreshDataSet()" 方法。

代码片段如下:

private void fnDeleteCurrentRecord 
{
    DialogResult dr=MessageBox.Show("Are you sure you want to delete" + 
                    " this record ? ", "Confirm deleting", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question); 
     //convert textboxPersonID into integer
    int pid=int.Parse(this.textboxPersonID.Text); 
    if (dr ==DialogResult.Yes)
    {
      string strDel="DELETE FROM PersonTable WHERE PersonID= "+pid;
      fnExecuteQuery(strDel); 
      fnRefreshDataSet(); 
      MessageBox.Show("Record deleted..."); 
    }
    else
      MessageBox.Show("Record NOT deleted..."); 
}

编辑当前记录

当您在记录之间导航时,当前记录在文本框中是禁用编辑的。一旦您点击**编辑**按钮,所有文本框将被启用以进行编辑,并且**更新**按钮将出现在工具栏中,以便您可以保存当前更新的记录。

this.toolBarButtonNew.Enabled=false; 
this.fnEnableDisableTextBox(true); 
fnSetEditUpdateText("Update");

这是 "fnSetEditUpdateText()" 方法,它接受一个 string 作为参数。

private void fnSetEditUpdateText(string str)
{
  this.toolBarButtonEdit.Text=str; 
}

更新/保存编辑后的当前记录

以下是点击**更新**按钮时调用的方法:

fnUpdateRecord(); 
fnSetEditUpdateText("Edit"); 
fnEnableToolbarButtons(true, "New"); 
this.fnEnableDisableTextBox(false);

首先,调用 "fnUpdateRecord()" 方法来更新记录。其次,使用 fnSetEditUpdateText("Edit") 方法将**更新**按钮的文本更改为“**编辑**”。然后调用 "fnEnableToolbarButtons(true, "New")" 方法将“**新建**”按钮设置为启用状态。最后,调用 "fnEnableDisableTextBox(false)" 方法,借助参数“false”禁用所有文本框。

这是 "fnUpdateRecord()" 方法的代码片段。

private void fnUpdateRecord() 
{
  try 
  {
     string strUpdateQuery = "update PersonTable set FirstName='"
    +this.textboxFirstname.Text+"',LastName='"
    +this.textboxLastname.Text+"' ,Title='"
    +this.textboxTitle.Text+"' ,City='"
    +this.textboxCity.Text+"' ,Country='"
    +this.textboxCountry.Text +"' WHERE PersonID= "+this.textboxPersonID.Text;
    fnExecuteQuery(strUpdateQuery);
    fnRefreshDataSet();  
    MessageBox.Show("Record updated..."); 
  }catch(Exception ex) 
  {
     MessageBox.Show(ex.ToString());
  }
}

刷新/取消行

通过**刷新**按钮,所有**文本框**都被设置为禁用编辑。**更新**按钮的文本将更改为“**编辑**”,**保存**按钮被禁用(false),**编辑**、**删除**和**新建**按钮被启用(true)。通过 "fnEnableButtonsNextPreviousLastFirst(true)" 方法,所有导航按钮(**下一条**、**上一条**、**末页**、**首页**)都将被启用。最后,调用 "fnRefreshDataSet()" 方法刷新 DataSet 中的行。换句话说,将显示第一条记录。

这是方法 "fnRefreshDataSet()" 的代码片段, 

private void fnRefreshDataSet()
{
  this.dataSet11.Clear(); //clear the contents of dataset 
  this.oleDbDataAdapter1.Fill(this.dataSet11,"PersonTable"); 
}

结论

我希望这个程序对您的 ADO.NET 数据库项目有所帮助。如果您愿意,可以向窗体添加新的 textbox(电话、传真、邮政编码等)来扩展该程序。我将很乐意收到任何建议或意见。

再次,这是此应用程序第一部分的文章链接:使用 ADO.NET 入门

编码愉快!!

历史

  • 2005 年 5 月 17 日:初始版本

许可证

本文没有明确的许可附加,但可能包含文章文本或下载文件本身的使用条款。如有疑问,请通过下面的讨论板联系作者。您可以 此处 找到作者可能使用的许可列表。

© . All rights reserved.