我們知道,數據庫連接文件(.udl)可以動態生成各種數據庫連接的參數,而且它是一個文本文件。所以我們就可以動態生成,以增強程序的靈活性。但是該文件必須是UNICODE文本文件,不能是普通的ANSI文本文件。因此必須進行數據類型轉換。
1、首先定義一個數據庫連接結構:
struct db
{
char Server[20];
char Database[20];
char UserId[20];
char Password[20];
};
2、生成數據庫連接文件:
BOOL CUdlFile::CreateUdlFile(LPCTSTR lpFileName)
{
CFile fUdl;
BOOL bResult;
CString s1,s2,s3;
int m_Length;
//set value
s1="[oledb]";
s2="; Everything after this line is an OLE DB initstring";
s3.Format("Provider=SQLOLEDB.1;Password=%s;\
Persist Security Info=True;\
User ID=%s;Initial Catalog=%s;\
Data Source=%s",
m_dbParameter.Password,
m_dbParameter.UserId,
m_dbParameter.Database,
m_dbParameter.Server);
//open file
bResult=fUdl.Open (lpFileName,CFile::modeCreate|CFile::modeWrite);
if(!bResult) return FALSE;
LPWSTR m_Buffer;
m_Buffer = (LPWSTR)malloc(2 * sizeof(WCHAR));
m_Buffer[0]=0xFEFF; //flag of UNICODE file
fUdl.Write (m_Buffer,2);
free(m_Buffer);
fUdl.Write (L"[oledb]",14); //14為[oldb]的長度X2
fUdl.Write(L"\r\n",4);
fUdl.Write (L"; Everything after this line is an OLE DB initstring",104); //104為字符串長度X2
fUdl.Write(L"\r\n",4);
m_Length=s3.GetLength ();
m_Buffer = (LPWSTR)malloc((m_Length + 1) * sizeof(WCHAR));
MultiByteToWideChar(CP_ACP, 0, s3, m_Length, m_Buffer, m_Length);
fUdl.Write (m_Buffer,s3.GetLength ()*2);
fUdl.Write(L"\r\n",4);
free(m_Buffer);
m_Buffer = NULL;
fUdl.Close ();
return TRUE;
}
3、刪除數據庫連接文件:
BOOL CUdlFile::DeleteUdlFile(LPCTSTR lpFileName)
{
return ::DeleteFile(lpFileName);
}