php editor Xiaoxin Reading database rows into mapping strings is a common data processing technique. By reading and mapping the row data of the database table into strings, data manipulation and processing can be conveniently performed. This technology is often used in web development to convert database query results into a more readable string format for easy display and use. It not only improves the efficiency of data processing, but also simplifies code logic, making the program more concise and easier to maintain. Reading database rows into mapped strings is an important skill and a must-have for developers.
I want to read the results from a simple sql table as shown below
customer | key |
---|---|
A | 12345 |
B | 6789 |
Now, I want to construct a map[string]string
whose key-value pairs are equal to the row values, like this:
map[a:12345, b:6789]
However, I'm having trouble taking the values out of the query results and dynamically creating key-value pairs. I'll provide a rough outline of the code (the sql connection wasn't the issue, I've figured it out)
import "database/sql" func main() { // some code to connect to mssql... db, _ := sql.open("mssql", connstring) stmt := "select customer, key from tbl" rows, _ := db.query(stmt) defer rows.close() data := make(map[string]string) for rows.next() { // need help here grabbing each row pair and adding them to my map... } }
I'm also willing to try doing this with an empty structure, where the fields become the first column of the result set (dynamically) and the values become the second column of the result set.
You can temporarily store the values in two variables and then store them in the map:
func main() { stmt := "SELECT customer, key from tbl" rows, _ := db.Query(stmt) defer rows.Close() data := make(map[string]string) var ( consumer string key string ) for rows.Next() { if err := rows.Scan(&consumer, &key); err != nil { // Handle err } data[consumer] = key } for k, v := range data { fmt.Println(k, v) } // "A" "12345" // "B" "6789" }
Note that the consumer
and key
variables are allocated outside the loop so we can reuse them. Even if the value is an empty string, the variable will be overwritten on each iteration.
The above is the detailed content of Read database rows into mapped string. For more information, please follow other related articles on the PHP Chinese website!