Enterprise Application: Database in C#, Java, and Golang

Estimated read time 2 min read

Below are examples of connecting to a simple in-memory database in C#, Java, and Golang. In a real-world scenario, you would replace the in-memory database with a proper database system such as SQL Server, MySQL, or MongoDB, and use appropriate libraries or drivers for database interaction.

C# Database Connection:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Data Source=(LocalDb)\\MSSQLLocalDB;Initial Catalog=SampleDB;Integrated Security=True";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            // Perform database operations here

            Console.WriteLine("Connected to the database in C#");
        }
    }
}

Java Database Connection:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DatabaseConnectionExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/sampledb";
        String username = "root";
        String password = "password";

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            // Perform database operations here

            System.out.println("Connected to the database in Java");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

Golang (Go) Database Connection:

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/mattn/go-sqlite3"
)

func main() {
    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        fmt.Println("Error opening database:", err)
        return
    }
    defer db.Close()

    // Perform database operations here

    fmt.Println("Connected to the database in Golang")
}

These examples demonstrate connecting to a database using C#, Java, and Golang. Remember to replace the sample connection strings and details with the actual connection details of your chosen database system. Additionally, consider using proper error handling and closing database connections in a production environment.

Related Articles