300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > vc访问远程mysql_vc实现对远程SQL Server数据库的访问

vc访问远程mysql_vc实现对远程SQL Server数据库的访问

时间:2019-05-06 21:57:59

相关推荐

vc访问远程mysql_vc实现对远程SQL Server数据库的访问

1、远程数据库

设远程数据库的ip地址为192.168.0.1,其中testdb数据库中有student表,student表包含两列:name和age。name为char类型,长度为10;age为int类型,长度为4。

2、源代码

HENV hEnv = NULL; // Env Handle from SQLAllocEnv()

HDBC hDBC = NULL; // Connection handle

RETCODE retcode;

// Allocate memory for ODBC Environment handle

SQLAllocEnv (&hEnv);

// Allocate memory for the connection handle

SQLAllocConnect (hEnv, &hDBC);

// Connect to the data source "test" using userid and password.

SQLCHAR szConnect[] = "DRIVER={SQL Server};SERVER=192.168.0.1;UID=sa;PWD=Goncely;DATABASE=testdb";

SQLCHAR szOutConn[1024];

SQLSMALLINT n(0);

retcode = SQLDriverConnect(hDBC, m_hWnd, szConnect, strlen((char*)szConnect),

szOutConn, 1024, &n, SQL_DRIVER_NOPROMPT);

if (retcode == SQL_SUCCESS || SQL_SUCCESS_WITH_INFO)

{

TRACE("connect to sql server success/n");

HSTMT hStmt = NULL;// Statement handle

// Allocate memory for the statement handle

retcode = SQLAllocStmt (hDBC, &hStmt);

UCHAR szSqlStr[128]= "SELECT * from student" ;

// Prepare the SQL statement by assigning it to the statement handle

retcode = SQLPrepare (hStmt, szSqlStr, sizeof (szSqlStr));

// Execute the SQL statement handle

retcode = SQLExecute (hStmt);

SQLSMALLINT ColumnCount(0);

retcode = SQLNumResultCols(hStmt, &ColumnCount);

TRACE("total %d cols in db./n", ColumnCount);

char name[11];

int age;

SQLINTEGER StrLen_or_Ind;

retcode = SQLBindCol(hStmt, 1, SQL_C_CHAR, name, 24, &StrLen_or_Ind);

retcode = SQLBindCol(hStmt, 2, SQL_C_SLONG, &age, 0, &StrLen_or_Ind);

do

{

retcode = SQLFetch(hStmt);

TRACE("name: %s, age: %d./n", name, age);

}

while(retcode == SQL_SUCCESS);

// Free the allocated statement handle

SQLFreeStmt (hStmt, SQL_DROP);

// Disconnect from datasource

SQLDisconnect(hDBC);

}

else if(/*retcode == SQL_SUCCESS_WITH_INFO ||*/ retcode == SQL_ERROR)

{

TRACE("ai/n");

SQLCHAR Sqlstate[6], MessageText[1024];

SQLINTEGER NativeError;

SQLSMALLINT TextLength;

SQLGetDiagRec(SQL_HANDLE_DBC, hDBC, 1, Sqlstate, &NativeError,

MessageText, 1024, &TextLength);

TRACE("%s/n", MessageText);

}

else

{

TRACE("failed for others/n");

}

// Free the allocated connection handle

SQLFreeConnect(hDBC);

// Free the allocated ODBC environment handle

SQLFreeEnv(hEnv);

3、代码分析

代码以sa账号建立到192.168.0.1服务器中testdb数据库的连接。远程连接的关键函数为SQLDriverConnect,函数的最后一个参数使用了SQL_DRIVER_NOPROMPT,如果将参数改为SQL_DRIVER_PROMPT,则每当此函数被调用后,会弹出一个数据库访问的配置对话框。此对话框的初始信息由szConnect初始化,用户进行更改后,最后的信息会返回到szOutConn,并以此为参数建立远程连接。对于SQL_DRIVER_NOPROMPT标记,函数直接将szConnect的内容拷贝到szOutConn。

成功建立连接后,上述代码的中间部分顺序读取student表中的内容,并trace输出。最后几行代码用于释放资源。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。