How to connect to and interact with databases (e.g., MySQL, PostgreSQL) in Go?

To connect to and interact with databases like MySQL and PostgreSQL in Go, you can use database/sql package along with respective database drivers. Here's a step-by-step approach to connecting and interacting with databases:

  1. Install the necessary database driver: You need to install the driver specific to the database you want to connect with. For example, for MySQL, you can use the "go-sql-driver/mysql" package:

    go get -u github.com/go-sql-driver/mysql

    Similarly, for PostgreSQL, you can use the "github.com/lib/pq" package:

    go get -u github.com/lib/pq
  2. Import the necessary packages: Import the required packages in your Go program:

    import ( "database/sql" _ "github.com/go-sql-driver/mysql" // for MySQL _ "github.com/lib/pq" // for PostgreSQL )
  3. Open a connection to the database: Use the Open() function from database/sql package to create a connection to the database:

    // For MySQL: db, err := sql.Open("mysql", "user:password@tcp(hostname:port)/database_name") // For PostgreSQL: db, err := sql.Open("postgres", "host=hostname port=port_number user=user_name password=password dbname=database_name sslmode=disable")

    Make sure to replace the placeholders with the actual values specific to your database setup.

  4. Check for connection errors: Ensure that the connection to the database is established without any errors:

    if err != nil { log.Fatal(err) }
  5. Close the connection when no longer needed: Defer closing the database connection to avoid resource leaks:

    defer db.Close()
  6. Perform database operations: You can use various functions provided by the "database/sql" package to perform operations like querying, inserting, updating, and deleting data. Here's an example of querying data:

    rows, err := db.Query("SELECT * FROM table_name") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var col1 string var col2 int err := rows.Scan(&col1, &col2) if err != nil { log.Fatal(err) } // Do something with the retrieved data }

    Adjust the SQL query as per your requirements and handle errors appropriately.

Remember to handle errors appropriately, close connections, and use placeholders or prepared statements to avoid SQL injection attacks.