VB.Net/Database ADO.net/DataSet XML

Материал из VB Эксперт
Перейти к: навигация, поиск

Display XML String from an ADO.NET DataSet

 
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections
Imports System.Windows.Forms
Imports System.Resources
Public Class MainClass
    Shared Dim OleDbConnection As System.Data.OleDb.OleDbConnection
    Shared Dim AddressBookDataAdapter As System.Data.OleDb.OleDbDataAdapter
    Shared Dim AddressBookDataSet As System.Data.DataSet
    Shared Sub Main()
       Connect()
       Display()
       Console.WriteLine( AddressBookDataSet.GetXml() )
       
       
       Display()
       Disconnect()
    End Sub
    Shared Sub Display()
       Dim OleDbSelectCommand As System.Data.OleDb.OleDbCommand
       OleDbSelectCommand = New System.Data.OleDb.OleDbCommand()
       OleDbSelectCommand.rumandText = "SELECT ID, FirstName, LastName,Salary FROM Employee"
       OleDbSelectCommand.Connection = OleDbConnection
       AddressBookDataAdapter = New System.Data.OleDb.OleDbDataAdapter()
       AddressBookDataAdapter.SelectCommand = OleDbSelectCommand

       AddressBookDataSet = New System.Data.DataSet()
       CType(AddressBookDataSet, System.ruponentModel.ISupportInitialize).BeginInit()
       AddressBookDataAdapter.Fill(AddressBookDataSet)

         Dim dataTable As DataTable = AddressBookDataSet.Tables(0)
         " ensure dataTable not empty
         If dataTable.Rows.Count <> 0 Then
            Dim recordNumber As Integer = Convert.ToInt32(dataTable.Rows(0)(0))
            Console.Write( recordNumber.ToString & "  ")
            Console.Write( Convert.ToString(dataTable.Rows(0)(1)) & "  ")
            Console.Write( Convert.ToString(dataTable.Rows(0)(2)) & "  ")
            Console.Write( Convert.ToString(dataTable.Rows(0)(3)) & "  ")
            " display not-found message
         Else
            Console.WriteLine( "No record found" )
         End If
         Console.WriteLine(  )
    End Sub
    Shared Sub Connect()
      OleDbConnection = New System.Data.OleDb.OleDbConnection()
      OleDbConnection.ConnectionString = _
         "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _
         "User ID=Admin;Data Source=Employee.mdb;Mode=Sha" & _
         "re Deny None;Extended Properties="""";" & _
         "Jet OLEDB:System database="""";Jet OLEDB:Regis" & _
         "try Path="""";Jet OLEDB:Database Password="""";" & _
         "Jet OLEDB:Engine Type=5;Jet OLEDB:Dat" & _
         "abase Locking Mode=1;Jet OLEDB:Global Partial " & _
         "Bulk Ops=2;Jet OLEDB:Global Bulk T" & _
         "ransactions=1;Jet OLEDB:New Database " & _
         "Password="""";Jet OLEDB:Create System Databas" & _
         "e=False;Jet OLEDB:Encrypt Database=False;" & _
         "Jet OLEDB:Don"t Copy Locale on Compact=" & _
         "False;Jet OLEDB:Compact Without Replica " & _
         "Repair=False;Jet OLEDB:SFP=False"

      Try
         OleDbConnection.Open()
      Catch ex As Exception
         Console.WriteLine(ex.Message)
      End Try
    End Sub
    Shared Sub Disconnect()
      Try
         OleDbConnection.Close()
      Catch ex As Exception
         Console.WriteLine(ex.Message)
      End Try
    End Sub
End Class


Generating XML from an ADO.NET DataSet

 
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections
Imports System.Windows.Forms
Imports System.Resources
Public Class MainClass
    Shared Dim OleDbConnection As System.Data.OleDb.OleDbConnection
    Shared Dim AddressBookDataAdapter As System.Data.OleDb.OleDbDataAdapter
    Shared Dim AddressBookDataSet As System.Data.DataSet
    Shared Sub Main()
       Connect()
       Display()
       
       AddressBookDataSet.WriteXml("Employee.xml")
       Display()
       Disconnect()
    End Sub
    Shared Sub Display()
       Dim OleDbSelectCommand As System.Data.OleDb.OleDbCommand
       OleDbSelectCommand = New System.Data.OleDb.OleDbCommand()
       OleDbSelectCommand.rumandText = "SELECT ID, FirstName, LastName,Salary FROM Employee"
       OleDbSelectCommand.Connection = OleDbConnection
       AddressBookDataAdapter = New System.Data.OleDb.OleDbDataAdapter()
       AddressBookDataAdapter.SelectCommand = OleDbSelectCommand

       AddressBookDataSet = New System.Data.DataSet()
       CType(AddressBookDataSet, System.ruponentModel.ISupportInitialize).BeginInit()
       AddressBookDataAdapter.Fill(AddressBookDataSet)

         Dim dataTable As DataTable = AddressBookDataSet.Tables(0)
         " ensure dataTable not empty
         If dataTable.Rows.Count <> 0 Then
            Dim recordNumber As Integer = Convert.ToInt32(dataTable.Rows(0)(0))
            Console.Write( recordNumber.ToString & "  ")
            Console.Write( Convert.ToString(dataTable.Rows(0)(1)) & "  ")
            Console.Write( Convert.ToString(dataTable.Rows(0)(2)) & "  ")
            Console.Write( Convert.ToString(dataTable.Rows(0)(3)) & "  ")
            " display not-found message
         Else
            Console.WriteLine( "No record found" )
         End If
         Console.WriteLine(  )
    End Sub
    Shared Sub Connect()
      OleDbConnection = New System.Data.OleDb.OleDbConnection()
      OleDbConnection.ConnectionString = _
         "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _
         "User ID=Admin;Data Source=Employee.mdb;Mode=Sha" & _
         "re Deny None;Extended Properties="""";" & _
         "Jet OLEDB:System database="""";Jet OLEDB:Regis" & _
         "try Path="""";Jet OLEDB:Database Password="""";" & _
         "Jet OLEDB:Engine Type=5;Jet OLEDB:Dat" & _
         "abase Locking Mode=1;Jet OLEDB:Global Partial " & _
         "Bulk Ops=2;Jet OLEDB:Global Bulk T" & _
         "ransactions=1;Jet OLEDB:New Database " & _
         "Password="""";Jet OLEDB:Create System Databas" & _
         "e=False;Jet OLEDB:Encrypt Database=False;" & _
         "Jet OLEDB:Don"t Copy Locale on Compact=" & _
         "False;Jet OLEDB:Compact Without Replica " & _
         "Repair=False;Jet OLEDB:SFP=False"

      Try
         OleDbConnection.Open()
      Catch ex As Exception
         Console.WriteLine(ex.Message)
      End Try
    End Sub
    Shared Sub Disconnect()
      Try
         OleDbConnection.Close()
      Catch ex As Exception
         Console.WriteLine(ex.Message)
      End Try
    End Sub
