连接数据库
我想在unix下写段c程序,要连接数据库(一个oracle还有一个sybase),主要是做查询,有没有现成的code???
谢谢大家了
------解决方案--------------------下面程序是我做的,主要功能是通过客户端发送的数据操作服务器端的数据库,功能上增删插改都有。如果不需要用fork创建子进程可以去掉这段,socket部分也可以去掉,我做的是对DB2做操作,你要用的话要稍微修改下sql语句就行了。
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/select.h>
#define CURRATE_LIS_PORT 11110
#define MAXCOMLEN 1024
EXEC SQL INCLUDE SQLCA;
main()
{
int forkId;
if ((forkId = fork ()) == 0) {
signal( SIGHUP, SIG_IGN );
signal( SIGQUIT, SIG_IGN );
signal( SIGINT, SIG_IGN );
signal( SIGCLD, SIG_IGN );
setpgrp();
NetServer (CURRATE_LIS_PORT);
} else if (forkId > 0) {
exit (0);
} else if (forkId < 0) {
printf( "UUcom: fork() error\n ");
exit (-1);
}
}
int NetServer (int SERV_TCP_PORT)
{
int sockfd,lis_sockfd,clilen,childpid;/*sockfd:数据传输socket;lis_sockfd:监听socket*/
struct sockaddr_in cli_addr,serv_addr;
setpgrp ();
signal (SIGINT,SIG_IGN);
signal (SIGCLD,SIG_IGN);
/*
* Open a TCP socket (an Internet Stream socket).
*/
if ((lis_sockfd = socket (AF_INET,SOCK_STREAM,0)) <0)
{
printf( "NetServer: can 't open stream socket\n ");
return (-1);
}
/*
* Bind our local address so that the client cna send to us.
*/
memset ((char *)&serv_addr,0,sizeof (serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl (INADDR_ANY);
serv_addr.sin_port = htons (SERV_TCP_PORT);
if (bind (lis_sockfd, (struct sockaddr *)&serv_addr,sizeof (serv_addr )) <0)
{
perror( "NetServer: can 't bind local address\n ");
return (-1);
}
listen (lis_sockfd, 5);
for (;;)
{
clilen = sizeof (cli_addr);
sockfd = accept (lis_sockfd, (struct sockaddr *)&cli_addr,&clilen);
if (sockfd < 0 )
{
perror( "NetServer: can 't accept connect\n ");
return (-1);
}
if (send(sockfd, "Hello,you are connected!\n ",26,0)==-1)
perror( "send出错! ");
if ((childpid = fork ()) <0)
{
perror( "NetServer: can 't fork\n ");
return (-1);
}
else if (childpid == 0)
{
/* Child process */
close (lis_sockfd);
Con_Access (sockfd);
exit (0);
}
close (sockfd);
}
}
Con_Access(int sockfd) /*处理接受的信息*/
{
/*********************定义变量**********************/
int funReturn,sendBuffLen,ret=0;
char rcvBuff[ MAXCOMLEN + 1 ];
char sendBuff[MAXCOMLEN + 1 ];
int i,j,k;
char idstr[4];
char namestr[20];
char phonestr[20];
memset(idstr,0,sizeof(idstr));
memset(namestr,0,sizeof(namestr));
memset(phonestr,0,sizeof(phonestr));
/*************初始化接收缓存和发送缓存区*************/
memset( rcvBuff, 0, sizeof( rcvBuff ) );
memset(sendBuff,0