首先,俺安装了
freetds-bin【FreeTDS command-line utilities】
freetds-common【configuration files for FreeTDS SQL client libraries】
freetds-dev【MS SQL and Sybase client library (static libs and headers)】
这三样东西,都是用apt-get安装的。
host = 192.168.0.2【SQL Server所在的IP】
port = 1433【或者自己设置的SQL Server端口】
tds version = 8.0【打开SQL Server查看版本号,这个和那个对应】
安装好了之后,首先去修改 Freetds 的配置文件,如果不知道在哪,就用 find / -name freetds 查找相关文件夹,在我的机器上查找到了两处:
/usr/share/freetds
/etc/freetds
然后我修改了
/etc/freetds 文件夹中的
freetds.conf 。
用 vim 打开,在下面加上:
[localhost]【下面这个配置的名字】
这时候,就已经能够在命令行下直接调用了,命令是这样的:
localhost:/etc/freetds# tsql -S localhost【你配置文件里取的名字】 -U 【数据库登录用户】 -P 【登录密码】
命令行显示:【1> 】就对了,可以在后面输入SQL语句,回车是换行,想要执行,则输入【go】之后回车。
下面是简单的C代码示例:
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #include <unistd.h>
-
- #include <sybfront.h> //freetds头文件
- #include <sybdb.h> //freetds
-
-
- int
main(void) - {
-
char szUsername[32] = "sa"; -
char szPassword[32] = "zkl"; -
char szDBName[32] = "test"; //数据库名 -
char szServer[32] = "192.168.232.133: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 StuID, Name, Age from StuInfo"); -
if(dbsqlexec(dbprocess) == FAIL) -
{ -
printf("Query table 'StuInfo' error.\n"); -
return -1; -
} -
-
DBINT result_code; -
char szStuID[20]={}; -
char szName[80]={}; -
char szAge[10]={}; -
int rows = 0; -
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); -
dbbind(dbprocess, 3, CHARBIND, (DBCHAR)0, (BYTE*)szAge); -
printf("StuID\tName\tAge\n", szStuID); -
while (dbnextrow(dbprocess) != NO_MORE_ROWS){ -
printf("%s\t", szStuID); -
printf("%s\t", szName); -
printf("%s\n", szAge); -
} -
} -
} -
-
printf("[插入数据到数据库表]\n"); -
dbcmd(dbprocess, "insert into StuInfo(StuID, Name, Age) values(888,'James',28)"); -
if(dbsqlexec(dbprocess) == FAIL) -
{ -
printf("insert into table 'StuInfo' error.\n"); -
return -1; -
} -
printf("insert into table 'StuInfo' 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; - }
代码写完之后,编译的时候需要链接正确才能通过,整句话是这样的:
gcc -o dbTest dbTest.c -lrt /usr/lib/libsybdb.a 【一定要加入
然后运行程序,看看是不是成功了。