Linux下通过freetds连接MSSQL数据库

1       概述
在linux下连接MSSQL是一件很痛苦的事,因为微软同志没有提供任何接口给开发人员,还好,MSSQL是从Sybase衍生出来的,FreeTDS是一个数据库底层的驱动程序,用freetds的库进行开发是一件很方便的事。freetds可以连接sybase和ms sql server数据库。
2       安装,配置,测试
官方网站:http://www.freetds.org
版本:0.64
$ tar -zxvf freetds-stable.tgz
$ ./configure --prefix=/usr/local/freetds
$ make
$ su root
$ make install
$ tsql -H 2.2.2.2 -p 1433 -U test -P test
tsql 说明:
    H :数据库IP
    p: 数据库端口
    U :用户名
    P :密码
3       linux下C/C++开发
3.1    利用freetds自带的程序开发
位置在freetds-0.64/src/ apps
$make clean
$make
3.2    利用freetds库快速开发
testsybase.c
 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
 
#include <sybfront.h>
#include <sybdb.h>
 
 
 
int main(void)
{
       char szUsername[32] = "test";
       char szPassword[32] = "test";
       char szDBName[32] = "test";
       char szServer[32] = "2.2.2.2:1433";
 
       //初始化db-library
       dbinit();
       //连接数据库
       LOGINREC *loginrec = dblogin();
       DBSETLUSER(loginrec, szUsername);      
       DBSETLPWD(loginrec, szPassword);
       DBPROCESS *dbprocess = dbopen(loginrec, szServer);
       if(dbprocess == FAIL){
              printf("ASB>>      Conect MS SQL SERVER fail       /n");
              return 0;
       }else{
              printf("ASB>>      ConnectEMS conect MS SQL SERVER success/n");
       }
       if(dbuse(dbprocess, szDBName) == FAIL){
              printf("ASB>>      Open database name fail/n");
       }else{
              printf("ASB>>      Open database name success/n");
       }
      
       //查询数据库
       dbcmd(dbprocess, "select ID,BeginTime,Description from Alarms");
       if(dbsqlexec(dbprocess) == FAIL){
              printf("ASB>>      Query Alarms table error/n");    
       }
      
       DBINT result_code;
       char szID[1024];
       char szBeginTime[1024];
       char szDescription[1024];
       int rows = 0;
       while ((result_code = dbresults(dbprocess)) != NO_MORE_RESULTS){
              if (result_code == SUCCEED){
                     dbbind(dbprocess, 1, CHARBIND, (DBINT)0, (BYTE*)szID);
                     dbbind(dbprocess, 2, CHARBIND, (DBCHAR)0, (BYTE*)szBeginTime);
                     dbbind(dbprocess, 3, CHARBIND, (DBCHAR)0, (BYTE*)szDescription);
                     while (dbnextrow(dbprocess) != NO_MORE_ROWS){                       
                            printf("ASB>>             ID=%s/n", szID);
                            printf("ASB>>             szAid=%s/n", szBeginTime);
                            printf("ASB>>             szBeginTime=%s/n", szDescription);
                     }
              }
       }
       //关闭数据库连接
       dbclose(dbprocess);
      
       return 0;
}
 
编译: gcc -o testsybase testsybase.c ./src/dblib/.libs/libsybdb.a
 

你可能感兴趣的:(Linux下通过freetds连接MSSQL数据库)