拿一段代码给你吧:
const
strDBName = 'ipcamera';
strConn = 'Provider=SQLOLEDB.1;Password=%s;Persist Security Info=True;User ID=%s;' +
'Initial Catalog=%s;Data Source=%s';
function TForm3.setupDB(DBname,count, psw: string): boolean;
var
str:string;
begin
ADOConnection1.Connected:=false;
ADOConnection1.ConnectionString:=format(strConn,[psw,count,'master',Dbname]);
try
ADOConnection1.Connected:=true;
adocmd.CommandText:='sp_attach_db ''ipcamera'' ,'''+ExtractFilePath(Application.ExeName)+'ipcamera_data.mdf'','''+ExtractFilePath(Application.ExeName)+'ipcamera_Log.LDF''';
ADOCMD.Execute;
if edit11.text='' then
begin
try
ADOCMD.CommandText:='sp_droplogin ipcamera';
ADOCMD.Execute;
str:=inttostr(random(100000));
ADOCMD.CommandText:='sp_addlogin ''ipcamera'','''+str+'''';
adocmd.Execute;
ADOCMD.CommandText:='sp_addsrvrolemember ''ipcamera'',''sysadmin''';
adocmd.execute;
edit10.Text:=edit1.text;
edit11.text:='ipcamera';
edit12.text:=str;
except
raise;
MessageBox(self.Handle,pchar('数据库操作失败。'),pchar(self.caption),MB_ICONERROR);
exit;
end;
end;
finally
if ADOConnection1.Connected=false then
raise exception.Create('与数据库连接失败。')
// show;
// Screen.Cursor := crDefault;
end;
MessageBox(self.Handle,pchar('数据库设置成功!'),pchar(self.caption),MB_ICONinformation);
end;