Samchon Framework for CPP  1.0.0
SQLi.cpp
1 #include <samchon/library/SQLi.hpp>
2 
3 #ifndef WIN32_LEAN_AND_MEAN
4 # define WIN32_LEAN_AND_MEAN
5 #endif
6 
7 #include <Windows.h>
8 #include <sqltypes.h>
9 #include <sql.h>
10 #include <sqlext.h>
11 
12 #include <iostream>
13 #include <memory>
14 #include <mutex>
15 
16 #include <samchon/library/SQLStatement.hpp>
17 #include <samchon/library/StringUtil.hpp>
18 
19 using namespace std;
20 using namespace samchon;
21 using namespace samchon::library;
22 
23 SQLi::SQLi(const std::string &driver, int port)
24 {
25  stmt = nullptr;
26 
27  this->driver = driver;
28  this->port = port;
29 }
30 SQLi::~SQLi()
31 {
32  disconnect();
33 }
34 
35 auto SQLi::createStatement() -> shared_ptr<SQLStatement>
36 {
37  return shared_ptr<SQLStatement>(new SQLStatement(this));
38 };
39 
40 void SQLi::connect(const std::string &ip, const std::string &db, const std::string &id, const std::string &pwd)
41 {
42  unique_lock<mutex> uk(stmtMutex);
43  SQLRETURN res;
44  SQLHANDLE environment;
45 
46  if ((res = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &environment)) == SQL_SUCCESS)
47  if ((res = SQLSetEnvAttr(environment, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0)) == SQL_SUCCESS)
48  if ((res = SQLAllocHandle(SQL_HANDLE_DBC, environment, &hdbc)) == SQL_SUCCESS)
49  {
50  res =
51  SQLDriverConnectA
52  (
53  hdbc, NULL,
54  (SQLCHAR*)&StringUtil::substitute
55  (
56  "DRIVER={0};SERVER={1}, {2};DATABASE={3};UID={4};PWD={5};",
57  driver, ip, port, db, id, pwd
58  )[0],
59  SQL_NTS, NULL, 1024, NULL, SQL_DRIVER_NOPROMPT
60  );
61  }
62 
63  SQLFreeHandle(SQL_HANDLE_DBC, environment);
64 
65  if (res != SQL_SUCCESS && res != SQL_SUCCESS_WITH_INFO)
66  {
67  disconnect();
68  throw exception(getErrorMessage(SQL_HANDLE_DBC).c_str());
69  }
70 }
71 void SQLi::disconnect()
72 {
73  if (stmt != nullptr)
74  stmt->free();
75 
76  //FOR STATIC DESTRUCTION
77  stmtMutex.lock();
78  SQLDisconnect(hdbc);
79  SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
80  stmtMutex.unlock();
81 }
82 
83 auto SQLi::getErrorMessage(short type) const -> string
84 {
85  char state[1024];
86  char message[1024];
87 
88  if (SQLGetDiagRecA(type, hdbc, 1, (SQLCHAR *)state, NULL, (SQLCHAR *)message, 1024, NULL) == SQL_SUCCESS)
89  return string("SQLSTATE: ") + state + "\nMESSAGE: " + message;
90  else
91  return "Unknown";
92 }
Definition: RWMutex.hpp:4
Package of libraries.
Definition: library.hpp:84
Top level namespace of products built from samchon.
Definition: ByteArray.hpp:7