顯示具有 ADO資料庫 標籤的文章。 顯示所有文章
顯示具有 ADO資料庫 標籤的文章。 顯示所有文章

星期三, 10月 14, 2015

SQL若是使用key當欄位名稱時,where上面寫key可能還沒差,但是insert into (key) 這樣就不行囉~

星期二, 6月 16, 2009

壓縮mdb資料庫


function CompressDB(DBName: string): Boolean;
var
DaoVar: OLEVariant;
tmpDBName : string;
begin
if not FileExists(DBName) then
begin
Result := False;
exit;
end;

tmpDBName := ExtractFilePath(DBName) + 'temp.mdb';
if dm1.ADOConnection2.Connected then dm1.ADOConnection2.Connected := false; //如果資料庫打開,則要先關閉
try
try
DaoVar := CreateOleObject('DAO.DBEngine.36');
if FileExists(tmpDBName) then DeleteFile(tmpDBName); //刪除臨時資料庫"temp.mdb"
DaoVar.CompactDatabase(DBName, tmpDBName); //壓縮"dbName" 到"temp.mdb"
if DeleteFile(DBName) then //刪除文件"dbName"
RenameFile(tmpDBName, DBName); //將"temp.mdb"改名為"dbName "
Result := true;
except
Result := false;
end;
finally
// dm1.ADOConnection2.Connected := true; //為了其它操作能夠正常執行,還要打開資料庫連接。
end;
end;

星期二, 11月 04, 2008

若須一直Select資料庫,可採用TVirtualTable

1.SELECT所有資料至VT5
2.

VT5.DisableControls;
VT5.First;

While not VT5.Eof do
begin
if Pos(SearchName,UpperCaseEx(VT5.FieldValues['swname']))<>0 then
begin

//FieldValues['swid']:=VT5.FieldValues['swid'];
//FieldValues['swname']:=VT5.FieldValues['swname'];
//FieldValues['swver']:=VT5.FieldValues['swver'];
//FieldValues['snum']:=VT5.FieldValues['num'];

VT5.Delete;
Break;
end else
VT5.next;
end;
VT5.First;
VT5.EnableControls;

星期四, 10月 30, 2008

同時更新DB方法


//******************************************************************************
//* InitADOQueryUpdateBatch: 設定UpdateBatch專用的TADOQuery物件 *
//* (例如轉換資料表格式)所需要的參數 *
//* 1. UpdateBatch方法要怎麼用? *
//* 答﹕啟用UpdateBatch功能的前提條件﹕ *
//* 使用ADO之BatchUpdate功能之前提條件 *
//* CursorType屬性值需為﹕ctKeySet 或 ctStatic *
//* a. LockType屬性值需為﹕LtBatchUpdate *
//* b. 執行的SQL敘述需為﹕Select 敘述 *
//* c. CursorLocation屬性值需為﹕clUseClient *
//* 當CursorLocation屬性值為clUseServer時也可使用BatchUpdate功能﹐ *
//* 只是說其缺點是無法使用ADO的Briefcase模型功能﹐且在執行效率上不佳﹒ *
//* *
//* 2. 完成如上的設定就已經自動開啟UpdateBatch功能了﹐ *
//* 在對資料庫進行異動時(如Post, Insert, Delete)﹐ *
//* 並非對后端的資料庫來源﹐而是針對前端的快取記憶體中的資料而言﹐ *
//* 因為Batchupdate功能已將后端資料庫中的資料抓取到前端的快取記憶體中了﹐ *
//* 回存后端資料庫時請參考第3點 *
//* *
//* 3. 在使用BATCHUPDATE時該怎麼做才會將資料寫到資料庫呢? *
//* 3-1 當需要把快取記憶體中所有的異動回存到后端資料庫來源﹕ *
//* begin *
//* ADODataSet1.UpdateBatch; *
//* end; *
//* *
//* 3-2 當需要把快取記憶體中所有的異動取消﹐ *
//* 即放棄之前在快取記憶體中的異動﹐不回存到后端資料庫﹕ *
//* begin *
//* ADODataSet1.CancelBatch; *
//* end; *
//******************************************************************************
procedure TRecUIControl.InitADOQueryUpdateBatch(ADOQueryUB: TADOQuery);
begin
// 設定ADOQueryUB物件所需參數
with ADOQueryUB do
begin
CommandTimeout := 1200;
Connection := m_ADOConnectionBT; //
CursorLocation := clUseClient; // Connection is client-side
CursorType := ctStatic ; // Only ctStatic is supported if the CursorLocation property is set to clUseClient
LockType := ltBatchOptimistic; // For batch update mode rather than immediate update mode
SQL.Clear;
end;
end;
////////////
bUpdateOK := True;
ADOQuery1.Connection.BeginTrans; // 使用交易機制,確保更新無誤
for i:=0 to TreeMember.Items.Count-1 do
begin
sUserID:=TreeMember.Items[i].ColumnText[1];
sSQL:= 'UPDATE usertable SET appliedsetting=' + IntToStr(APPLY_ONE_GROUP) +' WHERE userid=' + sUserID +';';
sSQL:=sSQL+'UPDATE grouptouser SET selected=0 WHERE userid=' + sUserID +';';
sSQL:=sSQL+'UPDATE grouptouser SET selected=1 WHERE userid=' + sUserID +' AND groupid=' + m_sID+';';
if not SQLExecuteOK(ADOQuery1,sSQL) then
begin
bUpdateOK := False;
Break;
end;
end;
if not bUpdateOK then
begin
ADOQuery1.Connection.RollbackTrans; // 發生問題時,回復交易內容
Exit;
end
else
ADOQuery1.Connection.CommitTrans; // 若更新無誤,送出交易內容

