Ir para conteúdo
Fórum Script Brasil
  • 0

(Resolvido) Pegar/conseguir TableName pelo DataSource..


LucAlucard

Pergunta

Gente to dando uma olhada aqui nos meus códigos antigos e resolví re-escrever algumas coisas... Por exemplo..

Algumas funções eu usava TADOTable nas variaveis.. mas pensei "puts e se eu precisar mudar o banco q não use mais o adotable? Vou ficar preso?" aew resolvi pegar pelo datasource já que praticamente todos precisam usar o datasource de alguma forma.

MASSSS quando estava quase terminando todas as minhas funções de adotable pra tdatasource ou tdataset.. acabei me confrontando com uma coisa..

Como conseguir pegar o tableName pelo dataSource.. já q o dataSource pod lincar tanto query (qry) quanto table (tbl).. procurei e procurei mas não consigo achar algum comando pra isso =/.. alguém pode me ajduar??

Vlw gente um forte abraço a todos!! ^^

Link para o comentário
Compartilhar em outros sites

6 respostass a esta questão

Posts Recomendados

  • 0
Como conseguir pegar o tableName pelo dataSource.. já q o dataSource pod lincar tanto query (qry) quanto table (tbl).. procurei e procurei mas não consigo achar algum comando pra isso =/.. alguém pode me ajduar??
Voce procurou no help do delphi ?

TDataSetProvider.OnGetTableName

Occurs when a resolver initializes its information about the table to which it applies updates.

type TGetTableNameEvent = procedure(Sender: TObject; DataSet: TDataSet; var TableName: string) of object;

property OnGetTableName: TGetTableNameEvent;

Description

Write an OnGetTableName event handler to enable the provider to apply updates to non-live queries, stored procedures, or other datasets where the resolver can’t determine the target table from the provider’s dataset. When the resolver component is initialized, it stores the name of the table that is the target of its updates. This table name can be used in generated SQL statements that apply the updates. When the dataset is a TTable, the resolver can use the table’s TableName property. However, if the dataset is a “dead” query or stored procedure, the resolver has no way to determine the destination of the update without input from an OnGetTableName event handler.

The Sender parameter is the provider component.

The DataSet parameter is the dataset to which updates should be applied. This may be the provider’s dataset or a nested detail dataset.

Return the name of the target table as the TableName parameter. The resolver uses this to apply updates.

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

