Database creation through ODBC

How to create a new database using the MFC ODBC API

In the connection string, you must specify the name of the database to which you want to connect. What if I have just installed SQL Server that does not contain user databases?

What database name do you specify in the connection string?

eg. for SQL Server:

    CDatabase db;

    db.OpenEx(L"Driver={ODBC Driver 11 for SQL Server};Server=myServerAddress;"
              L"Database=????????;Uid=myUsername;Pwd=myPassword", CDatabase::noOdbcDialog);

    db.ExecuteSQL(L"CREATE DATABASE testdb");

Should I use system databases (e.g. wizard, model, etc.)? Is there another general approach?

+4
source share
1 answer

Database= . , USE.

- :

SQLWCHAR     strConnect[256] = L"Driver={SQL Server};Server=.\\MACHINE;Trusted_Connection=yes;";
SQLWCHAR     strConnectOut[1024] = { 0 };
SQLSMALLINT nNumOut = 0;
SQLRETURN nResult = SQLDriverConnect(handleDBC, NULL, (SQLWCHAR*)strConnect, SQL_NTS, (SQLWCHAR*)strConnectOut, sizeof(strConnectOut), &nNumOut, SQL_DRIVER_NOPROMPT);
if (!SQL_SUCCEEDED(nResult))
    // some error handling

SQLHSTMT    handleStatement = SQL_NULL_HSTMT;
nResult = SQLAllocHandle(SQL_HANDLE_STMT, handleDBC, (SQLHANDLE*)&handleStatement);
if (!SQL_SUCCEEDED(nResult))
    // some error handling

// Create a new database and use that
nResult = SQLExecDirect(handleStatement, L"CREATE DATABASE Foobar", SQL_NTS);
nResult = SQLExecDirect(handleStatement, L"USE Foobar", SQL_NTS);

// create table Wallet in database Foobar
nResult = SQLExecDirect(handleStatement, L"CREATE TABLE Wallet (WalletID int NOT NULL,  Name nvarchar(5) NOT NULL)", SQL_NTS);
+3

Source: https://habr.com/ru/post/1667623/


All Articles