Prepared statement methods (준비된 문장 메서드)
이 문서는 문장을 준비한 뒤, 쿼리를 실행하고 결과를 검색하는 다양한 방법(run, all, first, raw 메서드)을 설명해요.
출처: 문서
본문
이 장에서는 문장을 준비한 뒤 쿼리를 실행하고 그 결과를 검색하는 다양한 방법을 다뤄요.
메서드 (Methods)
bind()
준비된 문장에 매개변수를 바인딩해요.
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
some_variable = "Bs Beverages"
stmt = self.env.DB.prepare(
"SELECT * FROM Customers WHERE CompanyName = ?"
).bind(some_variable)
매개변수 (Parameter)
Variable:string- 준비된 문장에 추가될 변수예요. 아래 안내를 참고하세요.
반환 값 (Return values)
D1PreparedStatement:Object- 입력 매개변수가 문장에 포함된
D1PreparedStatement예요.
- 입력 매개변수가 문장에 포함된
안내 (Guidance)
-
D1은 준비된 문장 매개변수 바인딩에 SQLite 규칙 ↗︎을 따르는 방식으로 개발됐어요. 현재 D1은 순서 지정(Ordered,
?NNNN) 및 익명(Anonymous,?) 매개변수만 지원해요. 향후 D1은 이름 지정(named) 매개변수도 지원할 예정이에요.Syntax Type Description ?NNNOrdered 숫자 NNN이 뒤따르는 물음표는NNN번째 매개변수의 자리를 차지해요.NNN은1과SQLITE_MAX_VARIABLE_NUMBER사이여야 해요?Anonymous 숫자가 뒤따르지 않는 물음표는, 이미 할당된 가장 큰 매개변수 번호보다 1 큰 번호의 매개변수를 만들어요. 그 결과 매개변수 번호가 SQLITE_MAX_VARIABLE_NUMBER보다 크면 오류예요. 이 매개변수 형식은 다른 데이터베이스 엔진과의 호환을 위해 제공돼요. 하지만 물음표 개수를 잘못 세기 쉽기 때문에 이 매개변수 형식의 사용은 권장되지 않아요. 프로그래머는 아래 기호 형식이나 위?NNN형식 중 하나를 사용하는 것이 권장돼요.매개변수를 바인딩하려면
.bind메서드를 사용하세요.순서 및 익명 예시:
const stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind("");stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind("")const stmt = db .prepare("SELECT * FROM Customers WHERE CompanyName = ? AND CustomerId = ?") .bind("Alfreds Futterkiste", 1);stmt = db.prepare( "SELECT * FROM Customers WHERE CompanyName = ? AND CustomerId = ?" ).bind("Alfreds Futterkiste", 1)const stmt = db .prepare( "SELECT * FROM Customers WHERE CompanyName = ?2 AND CustomerId = ?1" ).bind(1, "Alfreds Futterkiste");stmt = db.prepare("SELECT * FROM Customers WHERE CompanyName = ?2 AND CustomerId = ?1").bind(1, "Alfreds Futterkiste")
정적 문장 (Static statements)
D1 API는 정적 문장(static statements)을 지원해요. 정적 문장은 변수가 하드코딩된 SQL 문장이에요. 정적 문장을 작성할 때는 문장 문자열 안에 변수를 수동으로 입력해요.
준비된 문장의 장점 (Advantages of prepared statements)
권장하는 방법은 준비된 문장을 사용해 SQL을 실행하고 매개변수를 바인딩하는 것이에요. bind()를 사용해 준비된 문장에 매개변수를 바인딩하면 코드에서 준비된 문장을 재사용할 수 있고, SQL 인젝션 공격을 막을 수 있어요.
동적으로 바인딩된 값을 가진 준비된 문장 예시:
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
// A variable (someVariable) will replace the placeholder '?' in the query.
// `stmt` is a prepared statement.
some_variable = "Bs Beverages"
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(some_variable)
# A variable (some_variable) will replace the placeholder '?' in the query.
# `stmt` is a prepared statement.
정적 문장 예시:
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'");
// "Bs Beverages" is hard-coded into the query.
// `stmt` is a static statement.
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = 'Bs Beverages'")
# "Bs Beverages" is hard-coded into the query.
# `stmt` is a static statement.
run()
준비된 쿼리(또는 여러 쿼리)를 실행하고 결과를 반환해요. 반환되는 결과에는 메타데이터가 포함돼요.
const returnValue = await stmt.run();
return_value = await stmt.run()
매개변수 (Parameter)
- 없음.
반환 값 (Return values)
D1Result:Object- 성공 상태, meta 객체, 쿼리 결과를 담은 객체 배열을 포함하는 객체예요.
- 이 객체에 대한 자세한 내용은
D1Result를 참고하세요.
반환 값 예시 (Example of return values)
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
const returnValue = await stmt.run();
return Response.json(returnValue);
from workers import Response
some_variable = "Bs Beverages"
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(some_variable)
return_value = await stmt.run()
return Response.json(return_value)
{
"success": true,
"meta": {
"served_by": "miniflare.db",
"duration": 1,
"changes": 0,
"last_row_id": 0,
"changed_db": false,
"size_after": 8192,
"rows_read": 4,
"rows_written": 0
},
"results": [
{
"CustomerId": 11,
"CompanyName": "Bs Beverages",
"ContactName": "Victoria Ashworth"
},
{
"CustomerId": 13,
"CompanyName": "Bs Beverages",
"ContactName": "Random Name"
}
]
}
안내 (Guidance)
UPDATE,DELETE,INSERT같은 쓰기 작업의 경우results는 비어 있어요.- TypeScript를 사용할 때
D1PreparedStatement::run에 타입 매개변수를 전달해 타입이 지정된 결과 객체를 반환받을 수 있어요. D1PreparedStatement::run은 기능적으로D1PreparedStatement::all과 동일하며 별칭(alias)으로 취급할 수 있어요.- 반환 객체의
results속성만 반환해 문장에서 기대하는 결과만 추출할 수도 있어요.
results만 반환하는 예시 (Example of returning only the results)
results만 반환하는 예시 (Example of returning only the results)return Response.json(returnValue.results);
from workers import Response
return Response.json(return_value.results)
[
{
"CustomerId": 11,
"CompanyName": "Bs Beverages",
"ContactName": "Victoria Ashworth"
},
{
"CustomerId": 13,
"CompanyName": "Bs Beverages",
"ContactName": "Random Name"
}
]
raw()
준비된 쿼리(또는 여러 쿼리)를 실행하고, 결과를 배열의 배열(array of arrays)로 반환해요. 반환되는 결과에는 메타데이터가 포함되지 않아요.
열 이름은 기본적으로 결과 집합에 포함되지 않아요. 열 이름을 결과 배열의 첫 번째 행으로 포함하려면 .raw({columnNames: true})로 설정하세요.
const returnValue = await stmt.raw();
return_value = await stmt.raw()
매개변수 (Parameters)
columnNames:Object선택- 열 이름을 결과 배열의 첫 번째 행으로 포함하는 불리언 객체예요.
반환 값 (Return values)
Array:Array- 배열들의 배열이에요. 각 하위 배열은 하나의 행을 나타내요.
반환 값 예시 (Example of return values)
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
const returnValue = await stmt.raw();
return Response.json(returnValue);
from workers import Response
some_variable = "Bs Beverages"
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(some_variable)
return_value = await stmt.raw()
return Response.json(return_value)
[
[11, "Bs Beverages",
"Victoria Ashworth"
],
[13, "Bs Beverages",
"Random Name"
]
]
매개변수 columnNames: true를 사용할 때:
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
const returnValue = await stmt.raw({columnNames:true});
return Response.json(returnValue)
from workers import Response
some_variable = "Bs Beverages"
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(some_variable)
return_value = await stmt.raw(columnNames=True)
return Response.json(return_value)
[
[
"CustomerId",
"CompanyName",
"ContactName"
],
[11, "Bs Beverages",
"Victoria Ashworth"
],
[13, "Bs Beverages",
"Random Name"
]
]
안내 (Guidance)
- TypeScript를 사용할 때
D1PreparedStatement::raw에 타입 매개변수를 전달해 타입이 지정된 결과 배열을 반환받을 수 있어요.
first()
준비된 쿼리(또는 여러 쿼리)를 실행하고, 쿼리 결과의 첫 번째 행을 객체로 반환해요. 메타데이터는 반환하지 않아요. 대신 객체를 직접 반환해요.
const values = await stmt.first();
values = await stmt.first()
매개변수 (Parameters)
columnName:String선택- 쿼리 결과의 첫 번째 행에서 특정 열의 값을 반환하려면
columnName을 지정하세요.
- 쿼리 결과의 첫 번째 행에서 특정 열의 값을 반환하려면
- 없음.
- 첫 번째 행의 모든 열을 얻으려면 매개변수를 전달하지 마세요.
반환 값 (Return values)
firstRow:Object선택- 쿼리 결과의 첫 번째 행을 포함하는 객체예요.
columnName이 지정되면 반환 값이 특정 속성으로 더 필터링돼요.
null:null- 쿼리가 어떤 행도 반환하지 않으면 반환돼요.
반환 값 예시 (Example of return values)
첫 번째 행의 모든 열 가져오기:
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
const returnValue = await stmt.first();
return Response.json(returnValue)
from workers import Response
some_variable = "Bs Beverages"
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(some_variable)
return_value = await stmt.first()
return Response.json(return_value)
{
"CustomerId": 11,
"CompanyName": "Bs Beverages",
"ContactName": "Victoria Ashworth"
}
첫 번째 행에서 특정 열 가져오기:
const someVariable = `Bs Beverages`;
const stmt = env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(someVariable);
const returnValue = await stmt.first("CustomerId");
return Response.json(returnValue)
from workers import Response
some_variable = "Bs Beverages"
stmt = self.env.DB.prepare("SELECT * FROM Customers WHERE CompanyName = ?").bind(some_variable)
return_value = await stmt.first("CustomerId")
return Response.json(return_value)
11
안내 (Guidance)
- 쿼리가 행을 반환하지만
column이 존재하지 않으면D1PreparedStatement::first는D1_ERROR예외를 던져요. D1PreparedStatement::first는 SQL 쿼리를 변경하지 않아요. 성능을 높이려면 문장에LIMIT 1을 추가하는 것을 고려해 보세요.- TypeScript를 사용할 때
D1PreparedStatement::first에 타입 매개변수를 전달해 타입이 지정된 결과 객체를 반환받을 수 있어요.