星期四, 10月 02, 2008

自動塞入一萬萬行資料


declare @counter int
set @counter = 0
while @counter <10000begin set @counter = @counter + 1 print 'The counter is ' + cast(@counter as char) insert into log (
logdate,userid,pcid,sourcefile,filesize,filehash,writez,logmemo,domainid,hasfile,filelogtype,domain_name,user_name,full_name,compu
ter_name,location,format_tag,dept_name,host_address,backup_path,exe_name,remote_host,is_blocked,dest_drive,dest_drive_type,self_ex
tract_type,fort_server_id) select top 10000
logdate,userid,pcid,sourcefile,filesize,filehash,writez,logmemo,domainid,hasfile,filelogtype,domain_name,user_name,full_name,compu
ter_name,location,format_tag,dept_name,host_address,backup_path,exe_name,remote_host,is_blocked,dest_drive,dest_drive_type,self_ex
tract_type,fort_server_id from log
end

星期四, 7月 31, 2008

初始化ADOConnection函數


procedure TRecUIControl.InitADOConnectionBeginTrans(ADOConnBatchTrans: TADOConnection);
begin
// 設定ADOConnBatchTrans物件所需參數
with ADOConnBatchTrans do
begin
CommandTimeout := 300;
//ConnectOptions := coAsyncConnect; // The connection is formed asynchronously
CursorLocation := clUseServer; // Connection is client-side
LoginPrompt := False; // Don't show the login dialog when connecting to a database
Provider := 'SQLOLEDB.1'; //
ConnectionString := frmMain.ADOConnection1.ConnectionString; // 取主程式的ConnectionString
end;
end;

星期五, 11月 23, 2007

用執行序去跑ADO資料庫更新


unit Unit1;

uses unit2;

procedure TForm1.Button3Click(Sender: TObject);
begin
jjj := strtoint(Edit6.text); //jjj為記錄資料庫塞爆的全域變收

button1.enabled:=false;
TDownLoad.Create.OnTerminate := ThreadDoe;
end;

procedure TForm1.ThreadDoe(Sender: TObject);
begin
//Dec(ThreadsRunning); //減到為0又可以可以重跑 //如果TDownLoad.Create很多個同時
Button1.Enabled := True; //Thread跑完後
end;



unit Unit2;

interface

uses
Classes, ADODB, Dialogs, Forms;//這裡也使用Forms不太好

type
TDownload = class(TThread)
private
procedure Download;
{ Private declarations }
protected
procedure Execute; override;
public
constructor Create;
end;

implementation

uses Unit1;

{ TDownload }
constructor TDownload.Create;
begin
FreeOnTerminate := True;
inherited Create(False);
end;

