2008年(909)
分类:
2008-05-06 21:37:34
下载本文示例代码
我们知道,数据库连接文件(.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); }