Go

database/sql

database/sql, connections, queries, prepared statements, transactions, connection pooling

22 면접 질문·
Mid-Level
1

What is the main difference between DB.Query and DB.Exec?

답변

DB.Query is used to execute SELECT queries that return rows of data, while DB.Exec is for executing SQL commands that don't return results (INSERT, UPDATE, DELETE). Query returns a Rows object that must be iterated and closed with rows.Close(), whereas Exec returns a Result containing the number of affected rows and the last inserted ID.

2

Why is it important to close the Rows object after a query?

답변

Closing Rows with rows.Close() releases the database connection resources, allowing the connection to return to the pool. Without closing, connections remain occupied and the pool can be exhausted, causing blockages. It's recommended to use defer rows.Close() immediately after checking the Query error to guarantee closure even if a subsequent error occurs.

3

Which method should be used to retrieve a single row of results?

답변

DB.QueryRow is specifically designed to retrieve a single row and returns a Row object (singular). Unlike Query which returns Rows and requires iteration with rows.Next(), QueryRow simplifies the code by allowing direct scanning. Error handling occurs during Scan, where sql.ErrNoRows indicates that no row was found.

4

How to open a connection to a database with database/sql?

5

What does the rows.Scan() method return?

+19 면접 질문

다음 면접을 위해 Go을 마스터하세요

모든 질문, flashcards, 기술 테스트, 코드 리뷰 연습, 면접 시뮬레이터에 접근하세요.

무료로 시작하기