procedure TDownload.Execute;
begin
Download;
{ Place thread code here }
end;

procedure TDownload.Download;
var
i : integer;
query1 : string;
FADOQuery : TADOQuery;
FADOConn : TADOConnection;
begin

//showmessage(Edit3.text);
FADOConn := TADOConnection.Create(nil);
FADOQuery:=TADOQuery.Create(nil);
FADOConn.ConnectionString := svr_string;
FADOConn.Connected := True;

FADOQuery.Connection := FADOConn;
try
try
for i := 0 to jjj - 1 do
begin
if not SQLExecuteOK(FADOQuery, 'insert into test (k) values (3)') then
ShowMessage('Query ERROR!!');
Application.ProcessMessages;

end;
except
showmessage('error');
end;
finally
FADOQuery.free;
FADOConn.Free;

end;
end;

end.

星期五, 11月 02, 2007

判斷資料表是否存在



Function TableExist( pConn:TADOConnection; pcTable : string ) : boolean ; overload ;
var
tmpFldList : TStrings ;
nLoop : integer ;
begin
Result := False ;
tmpFldList := TStringList.Create ;
pConn.GetTableNames( tmpFldList, True ); // 包含系統表
for nLoop := 0 to tmpFldList.Count - 1 do
begin
if uppercase( tmpFldList[nLoop] ) = uppercase( pcTable ) then
begin
Result := True ;
break ;
end;
end;
tmpFldList.Free ;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin

if TableExist(ADOConnection1, '富達新興') then
showmessage('ok');
end;

星期一, 9月 17, 2007

如何連結access 2007的accdb資料庫

同樣的也是用ADOConnection來連結
提供者要選擇
Microsoft Office 12.0 Access Database Engine OLE DB Provider,若沒有可能要去下列連結安裝
http://www.microsoft.com/downloads/details.aspx?displaylang=zh-tw&FamilyID=7554f536-8c28-4598-9b72-ef94e038c891
接著在 連線->資料來源->手動輸入位置及檔名
最後在最下方 測試連線

星期三, 8月 29, 2007

log檔成長塞爆硬碟解決方法

以下是我自己做的管理程式,在登入SQL Server以後,能看目前擁有的硬碟空間,資料庫的資料檔及記錄檔佔用的空間,然後可以清鬆以一鍵做清空Log檔及壓縮資料庫的功能,並能調整資料檔及記錄檔的設定。





資料庫包含資料檔及記錄檔(log)
資料檔有
Data (資料)
Indexes (索引)
Unused (未使用)
Unreserved (未分派)

記錄檔包括
Used (已使用)
Unused (未使用)


清空log記錄檔
'backup log database_name with Truncate_only'

壓縮資料庫(包括資料檔及記錄檔(log))
'DBCC SHRINKDATABASE database_name';

查詢資料庫
'sp_spaceused';
可查到下列欄位
database_name
database_size
unallocated space
reserved
data
index_size
unused


查詢資料檔設定
'SELECT * FROM sysfiles where name = database_name';
查詢log檔設定
'SELECT * FROM sysfiles where name = database_name_log';
fileid
grouid (0表示記錄檔,1表示資料檔)
size (檔案大小以8k頁面為單位)
maxsize(-1表示無限制,0表示不成長,268435456 表示能成長的最大值)
growth(0表示不成長)
status (status>=1048576表示growth為百分比表示(0x100000))
perf (已保留)
name (檔案名稱)
filename (實體位置加檔案名稱)

查詢log檔案情況
'DBCC SQLPERF(LOGSPACE)';
可以查到下列欄位
Database Name
Log Size(MB)
Log Space Used(%)
Status


顯示
資料庫大小 = 查詢語法database_size即可
資料庫未使用大小 = 查詢語法unallocated space即可
資料檔大小 = 查詢語法size即可
資料檔未使用大小 = 查詢語法reserved的相反即可
記錄檔大小 = 查詢語法size即可
記錄檔未使用大小 = 查詢Log Space Used(%)相反即可

變更log檔大小要注意的是:
初始大小不能小於目前的大小,且不能大於2097152
檔案成長要界於1~10000
檔案成長不能大於檔案大小上限
檔案成長要界於1~1048572
檔案大小上限要大於或等於初始大小
檔案大小上限要界於1~2097152
每個資料庫的權限大小可能有設定,而初始大小不能大於限定的大小。