End Class

<A href="http://www.vbex.ru/Code/VBDownload/Employee.zip">Employee.zip( 7 k)</a>


Write Data in DataSet to XML file

 
Imports System
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Xml
Imports System.Windows.Forms
public class MainClass
   Shared Sub Main()
      Dim form1 As Form = New Form1
      Application.Run(form1)
   End Sub
End Class


Public Class Form1
   Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
   Public Sub New()
      MyBase.New()
      "This call is required by the Windows Form Designer.
      InitializeComponent()
      "Add any initialization after the InitializeComponent() call
   End Sub
   "Form overrides dispose to clean up the component list.
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing Then
         If Not (components Is Nothing) Then
            components.Dispose()
         End If
      End If
      MyBase.Dispose(disposing)
   End Sub
   "Required by the Windows Form Designer
   Private components As System.ruponentModel.IContainer
   "NOTE: The following procedure is required by the Windows Form Designer
   "It can be modified using the Windows Form Designer.  
   "Do not modify it using the code editor.
   Friend WithEvents btnConfigXML As System.Windows.Forms.Button
   Friend WithEvents XmlGrid As System.Windows.Forms.DataGrid
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
      Me.btnConfigXML = New System.Windows.Forms.Button
      Me.XmlGrid = New System.Windows.Forms.DataGrid
      CType(Me.XmlGrid, System.ruponentModel.ISupportInitialize).BeginInit()
      Me.SuspendLayout()
      "
      "btnConfigXML
      "
      Me.btnConfigXML.Location = New System.Drawing.Point(16, 27)
      Me.btnConfigXML.Name = "btnConfigXML"
      Me.btnConfigXML.Size = New System.Drawing.Size(75, 37)
      Me.btnConfigXML.TabIndex = 2
      Me.btnConfigXML.Text = "Configure XML"
      "
      "XmlGrid
      "
      Me.XmlGrid.DataMember = ""
      Me.XmlGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText
      Me.XmlGrid.Location = New System.Drawing.Point(112, 8)
      Me.XmlGrid.Name = "XmlGrid"
      Me.XmlGrid.Size = New System.Drawing.Size(304, 336)
      Me.XmlGrid.TabIndex = 3
      "
      "Form1
      "
      Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
      Me.ClientSize = New System.Drawing.Size(424, 349)
      Me.Controls.Add(Me.XmlGrid)
      Me.Controls.Add(Me.btnConfigXML)
      Me.Name = "Form1"
      Me.Text = "XML Demo"
      CType(Me.XmlGrid, System.ruponentModel.ISupportInitialize).EndInit()
      Me.ResumeLayout(False)
   End Sub
