Last active
September 9, 2024 00:55
-
-
Save mzhang77/395d471c7d9c8b104a2b52c0caeec92b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"log" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
func executeSQL(db *sql.DB, sql string) sql.Result { | |
result, err := db.Exec(sql) | |
if err != nil { | |
log.Fatal("Error executing query:", err) | |
} | |
return result | |
} | |
func insertRow(db *sql.DB, a int, b int) int { | |
insertQuery := "INSERT INTO tb (a,b) VALUES (?, ?) ON DUPLICATE KEY UPDATE b = VALUES(b)" | |
result, err := db.Exec(insertQuery, a, b) | |
if err != nil { | |
log.Fatal("Error executing insert query:", err) | |
} | |
// Get the last inserted ID | |
lastInsertId, err := result.LastInsertId() | |
if err != nil { | |
log.Fatalf("Error fetching LastInsertId: %v", err) | |
} | |
return int(lastInsertId) | |
} | |
func main() { | |
// Define the MySQL connection string | |
dsn := "root@tcp(127.0.0.1:4000)/test" | |
// Open a connection to the database | |
db, err := sql.Open("mysql", dsn) | |
if err != nil { | |
log.Fatalf("Error opening database connection: %v", err) | |
} | |
defer db.Close() | |
// Test the connection | |
err = db.Ping() | |
if err != nil { | |
log.Fatalf("Error connecting to the database: %v", err) | |
} | |
_ = executeSQL(db, "drop table if exists tb") | |
_ = executeSQL(db, "create table tb(a int primary key auto_increment, b int)") | |
lastInsertId := insertRow(db, 1, 1) | |
fmt.Printf("Last inserted ID: %d\n", lastInsertId) | |
lastInsertId = insertRow(db, 2, 2) | |
fmt.Printf("Last inserted ID: %d\n", lastInsertId) | |
lastInsertId = insertRow(db, 1, 2) | |
fmt.Printf("Last inserted ID: %d\n", lastInsertId) | |
} | |
Result: | |
Last inserted ID: 1 | |
Last inserted ID: 2 | |
Last inserted ID: 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment