连接到 SQL Server






3.76/5 (13投票s)
本文档解释了如何连接到 SQL Server 并传递一个字符串。
引言
本文档解释了如何连接到 SQL Server 数据库,然后使用 SQL 语句将字符串写入数据库表。
设置数据库
请您的 DBA(数据库管理员)执行以下操作:
- 创建一个名为 test 的表。
- 提供一个用户名和密码以连接到该数据库。
- 获取服务器名称。
设置 DSN(数据源名称)
您需要创建一个数据源名称,该名称标识您需要连接的服务器和表。
按照以下步骤设置 DSN:
- 转到 控制面板/管理工具/数据源(ODBC)。
- 在 用户 DSN 选项卡中,单击 添加。 在出现的列表中,选择 SQL Server 并单击 完成。
- 在弹出的 DSN 配置向导的第一步中,为您的 DSN 提供任何您想要的名称。
- 选择数据库所在的服务器,单击 下一步。
- 选择使用登录 ID 和密码进行 SQL Server 身份验证的单选按钮。
- 在客户端配置命令按钮中,选择 TCP/IP。
- 选中“连接到 SQL Server 以获取默认设置”复选框,以获取其他配置选项。
- 提供您的 DBA 提供的用户名和密码,单击 下一步。
- 选中“将默认数据库更改为”复选框,并输入您的表名。
- 接受默认值并执行测试连接。
包含
- windows.h
- sqlext.h
- stdio.h
- string.h
编写代码
打开一个名为 SQLtry 的空 Win32 控制台应用程序,添加一个新的 CPP 文件 Main。 您的 Main.cpp 如下所示:
int main(void)
{
   HENV   hEnv = NULL; // Env Handle from SQLAllocEnv()
   HDBC   hDBC = NULL; // Connection handle
   HSTMT  hStmt = NULL;// Statement handle
   UCHAR  szDSN[SQL_MAX_DSN_LENGTH] = "Test";// Data Source Name buffer
   UCHAR  szUID[10] = "test";// User ID buffer
   UCHAR  szPasswd[10] = "test";// Password buffer
   UCHAR  szModel[128];// Model buffer
   SDWORD cbModel;// Model buffer bytes recieved
   char   buff[9] = "Testing";
   UCHAR  szSqlStr[128]= "INSERT into (Tablename) (ColumnName) Values ('Testing')" ;
   RETCODE retcode;
  //sprintf((char*)szSqlStr,"INSERT into (Tablename)(Columname) Values ('%s')",buff);
  // 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.
  retcode = SQLConnect (hDBC, szDSN, SQL_NTS, szUID, SQL_NTS, szPasswd, SQL_NTS);
  if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)
  {
      // Allocate memory for the statement handle
      retcode = SQLAllocStmt (hDBC, &hStmt);  
      // 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);    
      // Project only column 1 which is the models
      SQLBindCol (hStmt, 1, SQL_C_CHAR, szModel, sizeof(szModel), &cbModel);
      // Get row of data from the result set defined above in the statement
      retcode = SQLFetch (hStmt);
      // Free the allocated statement handle
      SQLFreeStmt (hStmt, SQL_DROP);
      // Disconnect from datasource
      SQLDisconnect (hDBC);
  }    
            
  // Free the allocated connection handle
  SQLFreeConnect (hDBC);  
  // Free the allocated ODBC environment handle
  SQLFreeEnv (hEnv);
  return 0;
}
测试您的代码
执行以下步骤:
- 打开一个新的数据库项目。
- 当向导弹出时,执行与设置 DSN 相同的步骤。
- 单击您的表,并通过工具栏运行默认 SQL 语句。
- 您将在表中找到您在上述程序中发送的字符串。
就是这样
如有任何疑问/建议,请与我联系。


