How to integrate Go WebSocket with a database: Set up a database connection: Use the database/sql package to connect to the database. Storing WebSocket messages to the database: Use the INSERT statement to insert the message into the database. Retrieve WebSocket messages from the database: Use a SELECT statement to retrieve messages from the database.
How Go WebSocket integrates with the database
In WebSocket applications based on Go language, real-time data communication is crucial. To achieve persistence, we need to integrate WebSocket data with the database. This article will guide you how to integrate a database in a Go WebSocket application and provide practical examples.
Set up the database connection
First, you need to set up the connection to the database. Here's how to connect to a MySQL database using Go's database/sql
package:
import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" // MySQL 驱动程序 ) func main() { db, err := sql.Open("mysql", "user:password@tcp(host:port)/database") if err != nil { panic(err) } defer db.Close() // 记得关闭连接 // ... 执行数据库操作 ... }
Store WebSocket messages to the database
To store WebSocket messages To store to the database, you need to use the INSERT
statement. Here is an example:
stmt, err := db.Prepare("INSERT INTO messages (message) VALUES (?)") if err != nil { panic(err) } _, err = stmt.Exec(message) if err != nil { panic(err) }
Retrieving WebSocket messages from the database
To retrieve WebSocket messages from the database, you can use the SELECT
statement. Here is how to retrieve all messages:
rows, err := db.Query("SELECT id, message FROM messages") if err != nil { panic(err) } defer rows.Close() for rows.Next() { var id int var message string err := rows.Scan(&id, &message) if err != nil { panic(err) } fmt.Printf("Message ID: %d, Message: %s\n", id, message) }
Actual Case: Live Chat Application
Here is a practical example of how to use WebSocket to integrate with MySQL database in a live chat application:
In this way, you can build a chat application that allows real-time messaging.
The above is the detailed content of How does Go WebSocket integrate with databases?. For more information, please follow other related articles on the PHP Chinese website!