golang sqlite
Golang is a programming language known for its simplicity, efficiency, and strong support for concurrent programming. SQLite is a lightweight, embedded relational database management system (RDBMS) that is widely used for small-scale applications.
Golang provides a package called "database/sql" that offers a generic interface for working with SQL databases, including SQLite. To use SQLite in Golang, you need to import the "database/sql" package and the SQLite driver. You can install the SQLite driver using the following command:
go get github.com/mattn/go-sqlite3
Once the driver is installed, you can import it in your Go code and use the "database/sql" package to connect to the SQLite database, perform queries, and manage transactions.
Here's an example of how to use SQLite in Golang:
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
// Connect to the SQLite database
db, err := sql.Open("sqlite3", "test.db")
if err != nil {
fmt.Println("Failed to connect to database:", err)
return
}
defer db.Close()
// Create a table
_, err = db.Exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)")
if err != nil {
fmt.Println("Failed to create table:", err)
return
}
// Insert a new record
_, err = db.Exec("INSERT INTO users (name) VALUES (?)", "John Doe")
if err != nil {
fmt.Println("Failed to insert record:", err)
return
}
// Query the database
rows, err := db.Query("SELECT id, name FROM users")
if err != nil {
fmt.Println("Failed to query:", err)
return
}
defer rows.Close()
// Iterate over the query results
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
fmt.Println("Failed to scan row:", err)
return
}
fmt.Println("ID:", id, "Name:", name)
}
// Check for any errors during iteration
err = rows.Err()
if err != nil {
fmt.Println("Error during iteration:", err)
return
}
}
In this example, we connect to a SQLite database file called "test.db", create a table called "users", insert a record into the table, and then query and print the results.
Remember to handle errors appropriately in your code to ensure proper error handling and prevent unexpected behavior.
原文地址: http://www.cveoy.top/t/topic/i6BZ 著作权归作者所有。请勿转载和采集!