国庆10.5

结合数据库的方式完成用户注册,要求客户端输入账户密码,发送给服务器服务器接收到账户密码后,写入到数据库中不允许重复注册
 

#include 

int do_register(sqlite3* db);
int do_select(sqlite3* db);

int main(int argc, const char *argv[])
{
	//创建并打开数据库
	sqlite3* db=NULL;
	if( sqlite3_open("./my.db",&db)!=SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_open :%d :%s __%d__\n",sqlite3_errcode(db),sqlite3_errmsg(db),__LINE__);
		return -1;
	}
	printf("sqlite3_open success __%d__\n",__LINE__);

	char sql[128] = "create table if not exists stu (username char,passwd char);";
	char* errmsg = NULL;
	if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_exec: %s __%d__\n",errmsg,__LINE__);
		return -1;
	}
	printf("create table stu success __%d__\n",__LINE__);

	char choose = 0;
	while(1)
	{
		printf("----------------------------------\n");	
		printf("-------------1.注册---------------\n");	
		printf("-------------2.查询---------------\n");	
		printf("-------------3.退出---------------\n");	
		printf("----------------------------------\n");	
		printf("请输入>>>");
		choose = getchar();
		while(getchar()!=10);

		switch(choose)
		{
		case '1':
			do_register(db);
			break;
		case '2':
			do_select(db);
			break;
		case '3':
			goto END;
		}
	}
	
END:	
	//关闭数据库
	if( sqlite3_close(db)!=SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_open :%d :%s __%d__\n",sqlite3_errcode(db),sqlite3_errmsg(db),__LINE__);
		return -1;
	}
	printf("sqlite3_close success __%d__\n",__LINE__);

	return 0;
}


//查询
int do_select(sqlite3* db)
{
	char sql[128] = "select * from stu;";
	char** pres = NULL;
	int row,column;
	char* errmsg = NULL;

	if(sqlite3_get_table(db,sql,&pres,&row,&column,&errmsg) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_get_table: %s __%d__\n",errmsg,__LINE__);
		return -1;
	}
	printf("查询完毕\n");
	printf("row=%d column=%d pres=%p\n",row,column,pres);

	for(int i=0;i>>");
	scanf("%s %s",username,passwd);
	while(getchar()!=10);


	char sql[128] = "";
	char* errmsg = NULL;
	sprintf(sql,"insert into stu values (\"%s\",\"%s\");",username,passwd);
	printf("sql = %s\n",sql);
	if(sqlite3_exec(db,sql,NULL,NULL,&errmsg) != SQLITE_OK)
	{
		fprintf(stderr,"sqlite3_exec: %s __%d__\n",errmsg,__LINE__);
		return -1;
	}
	printf("register stu success __%d__\n",__LINE__);
	return 0;
}

你可能感兴趣的:(数据库)