#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include<iostream>
#include"sqlite3.h"
using namespace std;
int main() {
//创建套接字
int serv_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//将套接字和IP、端口绑定
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr)); //每个字节都用0填充
serv_addr.sin_family = AF_INET; //使用IPv4地址
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); //具体的IP地址
serv_addr.sin_port = htons(1234); //端口
bind(serv_sock, (struct sockaddr*) & serv_addr, sizeof(serv_addr));
//进入监听状态,等待用户发起请求
listen(serv_sock, 20);
//接收客户端请求
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size = sizeof(clnt_addr);
int clnt_sock = accept(serv_sock, (struct sockaddr*) & clnt_addr, &clnt_addr_size);
//进行信息的查询获取与格式化
char name[40];
read(clnt_sock, name, sizeof(name));
cout << "This is the request url:" << name << endl;
char sql[100] = "select * from records where name = \'";
strcat(sql, name);
char* end = "\'";
strcat(sql, end);
cout << "The sql of select:" << sql << endl;
//数据库查询
sqlite3* db;
char* zErrMsg = 0;
int rc;
const char* data = "Callback function called";
//连接数据库
rc = sqlite3_open("dns.db", &db);
if (rc) {
fprintf(stderr, "Can't open the database:%s\n", sqlite3_errmsg(db));
exit(0);
}
else {
fprintf(stderr, "Opened database successfully\n");
}
//查询数据库
char** pResult;
int nRow;
int nCol;
rc = sqlite3_get_table(db, sql, &pResult, &nRow, &nCol, NULL);
if (rc == SQLITE_OK)
{
cout << "the datas can be used are as follows:\n";
for (int i = 0; i < nCol; i++) {
cout << pResult[nCol + i] << endl;
}
cout << "the key information client want:" << pResult[nCol * 2 - 1] << endl;
}
char ip[40];
strcpy(ip, pResult[nCol * 2 - 1]);
write(clnt_sock, ip, sizeof(ip));
//关闭表与数据库
sqlite3_free_table(pResult);
sqlite3_close(db);
//关闭套接字
close(clnt_sock);
close(serv_sock);
return 0;
}
{
char sql[SQL_QUERY_LEN] = "select * from connect;";
char** pResult;
int nRow;
int nCol;
rc = sqlite3_get_table(db, sql, &pResult, &nRow, &nCol, NULL);
if (rc == SQLITE_OK)
{
cout << "connect,the row = " << nRow << endl;
for (int j = 0; j < nRow; j++) {
for (int i = 0; i < nCol; i++) {
cout << pResult[j * nCol + i] << "\t";
}
cout << endl;
}
}
//关闭表
sqlite3_free_table(pResult);
}
还可以参考这篇博客:https://lion-wu.blog.csdn.net/article/details/106266784