#End Region
   Private Sub form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles MyBase.Load
      " Create connection
      Dim thisConnection As New SqlConnection("Server=(local)\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=SSPI") 
      " Query string
      Dim sql As String = _
         "SELECT ID, LastName " & _
         "FROM Employee " & _
         "FOR XML AUTO"
      " Create Connection
      Dim thisCommand As New SqlCommand(sql, thisConnection)
      Try
         thisConnection.Open()
         Dim reader As XmlReader = thisCommand.ExecuteXmlReader()
         Dim ds As New DataSet
         ds.ReadXml(reader, XmlReadMode.InferSchema)
         XmlGrid.DataSource = ds

         " Write Data in DataSet to XML file
         ds = CType(XmlGrid.DataSource, DataSet)
         ds.WriteXml("XMLFileOut.xml", XmlWriteMode.IgnoreSchema)
      Catch ex As SqlException
         MessageBox.Show(ex.Message)
      Finally
         thisConnection.Close()
      End Try
   End Sub
End Class


XML DataSet

  
Imports System.Data.SqlClient
Imports System.Windows.Forms
<Global.Microsoft.VisualBasic.rupilerServices.DesignerGenerated()> _
Partial Class XmlTest
    Inherits System.Windows.Forms.Form
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.grid = New System.Windows.Forms.DataGridView
        Me.txtFile = New System.Windows.Forms.TextBox
        Me.cmdRead = New System.Windows.Forms.Button
        Me.cmdWrite = New System.Windows.Forms.Button
        CType(Me.grid, System.ruponentModel.ISupportInitialize).BeginInit()
        Me.SuspendLayout()
        "
        Me.grid.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.grid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
        Me.grid.Location = New System.Drawing.Point(11, 43)
        Me.grid.Name = "grid"
        Me.grid.Size = New System.Drawing.Size(352, 212)
        Me.grid.TabIndex = 8
        "
        Me.txtFile.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.txtFile.Location = New System.Drawing.Point(11, 14)
        Me.txtFile.Size = New System.Drawing.Size(160, 21)
        Me.txtFile.TabIndex = 7
        Me.txtFile.Text = "c:\DataSet.xml"
        "
        Me.cmdRead.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.cmdRead.Location = New System.Drawing.Point(271, 12)
        Me.cmdRead.Size = New System.Drawing.Size(92, 24)
        Me.cmdRead.TabIndex = 6
        Me.cmdRead.Text = "Read From XML"
        "
        Me.cmdWrite.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.cmdWrite.Location = New System.Drawing.Point(183, 12)
        Me.cmdWrite.Size = New System.Drawing.Size(84, 24)
        Me.cmdWrite.TabIndex = 5
        Me.cmdWrite.Text = "Write to XML"
        "
        "XmlTest
        "
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(375, 266)
        Me.Controls.Add(Me.grid)
        Me.Controls.Add(Me.txtFile)
        Me.Controls.Add(Me.cmdRead)
        Me.Controls.Add(Me.cmdWrite)
        Me.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Name = "XmlTest"
        Me.Text = "XmlTest"
        CType(Me.grid, System.ruponentModel.ISupportInitialize).EndInit()
        Me.ResumeLayout(False)
        Me.PerformLayout()
    End Sub
    Friend WithEvents grid As System.Windows.Forms.DataGridView
    Friend WithEvents txtFile As System.Windows.Forms.TextBox
    Friend WithEvents cmdRead As System.Windows.Forms.Button
    Friend WithEvents cmdWrite As System.Windows.Forms.Button
    Private Sub cmdWrite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdWrite.Click
        Dim SQL As String = "SELECT * FROM Products"
        Dim Connect As String = "Data Source=localhost;Integrated Security=True;Initial Catalog=Northwind;"
        Dim con As New SqlConnection(Connect)
        Dim cmd As New SqlCommand(SQL, con)
        Dim adapter As New SqlDataAdapter(cmd)
        Dim dsNorthwind As New DataSet()
        con.Open()
        adapter.Fill(dsNorthwind, "Products")
        con.Close()
        dsNorthwind.WriteXmlSchema(txtFile.Text & ".xsd")
        dsNorthwind.WriteXml(txtFile.Text)
    End Sub
    Private Sub cmdRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRead.Click
        Dim dsNorthwind As New DataSet()
        If System.IO.File.Exists(txtFile.Text) Then
            dsNorthwind.ReadXml(txtFile.Text)
            grid.DataSource = dsNorthwind.Tables(0)
        Else
            MessageBox.Show("You need to create this file first.")
        End If
    End Sub
End Class