CreateProcess操作 SQLPLUS 执行 SQL文件

sqlplus -S "scott/tiger@orcl" @"E:\1.sql"

-S  : 无提示模式 ,可去掉

"scott/tiger@orcl"  :连接信息,账号、密码、TNS

@"E:\1.sql"   :要执行的SQL文件路径,@ 必须有

   -----------  注意,如果1.SQL中有insert、update、delete等,需要使用commit,否则修改无效;


-----------------------------------------------------------------------------------------------------------------------------

为在程序中灵活使用上面的操作,可如下:通过代码创建无窗口命令控制台,执行上面的操作

	SECURITY_ATTRIBUTES   sa; 
	HANDLE   hRead,hWrite; 

	sa.nLength   =   sizeof(SECURITY_ATTRIBUTES); 
	sa.lpSecurityDescriptor   =   NULL; 
	sa.bInheritHandle   =   TRUE; 
	if   (!CreatePipe(&hRead,&hWrite,&sa,0))   
	{ 
		return   FALSE; 
	}   

	PROCESS_INFORMATION   pi;   
	ZeroMemory(&pi,sizeof(pi));

	STARTUPINFO   si; 
	ZeroMemory(&si,sizeof(si));
	si.cb   =   sizeof(STARTUPINFO); 
	si.hStdError   =   hWrite; 
	si.hStdOutput   =   hWrite; 
	si.dwFlags   =   STARTF_USESHOWWINDOW|STARTF_USESTDHANDLES; 
	si.wShowWindow   =   SW_SHOW; 
	si.lpReserved = NULL;
	si.lpDesktop = NULL;
	si.lpTitle = NULL;
	si.cbReserved2 = NULL;
	si.lpReserved2 = NULL;
	//关键步骤,CreateProcess函数参数意义请查阅MSDN 
	char cA[] = "sqlplus -S \"scott/tiger@orcl\" \"@E:\\1.sql\"";
	if (!CreateProcess( NULL,cA,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi))   
	{ 
		DWORD d = GetLastError();
		return   ""; 
	} 
	CloseHandle(hWrite); 

	char   buffer[4096]   =   {0}; 
	DWORD   bytesRead;   
	std::string strOutPut = "";

	while   (true)   
	{ 
		if   (ReadFile(hRead,buffer,4095,&bytesRead,NULL)   ==   NULL) 
			break; 
		//buffer中就是执行的结果,可以保存到文本,也可以直接输出 
		//printf(buffer); 
		strOutPut += buffer;
		//Sleep(200);   
	}


	return   strOutPut;


你可能感兴趣的:(oracle,C++,SQL文件,命令控制台)