Junior — Middle
How is data copying between database servers performed?
sobes.tech AI
Answer from AI
Copying data between database servers is usually done using replication mechanisms or backup and restore procedures. In replication, one database (master) transmits changes to another database (slave), ensuring data synchronization in real-time or with minimal delay.
In Go, you can use standard database libraries (e.g., database/sql) to perform data queries and insertions between servers. You can also use specialized tools or APIs specific to a DBMS.
An example of simple data copying from one database to another:
import (
"database/sql"
_ "github.com/lib/pq" // PostgreSQL driver
"log"
)
func copyData(srcDB, dstDB *sql.DB) error {
rows, err := srcDB.Query("SELECT id, name FROM users")
if err != nil {
return err
}
defer rows.Close()
tx, err := dstDB.Begin()
if err != nil {
return err
}
stmt, err := tx.Prepare("INSERT INTO users (id, name) VALUES ($1, $2)")
if err != nil {
return err
}
defer stmt.Close()
for rows.Next() {
var id int
var name string
if err := rows.Scan(&id, &name); err != nil {
return err
}
if _, err := stmt.Exec(id, name); err != nil {
return err
}
}
return tx.Commit()
}
For large data volumes and production systems, built-in replication mechanisms of the DBMS or specialized ETL tools are usually used.