Visual Basic and SQL Server – Exporting Data (JSON)

Sometimes it can be useful to export data from a database, so that it can be analysed, or, to import in to another computer system. JSON or JavaScript Object Notation files are an alternative file format to CSV, that can sometimes be used for both of these scenarios.

Below is an example of how Visual Basic can be used to export data to a JSON file called ‘personexport.json’, from an SQL Server database table called ‘person’, which was used in the examples for selecting, inserting, updating, deleting, importing and exporting data to CSV and XML formats.

Firstly, a connection to the database is established, the JSON file path and name are set and a check is made to see if the path actually exists. If it does, a query is executed to extract the data from the database and if data is returned, the JSON file is opened for writing. The contents of the file is then constructed. Feedback is provided as to the success or failure of the task. It should be noted that for this to work the third party library JSON.NET needs to be used and an ‘Imports’ statement must be added for ‘Newtonsoft.Json’.

' Database connection variable.
Dim connect = New SqlConnection(
    "Server=localhost\\MSSQLSERVERDEMO; Database=Demo;" &
    "User Id=DemoUN; Password=DemoPW")

Try

    ' Connect to database.
    connect.Open()

Catch ex As Exception

    ' Confirm unsuccessful connection and stop program execution.
    Console.WriteLine("Database connection unsuccessful.")
    End

End Try

' Export path and file.
Dim exportPath As String = "C:\demo\"
Dim exportJson As String = "personexport.json"

' Stream writer for JSON file.
Dim jsonFile As StreamWriter

' Check to see if the file path exists.
If Directory.Exists(exportPath) Then

    Try

        ' Query text.
        Dim sqlText As String =
            "SELECT id, firstname, lastname, title, dob " &
            "FROM dbo.person " &
            "ORDER BY id"

        ' Query text incorporated into SQL command.
        Dim sqlSelect As New SqlCommand(sqlText, connect)

        ' Execute SQL and place data in a reader object.
        Dim reader As SqlDataReader = sqlSelect.ExecuteReader()

        ' If data has been returned, do the export.
        If reader.HasRows Then

            ' Stream writer for JSON file.
            jsonFile = New StreamWriter(exportPath + exportJson)

            ' Add reader to data table object.
            Dim dataTable As New DataTable()
            dataTable.Load(reader)

            ' String for JSON.
            Dim jsonString As String = String.Empty

            ' Wrapper object for JSON.
            Dim collectionWrapper As New With
            {
                .person = dataTable
            }

            ' Convert to JSON.
            jsonString = JsonConvert.SerializeObject(collectionWrapper,
                                                        Formatting.Indented)

            ' Add JSON to the file.
            jsonFile.Write(jsonString)

            ' Flush the internal buffer.
            jsonFile.Flush()

        Else

            ' Message stating no data to export.
            Console.WriteLine("There is no data to export.")
            End

        End If

        ' Message stating export successful.
        Console.WriteLine("Data export successful.")

    Catch ex As Exception

        ' Message stating export unsuccessful.
        Console.WriteLine("Data export unsuccessful.")
        End

    Finally

        ' Close the database connection.
        connect.Close()

    End Try

Else

    ' Display a message stating file path does not exist.
    Console.WriteLine("File path does not exist.")

End If

The JSON file produced contains the following data.

{
  "person": [
    {
      "id": 1,
      "firstname": "Bob",
      "lastname": "Smith",
      "title": "Mr",
      "dob": "1980-01-20T00:00:00"
    },
    {
      "id": 3,
      "firstname": "Fred",
      "lastname": "Bloggs",
      "title": "Mr",
      "dob": "1975-05-07T00:00:00"
    },
    {
      "id": 4,
      "firstname": "Alan",
      "lastname": "White",
      "title": "Mr",
      "dob": "1989-03-20T00:00:00"
    },
    {
      "id": 5,
      "firstname": "Fiona",
      "lastname": "Bloggs",
      "title": "Mrs",
      "dob": "1985-05-19T00:00:00"
    },
    {
      "id": 6,
      "firstname": "Zoe",
      "lastname": "Davis",
      "title": "Miss",
      "dob": "1979-07-11T00:00:00"
    },
    {
      "id": 7,
      "firstname": "Tom",
      "lastname": "Ingram",
      "title": "Mr",
      "dob": "1971-10-04T00:00:00"
    },
    {
      "id": 8,
      "firstname": "Karen",
      "lastname": "Thomas",
      "title": "Mrs",
      "dob": "1969-03-08T00:00:00"
    },
    {
      "id": 9,
      "firstname": "Samantha",
      "lastname": "Yates",
      "title": "Miss",
      "dob": "1995-08-27T00:00:00"
    }
  ]
}

 

Navigation