How to get data in jtable from database

i m working on core java application i want to use jtable to show records to user. jtable will get records from mssql database. how to do this.. i m new so plz tell me briefly..with coding...
thanks

i have use this link:
import java.sql.*;
import javax.swing.table.*;
import javax.swing.event.*;
* This class takes a JDBC ResultSet object and implements the TableModel
* interface in terms of it so that a Swing JTable component can display the
* contents of the ResultSet. Note that it requires a scrollable JDBC 2.0
* ResultSet. Also note that it provides read-only access to the results
public class ResultSetTableModel implements TableModel {
ResultSet results; // The ResultSet to interpret
ResultSetMetaData metadata; // Additional information about the results
int numcols, numrows; // How many rows and columns in the table
* This constructor creates a TableModel from a ResultSet. It is package
* private because it is only intended to be used by
* ResultSetTableModelFactory, which is what you should use to obtain a
* ResultSetTableModel
ResultSetTableModel(ResultSet results) throws SQLException {
     this.results = results; // Save the results
     metadata = results.getMetaData(); // Get metadata on them
     numcols = metadata.getColumnCount(); // How many columns?
     results.last(); // Move to last row
     numrows = results.getRow(); // How many rows?
* Call this when done with the table model. It closes the ResultSet and
* the Statement object used to create it.
public void close() {
     try { results.getStatement().close(); }
     catch(SQLException e) {};
/** Automatically close when we're garbage collected */
protected void finalize() { close(); }
// These two TableModel methods return the size of the table
public int getColumnCount() { return numcols; }
public int getRowCount() { return numrows; }
// This TableModel method returns columns names from the ResultSetMetaData
public String getColumnName(int column) {
     try {
     return metadata.getColumnLabel(column+1);
     } catch (SQLException e) { return e.toString(); }
// This TableModel method specifies the data type for each column.
// We could map SQL types to Java types, but for this example, we'll just
// convert all the returned data to strings.
public Class getColumnClass(int column) { return String.class; }
* This is the key method of TableModel: it returns the value at each cell
* of the table. We use strings in this case. If anything goes wrong, we
* return the exception as a string, so it will be displayed in the table.
* Note that SQL row and column numbers start at 1, but TableModel column
* numbers start at 0.
public Object getValueAt(int row, int column) {
     try {
     results.absolute(row+1); // Go to the specified row
     Object o = results.getObject(column+1); // Get value of the column
     if (o == null) return null;
     else return o.toString(); // Convert it to a string
     } catch (SQLException e) { return e.toString(); }
// Our table isn't editable
public boolean isCellEditable(int row, int column) { return false; }
// Since its not editable, we don't need to implement these methods
public void setValueAt(Object value, int row, int column) {}
public void addTableModelListener(TableModelListener l) {}
public void removeTableModelListener(TableModelListener l) {}
the table is showing column name from database but not showing the data in row now what to do

Similar Messages

  • How to put data in JTable from database

    hi everyone,
    i want to query the databse and put the result in the JTable and if possible i want to edit some information. For example: i have 5 records in the database query them and place them in JTable and each record has its own status. if i want to change the status For Example: the status of the 4 records are "Cleared" and the other one is "RELEASEd" so if i have JCombo Box to set the 4 records in to RELEASED status and then save the changes is that possible?
    thank you
    dhing

    In [url /thread.jsp?forum=54&thread=387565]this thread I describe how to use a result set as a basis for table data. Check some database tutorials for information on getting a result set.

  • How to get data into the mySQL database?

    First some background.
    I have a website that has outgrown its designed dimensions and is a huge burden to maintain. See PPBM5 Benchmark
    There is a lot of maintenance work involved, so I'm investigating a PHP/MySQL approach to easen the burden and to add functionality to the site. With the current Excel based structure and over 420 entries, it is cumbersome for me to maintain, but also for users to find what they need.
    A MySQL based dynamic structure is a lot easier and offers vastly more selection capabilities, like selecting only records that meet specific criteria.
    Data submission is done with a form, that contains most of the relevant data, but the drawack is that people submitting their data are often not technically inclined, give wrong answers due to a lack of understanding or making typo's. The test results are attached in one or two separate .txt files, but often they have not read the instructions correctly or did something wrong, so these attached .txt files can not be trusted automatically, they have to be checked before inclusion.
    These were my initial thoughts:
    1. Data collection:
    To avoid spending all our energy and time  on correcting typo's, getting missing data, correcting errors, I am  investigating the use of CPU-Z in Ghost mode to create a .txt or .html  file that contains all relevant hardware info we need and even more. It gives all the info we currently have, but adds  data like number of memory sticks, DDR timings, stock clock speed and  BCLK setting, video card info and VRAM size, etc.
    To see what I mean, run CPU-Z, go to the About tab and press the Save Report button and look at the results.
    This can all be done without user intervention in an automatic way, but  maybe I need to add an Auto-It file to the test to make it all run as  desired.
    If this works and I'm able to extract the relevant data from the created  file and can insert it into the database, we may be in business for the  next version of PPBM5.5 or PPBM6. It does require a modification to the instructions, making them a lot  easier, because there is less data to fill out.
    2. Data submission:
    The submission form can be simplified if  the CPU-Z data can be used. We have to create an automatic way to attach  the created .html file from CPU-Z to the submission form and we have to  streamline the Output.txt and Output-MPE.txt files to be more easily included in the 'form.lib.php' file. It  currently is manual labor and very time consuming.
    3. Adding to Database:
    I have to find a way to create database  records from the Gmail forms I receive. All incoming mail messages need  to be checked on relevancy and if relevant, need to be added  automatically to the database and then offered for approval before final inclusion in the database. Data included in the database  will then include submission date and time, Email address,  IP address  used, plus links to the files submitted and available on the website.
    4. Publication of the database:
    After approval of new records from step  3, all updates will be automatically applied to the database and  accessible for users. I do not yet intend to introduce a user account ,  requesting login before all functionality is accessible. Too much trouble and administration.
    Queries should be possible on things like CPU (check box), so include  17-920, i7-930, i7-950 but exclude i7-980X and i7-990X, Size of memory  (check box), Overclocked (boolean, yes, no), SSD as OS disk, and similar  options.
    The biggest problem is to keep the color grading and statistical  indicators (Top, D9, Q3, Med, Q1 and D1) intact on dynamically generated  queries. Say you make a query which results in 20 observations, this  should show the related colors and legends. Next query results in 48 observations and of course the color grading and legends  do need to reflect that. Question in my mind, does the RPI remain  constant, independent of the query or does that need to be recalculated  on the basis of the query?
    Next thing is to allow a user to select a specific observation and by  simply clicking on it be shown, in a separate window (detail page) or  accordion, all the CPU-Z related information about the hardware.
    The graphs, Top-20 and MPE Gains, need to be dynamically adjusted, based on the query used.
    5. Ideally, external links:
    In an ideal situation, one could link the  CPU-Z data to external price databases, looking up current prices for  CPU, memory, video card, disks, raid controller, etc. to get instant  BFTB charts, based on the query made. But that is the next step.
    Situation now:
    I have a MySQL database that is easily updated with the new submissions. Simply create a .CSV flie from the submitted forms and import that into the database. The bulk of the initial work is done.Lots remain to be done as you can see above, but that is for a later time.
    Question:
    I have this table, that needs to be filled with data in the submitted and attached files. Mr. X submitted his data and can be uniquely identified by his "Ref_ID". He attached one or two files in .TXT format with the relevant test data. These files are stored on the server with a concatenated name:
    "Ref_ID","-","filename"
    Say his Ref-ID is: 20110204-6cf5 and his submitted file is called: Output(99).txt then the file can be found on the server as
    20110204-6cf5-Output(99).txt
    I need to be able to open that comma delimited file, the contents may look like this: "439","1036","819","531" and insert these contents into the relevant record and fields.
    Graphically,
    is what I want to achieve.
    This being my first exposure to PHP/MySQL, you can imagine I'm not clear on how to go from here.
    Added complication is that I actually have 5 numbers to insert per record and two calculated fields, Total Score and RPI should be calculated fields. Haven't yet figured out how to handle calculated fields, maybe only in the PHP/HTML code and not in the database.
    I hope someone can help me.

    You do have a very complex looking site and may need several tables in mysql to handle all that data. If you knew to phpmysql I would suggest taking a look at this tutorial it will help get you started in understanding how to $_GET info from a database and also how to $_POST data to a database. I am no expert just learning myself and I found this very helpful. This is the link http://www.adobe.com/devnet/dreamweaver/articles/first_dynamic_site_pt1.html
    There are also many tutorials on Youtube to help build a CMS Content Management Site I would suggest the following: -
    http://www.youtube.com/user/phpacademy
    http://www.youtube.com/user/betterphp
    http://www.youtube.com/user/flashbuilding
    And many more on my channel here
    http://www.youtube.com/user/Whisperingonthewind
    CMS's are easier to maintain, add edit and delete content.
    I have also recently bought a Book by David Powers Training from the Source very helpful.
    Anyway hope you get it sorted.

  • How to get time specification detail from database

    Dear All,
    How can I get the time specification detail from data base?
    Time specification is a 32 bit hexadecimal no type guid_32.
    Function wfd_timespec_reload provide the modified time specification detail.
    FUNCTION wfd_timespecs_reload
    ""Local Interface:
    *"  IMPORTING
    *"     VALUE(I_LOGSYS) TYPE  LOGSYS
    *"     VALUE(I_AWTYP) TYPE  WFD_AWTYP
    *"     VALUE(IT_TIMESPEC_KEYS) TYPE  WFD_KEY_TAB
    *"  EXPORTING
    *"     VALUE(ET_TIMESPEC_DETAILS) TYPE  WFD_TIMESPEC_TAB
    *"     VALUE(ET_INVALID_TIMESPECS) TYPE  WFD_KEY_TAB
    *"     VALUE(ET_CHANGED_TIMESPEC_KEYS) TYPE  WFD_KEY_TAB
    *"     VALUE(ET_RETURN) TYPE  BAPIRET2_T
    This function take time spec from data base not from cache(buffer) so provide the modified time spec in the same session.
    I need any newly created time specification detail also. So I can show all the time spec detail in my function module for any user in the same session.
    Can anyone provide the sample code for it?
    Thanks,
    Anup Garg

    Yes I can see the pattern.
    When I get the set of numbers from database UI doesn't know what is the the list of numbers database has. I need to choose some next available number that is not in database. In the list that u are talking about next available number is 7. Its something similar to when we try to create any mailid, while registration it gives some default id which is not existing which user can choose to create his mailid. How can I get similar feature?

  • How to display data in SelectOneChoice from database?

    Hi,
    I want to display data in SelectOneChoice component after fetching from database in a bean using Application module implementation class. I have two fields in my bean id and name. I want to display name in choice and in backend i want to play with the id of corresponding selected choice i.e displayed in SelectOneChoice. I am not able to bind the datacontrol with the SelectOneChoice component. I have data in my bean i.e list of id and name fetched from database.

    In my app module i have create a method which retruns UserBean in array List .
    I dropped that data control on my page as Select One Choice and bind the same.
    When i run that page I am able to see user bean object in drop down but when i try to see any specific var error occurs
    Code-
    <af:selectOneChoice value="#{bindings.return.inputValue}"
    label="#{bindings.return.label}"
    required="#{bindings.return.hints.mandatory}"
    shortDesc="#{bindings.return.hints.tooltip}"
    binding="#{backingBeanScope.backing_test12.soc1}"
    id="soc1">
    <f:selectItems value="#{bindings.return.items}"
    binding="#{backingBeanScope.backing_test12.si1}"
    id="si1"/>
    </af:selectOneChoice>
    This code works fine and drop down shows userbean .
    But when i change the code it fetch username form bean exception occurs
    Changed Code-
    <f:selectItems value="#{bindings.return.items.*Username*}"
    binding="#{backingBeanScope.backing_test12.si1}"
    id="si1"/>
    Exception-
    *[ServletContext@15368949[app:ADF module:ADF-ViewController-context-root path:/ADF-ViewController-context-root spec-version:2.5]] Servlet failed with Exception*
    java.lang.NumberFormatException: For input string: "Username"
    *     at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)*
    *     at java.lang.Integer.parseInt(Integer.java:449)*
    *     at java.lang.Integer.parseInt(Integer.java:499)*
    *     at javax.el.ListELResolver.toInteger(ListELResolver.java:373)*
    *     at javax.el.ListELResolver.getValue(ListELResolver.java:167)*
    *     Truncated. see log file for complete stacktrace*
    FYI:- This control wokrs fine when i but this data in table . Not sure about the reason for select choice :(

  • How to dynamic order of groups & How to fetch data at runtime from database

    Post Author: ferikpatel
    CA Forum: Formula
    I am using visual studio .net application having inbuilt crystal report feature. Now, what I want to do is, i have create 5 groups in crystal report, but dynamically want to change the order of those reports as per user's selection.
    How to do that?
    Also, how to fetch database item on runtime which is not selected through data expert as its relation is depends on situation. Say if one field's value is 5 than i want to get name of customer, but if same field's value is 6 than i want to get name of suppliers. In database both supplier and customers tables are different however they are connected with base table.
    I'm bit new in crystal report. Please help me out if it is possible.

    Post Author: Charliy
    CA Forum: Formula
    You don't actually change the order of the groups.  You group on a formula and change contents of the formula based on the parameter.
    IF {?Group1} = "Manager" then {table.Manager}
    else if {?Group1} = "Invoice Date" then Totext({table.InvDate},"yyyyMMdd")    note all options must be the same date type, so numbers and dates are converted
    else . . .

  • How to import data into JTable from a text file?

    thanks in advance!

    My guess is you will have to read the data in from the file, parse it, populate some vectors or something and use those vectors to instantiate the JTable. You could use FileReader to read in the data:
    FileReader in = new BufferedReader(new FileReader(file));then use StringTokenizer to parse it.
    m

  • How to get last inserted id from database

    Hello,
    In PHP Language, mysql_insert_id() gives the last inserted ID without writing any Queries in the code. Is there similar mechanism to do in Jsp page. I need to insert data in one table and in the meantime, with the last inserted ID i need to insert another sort of data in another table.
    Can u plz help me out?

    You can use Statement#getGeneratedKeys().
    The DDL should look like at least (you can use INT UNSIGNED instead, your choice):ID BIGINT AUTO_INCREMENT PRIMARY KEYBasic example:int affectedRows = statement.executeUpdate("INSERT INTO table (column1, column2) VALUES ('value1', 'value2')");
    Long insertID = null;
    if (affectedRows == 1) {
        ResultSet generatedKeys = statement.getGeneratedKeys();
        if (generatedKeys.next()) {
            insertID = new Long(generatedKeys.getLong(1));
    }Using MySQL Connector/J 5.0.

  • How to get first 50 records from database using cmp beans 2.0?

    does any body know how i should write ejb-statment to do that?
    thanks
    winnicki

    if i run method for example findAll() and thereare
    500k recods my server will by out of memory ithink.
    Yes, you are right. I know some guys who wrote
    quite a large system in that style :-)
    Of course, the application didnt work in real life.
    Customer decided to throw the system away and later
    er some other guys rewrote it ....... in .NET
    What a pity! sigh

  • How to get Date value from database and display them in a drop down list?

    Hello.
    In my Customers table, I have a column with Date data type. I want to create a form in JSP, where visitors can filter Customers list by year and month.
    All I know is this piece of SQL that is convert the date to the dd-mm-yyyy format:
    SELECT TO_CHAR(reg_date,'dd-mm-yyyy') from CustomersAny ideas of how this filtering possible? In my effort not to sound like a newbie wanting to be spoonfed, you can provide me link to external notes and resources, I'll really appreciate it.
    Thanks,
    Rightbrainer.

    Hi
    What part is your biggest problem?? I am not experienced in getting data out of a database, but the way to get a variable amount of data to show in a drop down menu, i have just messed around with for some time and heres how i solved it... In my app, what i needed was, a initial empty drop down list, and then using input from a text-field, users could add elements to a Vector that was passed to a JComboBox. Heres how.
    package jcombobox;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    public class Main extends JApplet implements ActionListener {
        private Vector<SomeClass> list = new Vector<SomeClass>();
        private JComboBox dropDownList = new JComboBox(list);
        private JButton addButton = new JButton("add");
        private JButton remove = new JButton("remove");
        private JTextField input = new JTextField(10);
        private JPanel buttons = new JPanel();
        public Main() {
            addButton.addActionListener(this);
            remove.addActionListener(this);
            input.addActionListener(this);
            buttons.setLayout(new FlowLayout());
            buttons.add(addButton);
            buttons.add(remove);
            add(dropDownList, "North");
            add(input, "Center");
            add(buttons, "South");
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == addButton) {
                list.addElement(new SomeClass(input.getText()));
                input.setText("");
            } else if (e.getSource() == remove) {
                int selected = dropDownList.getSelectedIndex();
                dropDownList.removeItemAt(selected);
        public void init(String[] args) {
            setSize(400,300);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(new Main());
    }And that "SomeClass" is show here
    package jcombobox;
    public class SomeClass {
        private String text;
        public SomeClass(String input) {
            text = input;
        public String toString() {
            return text;
    }One of the things i struggled a lot with was to get the dropdown menu to show some usefull result. If the list just contains class references it will show the memory code that points to that class. Thats where the toString cones in handy. But it took me some time to figure that one out, a laugh here is welcome as it should have been obvious :-)
    When the app is as simple as this one, using a <String> vector would have been easier, but this is just to demonstrate how to place classes in a vector and get some usefull info out of it, hope this answered some of your question :-)
    The layout might have been easier to write, than using the toppanel created by the JApplet and then the two additional JPanels, but it was just a small app brewed together in 15 minutes. Please comments on my faults, so that i can learn of it.
    If you need any of the code specified more, please let me know. Ill be glad to,

  • How to get data from database to JComboBox

    hi
    i am trying to get data which is in database. here the problem is i am getting only one row in the JcomboBox
    i want all data just like list. i dont know how to get that . below is the code plz any one help me....
    import javax.swing.*;
    import javax.swing.JList.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.String.*;
    import java.lang.Integer.*;
    import java.sql.*;
    public class customer_code extends JFrame implements ActionListener
    Container c=getContentPane();
    JLabel customer_code=new JLabel("Customer Code and Name");
    customer_code()
    super("Customer Details");
    setSize(300,250);
    setVisible(true);
    setLayout(null);
    setLocation(430,310);
    Font f=new Font("SansSerif",1,16);
    Font f1=new Font("SansSerif",0,14);
    customer_code.setBounds(10,20,250,30);
    add(customer_code);
    customer_code.setFont(f);
    ResultSet rs=null;
    String j=null,k=null;
    try
    System.out.println("MySQL Connect Example.");
    Statement st=null;
    Connection con=null;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbc:odbc:project","vikky","vishu");
    System.out.println("Connected to the database");
    st=con.createStatement();
    rs=st.executeQuery(" select code as c,Customer_name as n from customer_details ");
    while(rs.next())
    j=rs.getString("c");
    k=rs.getString("n");
    System.out.println(j);
    System.out.println(k);
    String[] names = new String[] {j,k};
    JComboBox comboBox = new JComboBox(names);
    add(comboBox);
    comboBox.setBounds(25,60,250,50);
    comboBox.setFont(f);
    comboBox.addActionListener(this);
    comboBox.setMaximumRowCount(10);
    con.close();
    System.out.println("Disconnected from database");
    catch (Exception e)
    e.printStackTrace();
    public void actionPerformed(ActionEvent event)
    if ("comboBoxChanged".equals(event.getActionCommand()))
    System.out.println("User has selected an item from the combo box.");
    JComboBox comboBox = (JComboBox) event.getSource();
    if(comboBox.getSelectedItem().equals("None"))
    public static void main(String agr[])
    customer_code cd=new customer_code();
    }

    r035198x wrote:
    Also separate that database code from interface display code.
    You should never access the database on the EDT.
    See [Doing Swing Right|http://bytes.com/topic/java/insights/853297-doing-swing-right] for more details.
    Yes! By the time you are working with Swing and JDBC you should already know how to structure code. If not, then you are not ready for these topics and you've jumped the gun.

  • How i get data in matrix grid from A/P Invoice

    How i get data in matrix grid from A/P Invoice before click add button

    Hi,
    Are you trying to read the data in the matrix of a system form? Then you only have to look for the matrix with the ID you can see by visualising the System Information in B1 and then directly read from the matrix cells (using columns element in matrix), the DBDataSources are not filled in until the document has been added to the database.
    There are many messages in this forum talking about how to read information in matrix item, just make a search for it.
    Hope it helps
    Trinidad.

  • How to get  data with the raw pattern from resultset ?

    would you tell me how to get data with the raw pattern from resultset ?
    thank you in advance!
    longgger2000

    I tried getBytes() and getObject()
    , but I can not get the right result , for example the
    data in oracle database is 01000000DFFF, when In used
    the method of getBytes() and getObject(), I get the
    result of [B@1c2e8a4, very different , please tell me
    why !
    thank you
    longgger2000
    [B is byte arrayseem that it return an bytes array for you.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to get Date Format from Local Object.

    Hi All,
    I am new to Web Channel.
    I need to know Date format From date of locale.
    suppose there is a date "01/25/2010" date in date field I want to get string "mm/dd/yyyy". Actually I have to pass date format to backend when I call RFC. 
    Is there any way to get Date format from "Locale" object. I should get date format for local object
    I get local object from "UserSessionData" object but how to get Date format from it.
    I am not looking for Date value. I am looking for current local date format ("mm/dd/yyyy or dd/mm/yyyy or mon/dd/yyyy) whatever local date format.  I could not find example which show how to get date format from "Locale" object.
    Any help will be appreciated with rewards.
    Regards.
    Web Channel

    Hi,
    You can get it from "User" or "Shop" business object.
    Try to get User or Shop Business Object as shown below.
    BusinessObjectManager bom = (BusinessObjectManager) userSessionData.getBOM(BusinessObjectManager.ISACORE_BOM);
    User user = bom.getUser();
    char decimalNotation = user.getDecimalPointFormat().getGroupingSeparator();
    If you are seeing "1,234.00" then above code will return "."
    I hope this information help you to resolve your issue.
    eCommerce Developer.

  • For some reason the system is telling me my birth date is wrong when it's not and it won't let me proceed to reset my password. Can someone tell me how to get a "real" person from tech on line?

    For some reason the system is telling me my birth date is wrong when it's not and it won't let me proceed to reset my password. Can someone tell me how to get a "real" person from tech on line?

    contact itunes support

Maybe you are looking for

  • Some questions for ressources provisionning.

    Hello people. I'm currently playing around with LDoms on a new brilliant shiny T5520 and I have some questions about. My actual configuration is the following: - 1 T5520 Server with 32 Gb RAM and a 8 cores 64 threads Niagara T2 - 4 SAS 143 Gb disks o

  • Problem in calling rsh command Please help......

    hi, I want to execute some commands on unix through java, for this i want to run my program simulataneously on differnt machines so that i get data to compare. I think i have to invoke the rsh command with the machine name for it but it is giving err

  • Password problems.

    I have noticed this problem in totally disparate situations on line. E-mail main website for reset password to be sent. A little chain of gobbledegook duly arrives which opens the site. On using the edit facility to get back to a more useful password

  • Photo Storage

    When I upgraded to Iphoto 8 the iphoto folder in my pictures folder disappeared. I used to be able to go to the folder and get the pictures when I was working in other programs and such but it is gone, does anyone know where the photos are now stored

  • Method changes

    Hi I have another question in mehtod changes. In period 1 my investment in the subsidiary is 30. So the COI mehtod is equity in period one and it is first consolidation. In period 2 i have acquired another 25% with the result my investment has gone b