C# and PostgreSQL – Generating Data

In order to test the performance of a database, or application that uses it, where there are large volumes of data, it may be useful to generate data rather than having to enter it manually.

The following example demonstrates how to generate data for a table called ‘person’, which was used in the examples for selecting, inserting, updating, deleting, importing (CSV, text, XML and JSON) and exporting data (CSV, text, XML and JSON).

First of all, a connection to the database is established and the number of records to generate is specified. This can be set to any value, as long as there is enough space in the database to accommodate the records. A number of arrays are defined so that a random first name, last name and title can be selected for each record. The first name array also holds the gender associated with the name so that an appropriate title can be selected. A date range is also specified to allow for the generation of a random date of birth, along with other variables.

A ‘for’ loop is used to generate the desired number of records. A random number is generated to select a first name from the corresponding array and this is extracted, along with the gender. The same process occurs to extract a random last name. The gender is then used to extract a title from the appropriate array. The final random value generated is the date of birth.

Once all the values have been generated, an SQL ‘insert‘ statement is constructed and then executed. Feedback is provided as to the number of records added to the database. A ‘try-catch-finally’ block is used to catch any errors that may occur, as well as close the database connection, regardless of whether the addition of records is successful or not.

// Database connection variable.
NpgsqlConnection connect = new NpgsqlConnection(
    "Server=localhost;" +
    "Database=Demo;" +
    "User Id=DemoUN;" +


    // Connect to database.

catch (Exception e)

    // Message confirming unsuccessful database connection.
    Console.WriteLine("Database connection unsuccessful.");

    // Stop program execution.


// Number of records to generate.
int recordsToGenerate = 500;

// First names.
string[,] fname = new string[,]
    { "Oliver", "M"}, { "Noah", "M"}, { "Harry", "M"},
    { "Leo", "M"}, { "Charlie", "M"}, { "Jack", "M"},
    { "Freddie", "M"}, { "Alfie", "M"}, { "Archie", "M"},
    { "Theo", "M"}, { "Olivia", "F"}, { "Sophia", "F"},
    { "Amelia", "F"}, { "Emily", "F"}, { "Ava", "F"},
    { "Isla", "F"}, { "Isabelle", "F"}, { "Charlotte", "F"},
    { "Layla", "F"}, { "Freya", "F"}

// Last names.
string[] lname = new string[]
    "Smith", "Johnson", "Williams", "Jones",
    "Brown", "Davis", "Miller", "Wilson",
    "Taylor", "Anderson", "Thomas", "White",
    "Martin", "Thompson", "Robinson", "Clark",
    "Walker", "Young", "Wright", "Hill"

// Male titles.
string[] mtitle = new string[]
    "Mr", "Dr", "Prof"

// Female titles.
string[] ftitle = new string[]
    "Miss", "Mrs", "Ms", "Dr", "Prof"

// Start and end dates for random date of birth range.
DateTime startDob = DateTime.Now.Date.AddYears(-100);
DateTime endDob = DateTime.Now.Date.AddYears(-20);

// Days between start and end date of birth.
int dobDiff = (endDob.Date - startDob.Date).Days;

// Random class and number.
Random random = new Random();
int randomNumber;

// New record values.
string firstname;
string lastname;
string gender;
string title;
DateTime dob;

// SQL variable.
string sqlPersonInfo;

// Record count.
int recordCount = 0;


    // Generate specified number of records.
    for (int i = 1; i <= recordsToGenerate; i++)

        // Randomly select a first name and associated gender.
        randomNumber = random.Next(0, fname.GetLength(0) - 1);
        firstname = fname[randomNumber, 0];
        gender = fname[randomNumber, 1];

        // Randomly select a last name.
        randomNumber = random.Next(0, lname.GetLength(0) - 1);
        lastname = lname[randomNumber];

        // Randomly select a title based on the gender.
        if (gender == "M")

            randomNumber = random.Next(0, mtitle.GetLength(0) - 1);
            title = mtitle[randomNumber];


            randomNumber = random.Next(0, ftitle.GetLength(0) - 1);
            title = ftitle[randomNumber];


        // Randomly select a date of birth.
        dob = startDob.AddDays(random.Next(dobDiff));

        // Query text.
        sqlPersonInfo = @"
            INSERT INTO person 
                    (firstname, lastname, title, dob) 
            VALUES (@firstname, @lastname, @title, @dob)

        // Query text incorporated into SQL command.
        NpgsqlCommand sqlInsert = new NpgsqlCommand(sqlPersonInfo, connect);

        // Bind the parameters to the query.
        sqlInsert.Parameters.AddWithValue("@firstname", firstname);
        sqlInsert.Parameters.AddWithValue("@lastname", lastname);
        sqlInsert.Parameters.AddWithValue("@title", title);

        // Execute SQL.

        // Increment the record count.
        recordCount += 1;


    // Provide feedback on the number of records added.
    if (recordCount == 0)

        Console.WriteLine("No new person records added.");

    else if (recordCount == 1)

        Console.WriteLine(recordCount + " person record added.");


        Console.WriteLine(recordCount + " person records added.");


catch (Exception e)

    // Confirm error adding person information and exit.
    Console.WriteLine("Error adding person information.");


    // Close the database connection.


Further Resources