mysql 程序设计遇到的一个问题

忘世麒麟 忘世麒麟 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我按照教材中的例子,编写好了如下三个文件,并且编译通过了,生成了可执行的文件
文件1:common.h

#include <mysql.h>
MYSQL * do_connext(char * host_name,char *user_name,char *password,char *db_name,
unsigned int port_num,char* socket_name,unsigned int flags);
void do_disconnect(MYSQL *conn);


文件2:common.c
#include "common.h"
#include <stdio.h>

MYSQL *do_connect(char *host_name,char *user_name,char*password,char *db_name,
unsigned int port_num,char *socket_name,unsigned int flags)
{
MYSQL *conn;
conn = mysql_init(NULL);
if(conn == NULL)
{
fprintf(stderr,"mysql_init() failed\n");
return NULL;
}
if(mysql_real_connect(conn,host_name,user_name,password,db_name,port_num,socket_name,flags) == NULL)
{
fprintf(stderr,"mysql_real_connect() failed: \n Error %u (%s)\n",mysql_errno(conn),mysql_error(conn));
return NULL;
}
return conn;
}

void do_disconnect(MYSQL *conn)
{
mysql_close(conn);
}

文件3:client.c
#include <stdio.h>
#include <stdlib.h>
#include <mysql.h>
#include "getopt.h"
#include "common.h"

#define def_host_name NULL
#define def_user_name NULL
#define def_password NULL
#define def_port_num 0
#define def_socket_name NULL
#define def_db_name NULL

char *groups[] = {"client",NULL};
struct option long_options[] =
{
{"host",required_argument,NULL,'h'},
{"user",required_argument,NULL,'u'},
{"password",optional_argument,NULL,'p'},
{"port",required_argument,NULL,'P'},
{"socket",required_argument,NULL,'S'},
{0,0,0,0}
};

MYSQL *conn;

int main(int argc,char *argv[])
{
char *host_name = def_host_name;
char *user_name = def_user_name;
char *password = def_password;
unsigned int port_num = def_port_num;
char *socket_name = def_socket_name;
char *db_name = def_db_name;

char passbuf[100];
int ask_password = 0;
int c,option_index = 0;
int i;

my_init();

while((c = getopt_long(argc,argv,"h:p::u:P:S",long_options,&option_index))!=EOF)
{
switch(c)
{
case 'h':
host_name = optarg;
break;
case 'u':
user_name = optarg;
break;
case 'p':
{
if(!optarg)
ask_password = 1;
else
{
(void)strncpy(passbuf,optarg,sizeof(passbuf)-1);
passbuf[sizeof(passbuf)-1] = '\0';
password = passbuf;
while(*optarg)
*optarg++ = ' ';
}
break;
}
case 'P':
port_num = (unsigned int)atoi(optarg);
break;
case 'S':
socket_name = optarg;
break;
}
}

argc -= optind;
argc += optind;

if(argc > 0)
{
db_name = argv[0];
--argc;
++argv;
}

if(ask_password)
password = get_tty_password(NULL);

conn = do_connect(host_name,user_name,password,db_name,port_num,socket_name,0);

if(conn == NULL)
exit(1);
do_disconnect(conn);
exit(0);
}

应该很眼熟吧,那本入门书籍应该很多人看过的。
我在mysql中建立了数据库SAMP_DB
然后我这样执行后弹出如下提示:

请问,我哪里错了,应该怎么样才可以连接到我的数据库
ps:本机的hostname 就是ubutu。
...全文

相关推荐

评论 9
收藏 已收藏
分享
返回顶部
忘世麒麟
MySQL 57,062 成员 56,759 内容