All pastes #24668 Raw Edit

Someone

public text v1 · immutable
#24668 ·published 2005-10-05 13:37 UTC
rendered paste body
int mssql_connect(void) {
	int iRet = 0;
	char sSQL[SQLCOMMAND_SIZE];
	TDSCONNECTINFO *connection = NULL;

	//-- attempt to allocate the variables
	if (!(login = tds_alloc_login())) {
		ast_log(LOG_ERROR, "tds_alloc_login() failed.\n");
		return -1;
	}

	tds_set_server(login, dbhost);
	tds_set_user(login, dbuser);
	tds_set_passwd(login, dbpass);
	tds_set_app(login, "TSQL");
	tds_set_library(login, "TDS-Library");
	tds_set_client_charset(login, dbcharset);
	tds_set_language(login, dblanguage);
	tds_set_packet(login, 512);
	tds_set_version(login, 7, 0);
	
	if (!(context = tds_alloc_context())) {
		ast_log(LOG_ERROR, "tds_alloc_context() failed.\n");

		//-- we need to escape here
		goto connect_failed;
	}

	if (!(tds = tds_alloc_socket(context, 512))) {
		ast_log(LOG_ERROR, "tds_alloc_socket() failed.\n");

		//-- we need to escape here
		goto connect_failed;
	}

	tds_set_parent(tds, NULL);

	connection = tds_read_config_info(tds, login, context->locale);
	if (!connection) {
		ast_log(LOG_ERROR, "tds_read_config() failed.\n");

		//-- we need to escape here
		goto connect_failed;
	}

	if (tds_connect(tds, connection) == TDS_FAIL) {
		ast_log(LOG_ERROR, "Failed to connect to MS SQL server.\n");
		tds = NULL;
		tds_free_connect(connection);
		connection = NULL;

		//-- we need to escape here
		goto connect_failed;
	}

	tds_free_connect(connection);
	connection = NULL;

	//-- create the SQL command to switch databases and submit
	sprintf(sSQL, "USE %s", dbname);

	if ((tds_submit_query(tds, sSQL) != TDS_SUCCEED) || (tds_process_simple_query(tds) != TDS_SUCCEED)) {
		ast_log(LOG_ERROR, "Could not change database (%s)\n", dbname);
		
		//-- we need to escape here
		goto connect_failed;
	} else {
		dbconnected = 1;
	}

	return dbconnected;

connect_failed:
	mssql_disconnect();

	return -1;
}