freetds c demo

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h>  

#include <sybfront.h> //freetds头文件 
#include <sybdb.h> //freetds 


int main(int argc, char* argv[]) 
{ 
    char szUsername[32] = "sa"; 
    char szPassword[32] = "****"; 
    char szDBName[32] = "******"; //数据库名 
    char szServer[32] = "192.168.1.254:1433";//数据库服务器:端口 

    //初始化db-library 
    dbinit(); 

    //连接数据库 
    LOGINREC *loginrec = dblogin(); 
    DBSETLUSER(loginrec, szUsername);        
    DBSETLPWD(loginrec, szPassword); 
    DBPROCESS *dbprocess = dbopen(loginrec, szServer);//连接数据库 
    if(dbprocess == FAIL) 
    { 
        printf("Conect to MS SQL SERVER fail, exit!\n"); 
        return -1;  
    } 
    printf("Connect to MS SQL SERVER success!\n"); 

    if(dbuse(dbprocess, szDBName) == FAIL) 
        printf("Open database failed!\n"); 
    else 
        printf("Open database success!\n"); 

    //查询数据库 
    printf("[查询数据库表]\n"); 
    dbcmd(dbprocess, "SELECT TOP 50 [medi_id], [medi_date_from] FROM [******].[dbo].[******]"); 
    if(dbsqlexec(dbprocess) == FAIL) 
    { 
        printf("Query table 'StuInfo' error.\n"); 
        return -1;  
    } 

    DBINT result_code;  
    char szStuID[12];
    char szName[27]; 
    char t1[12];
    char t2[27];
    
    memset(szStuID, 0, sizeof(szStuID));
    memset(szName, 0, sizeof(szName));
    while ((result_code = dbresults(dbprocess)) != NO_MORE_RESULTS){ 
        if (result_code == SUCCEED){ 
            dbbind(dbprocess, 1, CHARBIND, (DBINT)0, (BYTE*)szStuID); 
            dbbind(dbprocess, 2, CHARBIND, (DBCHAR)0, (BYTE*)szName); 
            printf("StuID\tName\n", szStuID); 
            while (dbnextrow(dbprocess) != NO_MORE_ROWS){ 
               memset(t1, 0, sizeof(t1));
               memset(t2, 0, sizeof(t2));
               sprintf(t1, "%s", szStuID); 
               sprintf(t2, "%s", szName); 
               printf("%s\t",t1);
               printf("%d\t%d\t%s\n", strlen(szName),strlen(t2),t2); 
               memset(szStuID, 0, sizeof(szStuID));
               memset(szName, 0, sizeof(szName));
            } 
        } 
    }
 /*    
        printf("[update数据到数据库表]\n"); 
        dbcmd(dbprocess, "UPDATE [*****].[dbo].[******] SET [inf_dia_name1] = '一二三四五六七八九十' where [inf_dia_id] = 1"); 
        if(dbsqlexec(dbprocess) == FAIL) 
        { 
            printf("UPDATE  error.\n"); 
            return -1;  
        } 
        printf("UPDATE  success.\n"); 
          
        printf("[删除数据库表中的记录]\n"); 
        dbcmd(dbprocess, "delete from StuInfo where StuID=888"); 
        if(dbsqlexec(dbprocess) == FAIL) 
        { 
            printf("delete from table 'StuInfo' error.\n"); 
            return -1;  
        } 
        printf("delete from table 'StuInfo' success.\n"); 
  */       
        //关闭数据库连接 
    dbclose(dbprocess); 
    return 0; 
} 

Leave a Reply