A minha versão do Delph é lite (vem só o básico do básico e isso não inclui o Help ^^')..

Então amigo eu não sei usar esse componente (acabei dando uma estudada sobre esse cara..) mas esse OngetTableName ele é um evento... como ela poderia me ajudar a conseguir o nome de uma tabela? vlw gente!!

Editado por LucAlucard
Link para o comentário
Compartilhar em outros sites

  • 0

algumas dicas:

Use uma função "GetTableNameFromSQL" do próprio Delphi que está na 
unit DBCommon
// Obter nome das tabelas de um determinado ALIAS.
try
S := TStringList.Create;
GetTableNames('NomeDoAlias', '*.db', False, False, S);
Memo1.Text:=S.Text;
finally
S.Free;
end;
MyStringList := TStringList.Create;
try
  Session.GetTableNames('DBDEMOS', '*.db',False, False, MyStringList);
  { Add the table names to a list box }
  ListBox1.Items = MyStringList;
finally
  MyStringList.Free;
end;
Populates a string list with the names of tables in the database.

procedure GetTableNames(List: TStrings; SystemTables: Boolean = False);

Description

Call GetTableNames to retrieve a list of tables in the associated database.

List is the already-existing string list object into which the tables names are put.

Set SystemTables to indicate whether the list of table names should include the database’s system tables.

ADOConnection1.GetTableNames(ListBox2.Items, False);

Note: any contents already in the target string list object are eliminated and overwritten by the data produces by GetTableNames.


To get a listing of all of the tables contained in the database accessed via the connection object, use the GetTableNames method. This method copies a list of table names to an already-existing string list object. Use individual elements from this list for such things as the value for the TableName property of a TADOTable component or the name of a table in an SQL statement executed by a TADOQuery.

ADOConnection1.GetTableNames(ListBox1.Items, False);

The example below traverse a list of table names created using the GetTableNames method. For each table, the routine makes an entry in another table with the table’s name and number of records.

procedure TForm1.Button1Click(Sender: TObject);

var
  SL: TStrings;
  index: Integer;
begin
  SL := TStringList.Create;
  try
    ADOConnection1.GetTableNames(SL, False);
    for index := 0 to (SL.Count - 1) do begin
      Table1.Insert;
      Table1.FieldByName('Name').AsString := SL[index];
      ADOTable1.TableName := SL[index];
      ADOTable1.Open;
      Table1.FieldByName('Records').AsInteger :=
        ADOTable1.RecordCount;
      Table1.Post;
    end;
  finally

    SL.Free;
    ADOTable1.Close;
  end;
end;

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Desculpa cara. entendi q aew da pra pegar o nome das tabelas e tals... mas ainda não entendi como lincar isso no datasource pra conseguir saber se o datasource está relacionado com uma tTable ou um tQry.. pra poder pegar o nome da tabela quando necessário.. ^^''

Foi mal.. acho q já deve ta enchendo o saco isso... mas é q ta difícil achar isso aqui =/

Link para o comentário
Compartilhar em outros sites

  • 0
mas ainda não entendi como lincar isso no datasource pra conseguir saber se o datasource está relacionado com uma tTable ou um tQry.. pra poder pegar o nome da tabela quando necessário.. ^^''

Foi mal.. acho q já deve ta enchendo o saco isso... mas é q ta difícil achar isso aqui =/

acho que voce é que não esta entendendo .... dá até para saber qual é o table ou query associado ao DataSource, mas para saber qual é o nome da tabela através do DataSource não.

existe entretanto outra opção .... este comando

TableName := GetTableNameFromSQL(Command); // Set TableName property

uses DBCommon, AdoConEd, SQLEdit 

procedure TForm3.btnConnectionStringClick(Sender: TObject); 
var 
  SQLStr: string; 
  sqlFrm: TSQLEditForm; 
  Command: string; 
  Connection: TADOConnection; 
  TableName: string; 
begin 
  // Close the connection (when open) 
  ADOConnection1.Close; 
  
 if EditConnectionString(ADOConnection1) then // build it 
  begin 
    ADOConnection1.Open; // if succeeded open your connection 
    ADOConnection1.Connected := True; // and set Connected state to True 
  end; 

  // Build the query for your AdoDataSet using the default 
  // property handler within delphi 
  Command := ADODataSet1.CommandText; 
  Connection := ADOConnection1; 
  
  if Command <> ''then // check to be sure a connection has been made... 
    TableName := GetTableNameFromSQL(Command); // Set TableName property 
  
  // this is the function you can call to open the build dialog... 
  if EditSQL(Command, Connection.GetTableNames, Connection.GetFieldNames, TableName) then 
    ADODataSet1.CommandText := Command; 
  
  ADODataSet1.Active := True; // Set Active... 
end;

OBS: pegar o nome da tabela quando necessário

Se voce está tentanto automatizar alguma rotina relacionada a nomes de tabelas, acho que esta pegando o caminho mais dificil

abraço

Link para o comentário
Compartilhar em outros sites

  • 0

Entendi.. é tava tentando automatizar umas rotinas minhas... só faltava uma... pra mim não ficar "preso" ao Banco de Dados sabe?

Conseguí enteder.. fiz até um exemplinho aqui no meu projeto usando o TADODataSet (nunca tinha usado por sinal ^^'')

procedure TFrmMenu.Button1Click(Sender: TObject);
begin
DMTabelas.ADODataSet1.commandText := 'select * from ESTADOS';
showmessage(GetTableNameFromSQL(DMTabelas.ADODataSet1.commandText));
end;

Mas pelo q da pra ver... fica mais fácil usar mesmo ficar noq eu to.. Mas brigadão amigo! Quebrou um galhão!! ^^

Brigadão pela força browder.. sempre quando eu to com dúvida você sempre me ajuda.. nossa tomara q você esteja bem onde está! E Parabéns mesmo!!

Um forte abraço!!

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      651,9k
×
×
  • Criar Novo...