Getting column names for a particular Table from Connection object.

Hi,
Can any one suggests me a way to get column names from a particular table of a database from the java.sql.Connection object. ?
Thanks in advance.

Connection connection;
DatabaseMetaData metadata = connection.getMetaData();
  String[] names = {"TABLE"};
  ResultSet tables = metadata.getTables(null,"%", "%", names);
  while (tables.next()) {
  String tableName = tables.getString("TABLE_NAME");
   ResultSet columns = metadata.getColumns(null, "%", tableName, "%");
while (columns.next()) {
  String columnName = columns.getString("COLUMN_NAME");
    }

Similar Messages

  • How do you get the column names for a given table from an SQL LocalDB programmatically in Visual Basic.

    Just new to this and unable to find answers

    My solution
        Public Function GetTableColumnNames() As Boolean
            Form1.ListBox1.Items.Clear()
            _MDFFileName = String.Format("{0}.mdf", _DatabaseName)
            _sqlConnectionString = String.Format("Data Source=(LocalDB)\v11.0;AttachDBFileName={1};Initial Catalog={0};Integrated Security=True;", _DatabaseName, Path.Combine(_DatabaseDirectory, _MDFFileName))
            Dim cn As New SqlConnection(_sqlConnectionString)
            'put the table name in brackets in case it has spaces in it
            Dim SQLString As String = "SELECT * FROM [" & _TableName & "]"
            Try
                cn.Open()
                Dim cmd As New SqlCommand(SQLString, cn)
                Dim rdr As SqlDataReader =
                cmd.ExecuteReader(CommandBehavior.KeyInfo)
                Dim tbl As DataTable = rdr.GetSchemaTable
                'This shows all of the information you can access about each column.
                For Each col As DataColumn In tbl.Columns
                    Form1.ListBox1.Items.Add(col.ColumnName)
                    Debug.Print("col name = " & col.ColumnName & ", type = " & col.DataType.ToString)
                Next
                'Get each column.
                For Each row As DataRow In tbl.Rows
                    Form1.ListBox1.Items.Add(row("ColumnName"))
                Next
                rdr.Close()
            Catch
                MessageBox.Show("Error opening the connection to the database.")
            Finally
                cn.Close()
            End Try
            Return _Success
        End Function

  • C# : Get Column name for an Insert Query from The Selected GridView Row.

    Hi Guys, I am trying to insert data in an SQL table by executing an Insert Query. 
    The problem is that I need to get the column name from a cell in the selected gridview Row.
    Here's the snippet:
    SqlCommand cmd30 = new SqlCommand("insert into mytable ( '"+GridView7.SelectedRow.Cells[0].Text+"' , r_id) values ('"+ GridView7.SelectedRow.Cells[1].Text +"', '"+TextBox1.Text+"')",con30);
            cmd30.ExecuteNonQuery();
    **r_id is not a Primary Key.
    The Error is get is:
    Incorrect syntax near 'r_id'.
    Any Help will be appreciated.
    Thanks,
    Shaleen
    TheHexLord

    Hi TheShaleen,
    Like your title mentioned.GridView control is a web class.This forum is to discuss problems of C# development.  Your question is not related to the topic of this forum.
    You'll need to post it in the dedicated ASP.Net Forum  for more efficient responses, where you can contact ASP.NET experts. Thanks for understanding.
    Best regards,
    Kristin
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Find the sequence name for a particular table

    Hi,
    Please give query to find the sequence name for a particular table in oracle.
    Thanks

    I mean getting List of Sequence names defined in DB.
    I got the answers
    select *from user_sequences                                                                                                                                                                                                               

  • How to get column names for a specific view in the scheme?

    how to get column names for a specific view in the scheme?
    TIA
    Don't have DD on the wall anymore....

    or this?
    SQL> select text from ALL_VIEWS
      2  where VIEW_NAME
      3  ='EMP_VIEW';
    TEXT
    SELECT empno,ename FROM EMP
    WHERE empno=10

  • Getting Column names (header) of a table dynamically

    Dear Experts,
    Greetings.
    I have a requirement in which I need to get the column name (header) of a table when the user clicks on a column.
    Kindly suggest me the possible ways.
    Thanks in advance.
    Regards
    Sathya

    Hi,
    use one of the following based on your requirement
    Bind the header text to a context attribute and access this attribute from code when clicked on the column.
    Or use parameter mapping.
    Regards
    Ayyapparaj

  • Getting column names for resultMap - Ibatis

    Hi friends,
    I need to get the column names for the properties specified in sqlMap.xml in my code .
    for example: <resultMap id="resmap" class="java.util.HashMap">
    <result property="custId" column="cust_id"/>
    <result property="routerId" column="router_id"/>
    <result property="routerName" column="router_name" jdbcType="CLOB"/>
    <result property="device_type" column="device_type"/>
    </resultMap>
    i need to get the column values in code.........
    is there anyway to access the sqlMap.xml file as an instance in Ibatis.

    I always use jaxb2 to unmarshall/marshall, works like a charm

  • How to know the column name using the index name for a particular table

    Hi All,
    I have small query regarding, I have index name and table name so by using this how can I know the column name associated with that index of that particular table specific to Oracle9i.
    Thanks
    Sudheer

    select *
    from user_ind_columns -- or all_ind_columns
    where table_name = UPPER('&table_name')
    and index_name = UPPER('&index_name');
    Regards
    Arun
    Gurgaon

  • How To Get Attribute Names for a Particular VO

    Hi ,
    How To Get Attribute Names Of a Vo where I can Set Viewattributname To the Table RN Columns Where I am Adding Extra Columns Based on Some Condn..
    So wen i am creating new Column to existing Table RN and we Need to add Attribute Name Also...Rt..
    And How To get RelationShip Between Database Column Name and Java Vo Attribute Name
    Ex: PlanId is the Java VO Attribute Name for the Database Column PLAN_ID
    In The Same way Hw We Get the Relation ship for All other columns In the Controller Cllass ..
    Can Any One Reply as It is urgent Req...
    Thanks ,,
    Jithen

    Instead of using the VO attribute names to set and get values, best to go to the VO definition, click on Java, and generate the View Row Class with the accessors.
    In the class where you're trying to set attributes, instead of a Row class, use the View Row class of your VO (eg ViewObjectName's class would be ViewObjectNameRowImpl), and when retrieving a row from the VO, cast the row to the previously mentioned View Row Class.
    At that point you can use the View Row Class's methods that would perform sets and gets of each column.
    To get attribute names, I don't know off the top of my head, but there might be a method mentioned in the Javadoc for the ViewRowImpl or ViewObject or ViewObjectDefinition classes to get the attribute/column mapping, or perhaps you can somehow read the XML definition of the VO which has that mapping.
    Assuming business components were built automatically and no attribute names were overridden, intuitively the attribute name is a camelcase version of the column name, removing understores and capitalizing the character following the removed underscore - but that's not a fool proof approach. Just a general observation.
    Hope this helps.
    Edited by: user6631964 on Sep 16, 2010 12:31 PM

  • Getting column names for a Query resultList?

    For a Query created via EntityManager.createQuery("some qlString here"), where the query language string picks out individual properties (so select p.firstName, p.lastName from Person p), is there any way to get the property names of the things retrieved?
    I'm trying to allow an end user to define JPA queries by storing the query language string persistently, and then (after some rudimentary checking) create a Query from it, hosted (at this point) in a JTable. It would be nice if there were a way to wire up the items returned by the query such that the JTable columns were "titled" with something appropriate.
    Otherwise I have to either (a) parse the QL string (yuck yuck yuck) or (b) somewhat redundantly have the user specify the columns/properties/related objects that they think they're retrieving.
    Thanks,
    Laird

    Connection connection;
    DatabaseMetaData metadata = connection.getMetaData();
      String[] names = {"TABLE"};
      ResultSet tables = metadata.getTables(null,"%", "%", names);
      while (tables.next()) {
      String tableName = tables.getString("TABLE_NAME");
       ResultSet columns = metadata.getColumns(null, "%", tableName, "%");
    while (columns.next()) {
      String columnName = columns.getString("COLUMN_NAME");
        }

  • How to Get Page Names For an Particular Role

    Hi Experts,
    I can easly get the roles assigned to an particular user through UME.
    How can i get the pages assigned to each roles.
    Please help me...
    Thanks
    Rabin

    Hi Rabin,
    Refer to this blog.
    Browse Roles, Folders, Pages & iViews assigned to a user: EP6 SP9 and higher
    Thanks
    Prashant

  • Why do I get a class conflict between the Prepare SQL.vi and the Get Column Name.vi with the SQL Toolkit compatibility vis from the Database Connectivity Toolkit?

    I have done extensive programming with the SQL Toolkit with LabVIEW versions through 6.1. My customer now wants to upgrade to Windows 7, so I am trying to upgrade to LabVIEW 2009 (my latest purchased version) using the Database Connectivity Toolkit, and the SQL Toolkit Compatibility vis. Everything seemed to be going okay with the higher level SQL operations, but I ran into trouble with the Get Column Name.vi. 
    The pictures below show the problem. The original SQL Toolkit connected the Prepare SQL.vi with the Get Column Name.vi with a cluster of two references, one for connection, and one for sql. The new compatibility vis have a class conflict in the wire because the Prepare SQL.vi contains a cluster with connection, and command references, but the Get Column Name.vi expects a cluster with connection and recordset references. 
    How do I resolve this conflict?
    Thank You.
    Dan

    I've never worked with the old version of the toolkit, so I don't know how it did things, but looking inside the SQL prep VI, it only generates a command, and the the column name VI wants a recordset. I'm not super familiar with all the internals of ADO, but my understanding is that is standard - you only have the columns after you execute the command and get the recordset back. What you can apparently do here is insert the Execute Prepared SQL VI in the middle and that will return what you need.
    I'm not sure why it worked before. Maybe the execute was hidden inside the prep VI or maybe you can get the column names out of the command object before execution. In general, I would recommend considering switching to the newer VIs.
    Try to take over the world!

  • Return the column names for which the row values are not null.

    Hi i m a new guy to db admin, and i need a sql script which should return column names of the particular table. and the returned column should have value (fyi - if the column has null value column name should not come in the sql o/p).
    Exmple:
    table name - A
    s.no name mark status fee
    1 aa 45 p null
    2 bb 30 null paid
    3 cc 35 p paid
    fyi -1) if i give the table name(A) and s.no (2) the o/p should be -- name,mark.
    2) if i give the tablename(A) and s.no (1) the o/p should be --- name,mark,status.
    Thanks
    Krishna.
    Edited by: user13294228 on Jun 14, 2010 10:54 PM

    BTW,
    The previous solution is for all values of the column, if you want a specific row, you can add it in where clause.
    I mean in your example, it you look like:
    SET serveroutput on;
    DECLARE
       l_cnt          NUMBER;
       l_str          VARCHAR2 (255) := '';
       l_table_name   VARCHAR2 (255) := 'YOUR_TABLE_NAME';
       l_col_cond     VARCHAR2 (255) := 'S_NO';
       l_val          NUMBER         := 1;
       CURSOR c_col
       IS
          SELECT column_name
            FROM user_tab_columns
           WHERE table_name = l_table_name;
    BEGIN
       FOR i IN c_col
       LOOP
          EXECUTE IMMEDIATE    'SELECT COUNT ('
                            || i.column_name
                            || ') FROM '
                            || l_table_name
                            || ' WHERE '
                            || l_col_cond
                            || ' = '
                            || l_val
                       INTO l_cnt;
          l_str := l_str || CASE
                      WHEN l_cnt = 0
                         THEN ''
                      ELSE i.column_name
                   END || ',';
       END LOOP;
       l_str := SUBSTR (l_str, 1, LENGTH (l_str) - 1);
       DBMS_OUTPUT.put_line (l_str);
    END;Saad,
    Edited by: S.Nayef on Jun 15, 2010 11:54 AM

  • How to use get column name.vi in SQL toolkit 2.0?

    Due to the vi "get column name.vi" paremeters,no table name has connected to the vi. So, I want to ask how to use this vi for gain one column name of a table. Maybe there are some other ways to solve column name getting.
    Thanks.

    Thanks!
    Error 4101 Description:
    Execute SQL - The connection, statement, or query handle you provided is not valid.
    I don't just used the toolkit in a while,now, I am developing a irrigation system. For the table field names defined by users,column names must be known before any select operations. Do you have any other good idea about drawing out the columnname parameters?
    As you know, a valid DSN and table have been also available. The database I used is Access. The bad thing to me is that there is no any text information gotten. And I think, it may be some problems in connection way which I don't find out.
    Really appreciated by your reply.
    Could you give me some example in the aspect?
    Thank you again.

  • Jakata POI excel: get column name

    Hi All
    Is there a way I can get column name where a particular cell is: (In excel spreadsheet)
    Ex: If I have column number 2: I should get "C" ( given col numbers are 0 based).
    Please let me know.
    Thanks
    bib

    It's not as easy as it might seem, since the letter sequence system is not compatible with common numeric sequence system.
    See here:
    [Java, POI - Converting number to Excel columns letter names|http://ondra.zizka.cz/stranky/programovani/java/converting_number_to_excel_column_letters_name.texy]

Maybe you are looking for

  • Can I have 2 Online numbers on one account?

    Hi, I'm already using an online number for my account. I'd like to use a second online number for a home business that I'm starting. How will that work having 2 online numbers on the same account? When Skype rings, will it tell me which number was di

  • Error while saving changes in RSPC Error Stack.

    Hi gurus,     I am able to make changes in the error stack in the transaction RSPC, However, when trying to save those changes, I get an error stating that the request "DTPR_* " doesn't exist. and the message is RSAODS005. I tried searching in SDN as

  • Can I assign the exchange rate data to consignment when I use MRKO

    We with the selling on consignment supplier are the foreign currency transactions The exchange rate was changed between the consignment withdrawal in inventory management and the posting of the consignment invoice. Then the transfer posting occur bet

  • Plannig values at cost element group level instead of at cost element lev

    Is it possible to plan values at cost element group level instead of at cost element level in BPS or SEM? Similary I have another question for financial statements. Is it possible to plan values at financial statement level instead of at G/ in BPS or

  • UCCX 5.02 Copy/Move Agent Recordings

    UCCX 5.02 Copy/Move Agent Recordings We are running UCCX 5.02 and have a workflow setup to automatically record all agent calls without Supervisor intervention. We are not using QM. Is there a UCCX tool, other than writing a .bat file and scheduling