방법: Geography 열에 행 삽입(ODBC)
이 예제는 두 개의 다른 바인딩(SQLCCHAR 및 SQLCBINARY)을 사용하는 WKB(WellKnownBinary)에서 가져온 두 개의 행을 geography 열이 포함된 테이블에 삽입합니다. 그런 다음 이 테이블에서 한 행을 선택하고 ::STAsText()를 사용하여 행을 표시합니다. WKB는 0x01010000000700ECFAD03A4C4001008000B5DF07C0이며 응용 프로그램은 POINT(56.4595 -2.9842)라는 결과를 콘솔로 출력합니다.
이 예제는 ODBC 데이터 원본을 필요로 하지는 않지만 기본적으로 SQL Server의 로컬 인스턴스에서 실행됩니다.
SQL Server 2008 이전 버전의 SQL Server에서는 이 예제를 사용할 수 없습니다.
공간 저장소에 대한 자세한 내용은 공간 데이터(SQL Server)을 참조하십시오.
예
첫 번째(Transact-SQL) 코드 목록은 이 예제에서 사용하는 테이블을 만듭니다.
odbc32.lib 및 user32.lib를 사용하여 두 번째(C++) 코드 목록을 컴파일합니다. INCLUDE 환경 변수에 sqlncli.h가 들어 있는 디렉터리를 포함해야 합니다.
이 예제를 64비트 운영 체제에서 32비트 응용 프로그램으로 작성하여 실행하려는 경우 %windir%\SysWOW64\odbcad32.exe에서 ODBC 관리자를 사용하여 ODBC 데이터 원본을 만들어야 합니다.
이 예제는 컴퓨터의 기본 SQL Server 인스턴스에 연결됩니다. 명명된 인스턴스에 연결하려면 ODBC 데이터 원본의 정의를 변경하여 server\namedinstance 형식으로 인스턴스를 지정합니다. 기본적으로 SQL Server Express는 명명된 인스턴스에 설치됩니다.
세 번째(Transact-SQL) 코드 목록은 이 예제에서 사용하는 테이블을 삭제합니다.
use tempdb
GO
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'SpatialSample')
DROP TABLE SpatialSample
CREATE TABLE SpatialSample (Name varchar(10), Geog Geography)
GO
// compile with: odbc32.lib user32.lib
#include <windows.h>
#include <Sqlext.h>
#include <mbstring.h>
#include "sqlncli.h"
#include <string.h>
#include <stdio.h>
#define MAX_DATA 1024
#define MYSQLSUCCESS(rc) ( (rc == SQL_SUCCESS) || (rc == SQL_SUCCESS_WITH_INFO) )
SQLCHAR szDSN[] = "Driver={SQL Server Native Client 10.0};Server=.;Database=tempdb;Trusted_Connection=Yes;";
class direxec {
RETCODE rc; // ODBC return code
HENV henv; // Environment
HDBC hdbc; // Connection Handle
HSTMT hstmt; // Statement Handle
SQLHDESC hdesc; // Descriptor handle
SQLCHAR szData[MAX_DATA]; // Returned Data Storage
SDWORD cbData; // Output Lenght of data
SQLCHAR szConnStrOut[MAX_DATA + 1];
SWORD swStrLen;
public:
void sqlconn(); // Allocate env, stat and conn
void sqldisconn(); // Free pointers to env, stat, conn and disconnect
void error_out(); // Display errors
void check_rc(RETCODE rc); // Checks for success of the return code
void SqlInsertFromChar(); // Insert a WKB in character form
void SqlInsertFromBinary(); // Insert a WKB in binary form
void SqlSelectGeogAsText(); // Retrieve the geography as Text.
};
// Allocate environment handles, connection handle, connect to data source, and allocate statement handle
void direxec::sqlconn() {
// Allocate the enviroment handle
rc = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
check_rc(rc);
// Set the ODBC version to version 3
rc = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER);
check_rc(rc);
// Allocate the database connection handle
rc = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
check_rc(rc);
// Connect to the database
rc = SQLDriverConnect(hdbc, NULL, szDSN, SQL_NTS, szConnStrOut, MAX_DATA, &swStrLen, SQL_DRIVER_NOPROMPT);
check_rc(rc);
// Allocate the statement handle
rc = SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
check_rc(rc);
// Allocate the descriptor handle
rc = rc = SQLAllocHandle(SQL_HANDLE_DESC, hdbc, &hdesc);
check_rc(rc);
}
// Display error message from the DiagRecord
void direxec::error_out() {
// String to hold the SQL State
SQLCHAR szSQLSTATE[10];
// Error code
SDWORD nErr;
// The error message
SQLCHAR msg[SQL_MAX_MESSAGE_LENGTH + 1];
// Size of the message
SWORD cbmsg;
// If hstmt is not null use that for getting the DiagRec
if (hstmt)
rc = SQLGetDiagRec(SQL_HANDLE_STMT, hstmt, 1, szSQLSTATE, &nErr, msg, sizeof(msg), &cbmsg);
// else get the diag record from the env
else
rc = SQLGetDiagRec(SQL_HANDLE_ENV, henv, 1, szSQLSTATE, &nErr, msg, sizeof(msg), &cbmsg);
// If the rc is successful, show the message using a message box
if ( rc == SQL_SUCCESS) {
printf((char *)szData, "Error:\nSQLSTATE=%s,Native error=%ld, msg='%s'", szSQLSTATE, nErr, msg);
MessageBox(NULL, (const char *)szData, "ODBC Error", MB_OK);
}
}
// Checks the return code. If failure, displays the error, free the memory and exits the program
void direxec::check_rc(RETCODE rc) {
if (!MYSQLSUCCESS(rc)) {
error_out();
SQLFreeEnv(henv);
SQLFreeConnect(hdbc);
exit(-1);
}
}
void direxec::SqlInsertFromBinary() {
rc = SQLPrepare(hstmt, (SQLCHAR*) "INSERT INTO SpatialSample(Name,Geog) values('Sample1',Geography::STGeomFromWKB(?,4326))", SQL_NTS);
check_rc(rc);
SQLCHAR szBytes [] = "\x01\x01\x00\x00\x00\x07\x00\xEC\xFA\xD0\x3A\x4C\x40\x01\x00\x80\x00\xB5\xDF\x07\xC0";
SQLLEN iDataLength = sizeof(szBytes)-1;
rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_VARBINARY, 100, 0, szBytes, sizeof(szBytes), &iDataLength);
check_rc(rc);
rc = SQLExecute(hstmt);
check_rc(rc);
}
void direxec::SqlInsertFromChar() {
rc = SQLPrepare(hstmt, (SQLCHAR*) "INSERT INTO SpatialSample(Name,Geog) values('Sample2',Geography::STGeomFromWKB(?,4326))", SQL_NTS);
check_rc(rc);
SQLCHAR szBytes [] = "01010000000700ECFAD03A4C4001008000B5DF07C0";
rc = SQLBindParameter(hstmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARBINARY, 100, 0, szBytes, sizeof(szBytes), NULL);
check_rc(rc);
rc = SQLExecute(hstmt);
check_rc(rc);
}
void direxec::SqlSelectGeogAsText() {
rc = SQLFreeStmt(hstmt, SQL_CLOSE);
check_rc(rc);
rc = SQLExecDirect(hstmt, (SQLCHAR*) "SELECT geog.STAsText() FROM SpatialSample", SQL_NTS);
check_rc(rc);
SQLCHAR rgcAsText[MAX_DATA];
SQLLEN cbAsText;
rc = SQLBindCol(hstmt, 1, SQL_C_CHAR, rgcAsText, sizeof(rgcAsText), &cbAsText);
check_rc(rc);
rc = SQLFetch(hstmt);
check_rc(rc);
rgcAsText[cbAsText] = '\0';
printf("%s\r\n", (LPSTR)rgcAsText);
}
int main() {
direxec x;
// Allocate handles, and connect.
x.sqlconn();
// Insert 2 samples into the table
x.SqlInsertFromChar();
x.SqlInsertFromBinary();
// Select 1 row from the table and display the geography as text
x.SqlSelectGeogAsText();
}
use tempdb
GO
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'SpatialSample')
DROP TABLE SpatialSample
GO