變更log檔所下的語法
'ALTER DATABASE kobe MODIFY FILE (NAME = database_log_name, MAXSIZE = 26MB, SIZE = 11MB, FILEGROWTH = 21MB)';

查詢資料庫硬碟大小空間
'master.dbo.xp_fixeddrives';

星期三, 8月 22, 2007

用ADOStoredProc1去執行access上的更新語法

須新增TADOConnect,TADOStoreProc,TButton,TEdit。
在TADOConnect的connected屬性改為True及LoginPrompt屬性改為False,以及ConnectionString設定好access位置。
TADOStoreProc的connection屬性設ADOConnect1。
TButton1點一下後
貼上程式碼


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FMTBcd, StdCtrls, DB, ADODB, SqlExpr, Grids, DBGrids;

type
TForm1 = class(TForm)
ADOStoredProc1: TADOStoredProc;
ADOConnection1: TADOConnection;
Button1: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
ADOStoredProc1.ProcedureName:='q1';
ADOStoredProc1.parameters.clear;
ADOStoredProc1.parameters.CreateParameter('va', ftInteger, pdInput, 1, edit1.text);
ADOStoredProc1.Prepared;
ADOStoredProc1.execproc;
end;

end.



access的資料庫新增一個資料表ccc,及查詢q1,ccc資料表有a、b欄位(a為整數,b為文字),q1的程式碼如下:
update ccc set ccc.b='ok' where ccc.a=[va];

星期一, 8月 13, 2007

方便連結與中斷及操作資料庫的函式

no e
uses ADODB, ComObj;

var
function SQLOpenOK(ADO:TADOQuery; sSQL:string): boolean;
function SQLExecuteOK(ADO:TADOQuery; sSQL:string): boolean;



{-------------------------------------------}
//執行SQL命令,成功=true ,失敗=false
function SQLOpenOK(ADO:TADOQuery; sSQL:string): boolean;
function QuotedMsg(sMsg:string): string;
begin
sMsg:=Trim(sMsg);
if sMsg='' then Result:=''
else Result:=' ['+sMsg+']';
end;
begin
Result:=False;
try
ADO.Close;
ADO.SQL.Clear;
ADO.SQL.Add(sSQL);
ADO.Open;
except
On E:EOleException Do
begin
ShowMessage(E.Message);
if E.ErrorCode=E_FAIL then //連線失敗
begin
ShowMessage('與DB連線失敗');
Application.Terminate;
end;
exit;
end;
end;
Result:=True;
end;


{-------------------------------------------}
function SQLExecuteOK(ADO:TADOQuery; sSQL:string): boolean;
function QuotedMsg(sMsg:string): string;
begin
sMsg:=Trim(sMsg);
if sMsg='' then Result:=''
else Result:=' ['+sMsg+']';
end;
begin
Result:=False;
try
ADO.Close;
ADO.SQL.Clear;
ADO.SQL.Add(sSQL);
ADO.ExecSQL;
except
On E:EOleException Do
begin
ShowMessage(E.Message);
if E.ErrorCode=E_FAIL then //連線失敗
begin
ShowMessage('與DB連線失敗');
Application.Terminate;
end;
exit;
end;
end;
Result:=True;
end;

如何使用呢?
ADOConnection1的屬性Connectted=TrueLoginPrompt=Flase

try
ADOConnection1.Connected := True;
except
Showmessage('連線失敗!');
end;

if not SQLOpenOK(ADOQuery1,'SELECT * FROM 資料表名') then
ShowMessage('Query ERROR!!');
s := 'create table 富達新興 (';
s := s + '流水號 AUTOINCREMENT NOT NULL';
s := s + ', [日期] Date';
s := s + ', 淨值 int';
s := s + ', PRIMARY KEY (流水號)';
s := s + ');';
if not SQLExecuteOK(ADOQuery1,s) then
ShowMessage('Query ERROR!!');


insert into 資料表(column1, column2, column3..) values(v1, v2, v3...);
記得是整數時前後不用加''',若是字串時則要加'''',若是時間時則不用加''',但要加個#。