对SQL数据库的操作我们首先要判断SQL Server是否安装,然后启动SQL Server。
再通过osql.exe执行SQL语句进行数据库操作。 下面是针对这几种操作的一些函数:
1、检查SQL Server是否安装
prototype CheckSQL();
function CheckSQL()
BOOL bSuccess;
NUMBER nType, nvSize;
STRING szVer;
STRING szSetupVer, szSetupPath;
begin
RegDBSetDefaultRoot ( HKEY_LOCAL_MACHINE );
szSetupPath = "SOFTWARE\\Microsoft\\MSSQLServer\\Setup";
szSetupVer = "SOFTWARE\\Microsoft\\MSSQLServer\\MSSQLServer\\CurrentVersion";
//获取SQL Server版本
nType = REGDB_STRING;
if (RegDBGetKeyValueEx ( szSetupVer, "CurrentVersion" , nType , szVer , nvSize ) < 0) then
bSuccess = FALSE;
else
//获取SQL Server安装路径
if (RegDBGetKeyValueEx ( szSetupPath, "SQLPath" , nType , szSQLPATH , nvSize ) < 0) then
bSuccess = FALSE;
else
bSuccess = TRUE;
endif;
endif;
return bSuccess;
end;
2、检查SQL Server版本号,是否安装了SP3
prototype CheckSQLVersion();
function CheckSQLVersion()
BOOL bSuccess;
NUMBER nType, nvSize;
STRING szVer;
STRING szSetupVer;
begin
RegDBSetDefaultRoot ( HKEY_LOCAL_MACHINE );
bSuccess = FALSE;
szSetupVer = "SOFTWARE\\Microsoft\\MSSQLServer\\MSSQLServer\\CurrentVersion";
nType = REGDB_STRING;
if (RegDBGetKeyValueEx ( szSetupVer, "CSDVersion" , nType , szVer , nvSize ) < 0) then
bSuccess = FALSE;
else
if szVer = '8.00.761' then
bSuccess = TRUE;
endif;
endif;
return bSuccess;
end;
3、启动SQL Server服务器
prototype StartSQLServr(STRING, STRING);
//传入用户名,用户密码
function StartSQLServr(szLoginName, szPassword)
BOOL bSuccess;
VARIANT objSQL;
begin
objSQL = CreateObject("SQLDMO.SQLServer");
if IsObject(objSQL) then
try
try
objSQL.Start(TRUE, "(Local)", szLoginName, szPassword);
catch
objSQL.Connect("(Local)", szLoginName, szPassword);
endcatch;
catch
bSuccess = FALSE;
return bSuccess;
endcatch;
else
bSuccess = FALSE;
return bSuccess;
endif;
if objSQL.VerifyConnection then
bSuccess = TRUE;
else
bSuccess = FALSE;
endif;
return bSuccess;
end;
4、检查数据库是否已经存在
prototype IsExistDB(STRING, STRING, STRING);
//传入用户名,用户密码,数据库名
function IsExistDB(szLoginName, szPassword, szDBName)
BOOL bExist;
NUMBER i;
STRING szTemp;
VARIANT objSQL;
begin
objSQL = CreateObject("SQLDMO.SQLServer");
objSQL.Connect("(Local)", szLoginName, szPassword);
bExist = FALSE;
for i = 1 to objSQL.Databases.Count
StrToUpper(szTemp, objSQL.Databases.Item(i).Name);
if (szTemp == szDBName) then
bExist = TRUE;
return bExist;
endif;
endfor;
return bExist;
end;
5、删除数据库
prototype DeleteDB(STRING, STRING, STRING);
//传入用户名,用户密码,数据库名
function DeleteDB(szLoginName, szPassword, szDBName)
STRING szSQL;
begin
szSQL = "declare @dttm varchar(55) \n"
+ "select @dttm=convert(varchar,getdate(),113)\n"
+ "raiserror('Beginning Check Database at %s ....',1,1,@dttm) with nowait \n"
+ "GO \n"
+ "use master \n"
+ "go \n"
+ "if exists (select * from sysdatabases where name='" + szDBName + "') \n"
+ "begin \n"
+ "raiserror('Dropping existing " + szDBName + " database ....',0,1) \n"
+ " DROP database " + szDBName + "\n"
+ "end \n"
+ " GO \n"
+ "CHECKPOINT \n"
+ "go \n";
if !ExecuteSQL(szLoginName, szPassword, szSQL) then
return FALSE;
endif;
return TRUE;
end;