Home Answers Viewqa JDBC Connecting JTable to database

 
 


Divya
Connecting JTable to database
3 Answer(s)      3 years and 3 months ago
Posted in : JDBC

Hi..
I am doing a project on Project Management System for which i created the user interfaces..
I have a user interface in which i have used JTables..
Now my problem is I dont know how to how to store this JTable content in my database table..
This is a very important table of my priject..
Please help me out..
View Answers

April 2, 2010 at 10:10 AM


Hi Friend,

Try the following code:

import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;

public class InsertJTableDatabase{
JTable table;
JButton button;
public static void main(String[] args) {
new InsertJTableDatabase();
}

public InsertJTableDatabase(){
JFrame frame = new JFrame("Getting Cell Values in JTable");
JPanel panel = new JPanel();
String data[][] = {{"Angelina","Mumbai"},{"Martina","Delhi"}};

String col[] = {"Name","Address"};
DefaultTableModel model = new DefaultTableModel(data, col);
table = new JTable(model);
JScrollPane pane = new JScrollPane(table);
button=new JButton("Submit");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
PreparedStatement pstm;
ResultSet rs;
int index=1;
int count=table.getRowCount();

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect =DriverManager.getConnection("jdbc:odbc:access");
for(int i=0;i<count;i++){
Object obj1 = GetData(table, i, 0);
Object obj2 = GetData(table, i, 1);
String value1=obj1.toString();
String value2=obj2.toString();

System.out.println(value1);
System.out.println(value2);

pstm=connect.prepareStatement("insert into data values(?,?)");
pstm.setString(1,value1);
pstm.setString(2,value2);

index++;
}
pstm.executeUpdate();
}
catch(Exception e){}
}
});
panel.add(pane);
panel.add(button);
frame.add(panel);
frame.setSize(500,250);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public Object GetData(JTable table, int row_index, int col_index){
return table.getModel().getValueAt(row_index, col_index);
}
}

Thanks

April 2, 2010 at 10:24 AM


Hi Friend,

Make one change to above code, put pstm.executeUpdate(); inside the for loop before incrementing 'index' variable.

Thanks

February 10, 2011 at 5:24 PM


import java.awt.print.*; import java.awt.*; import java.sql.*; import java.util.*; import javax.swing.*; import java.awt.event.*; import javax.swing.table.*; import java.io.*; import javax.swing.JFileChooser; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JDialog; import javax.swing.JFileChooser;

class JT implements ActionListener {

JButton b=new JButton("Print"); 
Vector JButton= new Vector();

JFileChooser fc;
static private final String newline = "\n";
JButton b1=new JButton("Save");
JTextArea log;
JTable table ;

File file;

public JT()
{

//***********Button*****************
//b.addActionListener(printAction); 
b.setBounds(10,100,100,50);



b1.setBounds(10,200,100,50);    
b1.addActionListener(this);

/* ActionListener printAction = new ActionListener() { public void actionPerformed(ActionEvent e) {

    try 
{
       table.print();
    }
 catch (PrinterException pe) 
{
      System.err.println("Error printing: " + pe.getMessage());
    }
  }

};*/ //************

Vector columnNames = new Vector();
Vector data = new Vector();
JPanel p=new JPanel();

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:supermarket.mdb");
String sql = "Select * from bill data";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) 
{
columnNames.addElement( md.getColumnName(i) );

}

while (rs.next()) 
{
    Vector row = new Vector(columns);

    for (int i = 1; i <= columns; i++)
    {
    row.addElement( rs.getObject(i) );
    }

    data.addElement( row );
}

rs.close();
stmt.close();

} catch(Exception se) { //System.out.println(e); }

table= new JTable(data, columnNames); table.setVisible(true);

TableColumn col; for (int i = 0; i < table.getColumnCount(); i++) { col = table.getColumnModel().getColumn(i); col.setMaxWidth(250); } JScrollPane scrollPane = new JScrollPane( table ); p.add( scrollPane ); JFrame f=new JFrame(); f.add(p); p.add(b); p.setBackground(Color.pink); p.add(b1); f.setSize(600,400); f.setVisible(true);

fc = new JFileChooser();

}//constructor

public void actionPerformed(ActionEvent e) {

if (e.getSource() == b1)
{

int returnVal; int flag; do { flag=0; final JFileChooser fc = new JFileChooser(); file = fc.getSelectedFile(); //here when i put it in do while loop it opens from MY DOCUMENTS which i dont want..it must retain its previous location returnVal = fc.showSaveDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { try {

file = fc.getSelectedFile();

String[] files=new File(file.getParent()).list(); for(int i=0;i

    if (returnVal == JFileChooser.APPROVE_OPTION)
    {
        try
        {
        String fileName = file.getName();
        Writer output=null;
        output=new BufferedWriter(new FileWriter(file));
        //output.write(textArea.getText());
        output.close();
        }
        catch(Exception e2){};
    }

String filename =file.getName();

     try {  


    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));  

         oos.writeObject(table);  

         oos.close();  

         }  

     catch(IOException fe) 
     {  

         System.out.println("Problem creating table file: " + fe);  
         return;  

         }  

     System.out.println("JTable correctly saved to file " + filename);  


}

}

public static void main(String[] args)
{
JT hh=new JT();
}

} //now you can access definately access database just type your own database name and see magic here 'supermarket' is my database name and 'bill' is my table name









Related Pages:
Connecting JTable to database - JDBC
Connecting JTable to database  Hi.. I am doing a project on Project... to store this JTable content in my database table.. This is a very important... InsertJTableDatabase{ JTable table; JButton button; public static void main(String
JTable
JTable  i want to delete record from JTable using a MenuItem DELETE. and values of JTable are fetched from database....please reply soon
JTable
JTable  Hello, i cannot display data from my table in the database to the cells of my JTable. please help me
jtable
jtable  how to get the values from database into jtable and also add a checkbox into it and then when selected the checkbox it should again insert into database the selected chewckbox.plzz help
jtable
jtable  hey i have build a form and i m also able to add data from database to jtable along with checkbox.the only problem is that if i select multiple checkboxes the data doesnt get inserted into new database and if only one
Connecting to a database through the Proxy.
Connecting to a database through the Proxy.  Connecting to a database through the Proxy I want to connect to remote database using a program that is running in the local network behind the proxy. Is that possible
jtable
jtable  i have build an application and i retrieve data from the database and store it in jtable.now i have to make a checkbox column in each row... { private Vector<Vector<String>> data; //used for data from database
connecting with database - Struts
connecting with database  I am creating an application where when jsp page is displayed, it contains the combo box where data is populated from the database.it has 3 buttons and the functionality for all buttons is different
connecting to database - Struts
connecting to database  Hi I am having problems with connection to MS SQL Server 2005 database. My first is what do i write in struts... information via the database in my web page. Thanks Tayo  Hi friend
Connecting code of reset password to database
Connecting code of reset password to database  connecting code of reset password to database
Connecting to MYSQL Database in Java
Connecting to MYSQL Database in Java  I've tried executing the code... to the database"); conn.close(); System.out.println("Disconnected from database"); } catch (Exception e) { System.out.println("Error
connecting databases
connecting databases  I need to connect mysql on 2 or more remote pc'c. how can i giv the ip address for 2 or more systems. is it possible to connect to the required systems by user specifying the database and table name my
connecting to access database
connecting to access database  print("code sample");Hi I Write java... this there is no error but my data is not going to my Acess Database. There is working... Access Driver(*.mdb) Select database name and Create the DSN name (e.g access
Connecting Oracle database with struts - Struts
Connecting Oracle database with struts  Can anyone please provide me some solutions on Connection between Oracle database and struts
Problems connecting to a database. Java/SQLite
Problems connecting to a database. Java/SQLite  `print("try { con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite"); } catch... on an SQL database but i am having problems connecting to it, I think the problem
JAVA DATABASE CONNECTION WITH JTABLE
JAVA DATABASE CONNECTION WITH JTABLE  HOw To Load Database Contents From Access Database to JTable without using Vector
connecting to a database dynamically - JSP-Servlet
connecting to a database dynamically   abc.html :- abc.jsp :- Above code gives the following... with database dynamically. Plz debug the code and explain the reasons for the exception
code for connecting reset password code to database.
code for connecting reset password code to database.  code for connecting reset password code to database.   Hello Friend, Do you want to change your password and update the password to database
Connecting to Database from a hyperlink in JSP - JSP-Servlet
Connecting to Database from a hyperlink in JSP  How can I connect to database by clicking on a hyperlink in a JSP Page.Can you please give me sample... which is connect to database using jdbc database
jsp -sevlet connecting to database using dropdown
jsp -sevlet connecting to database using dropdown  How can I get my dropdown list from oracle database and then submit it to another table in JSP. I... to the database and fetches an array of strings from a database table and then sends
jtable query
jtable query  I need a syntax...where i could fetch the whole data from the database once i click the cell in jtable...and that must be displayed in the nearby text field which i have set in the same frame
java jtable
java jtable  Hello Sir, I am developing a desktop application in which i have to display database records in jtable .now I want to read only... that in jtable. plz help me with the code
ABOUT Jtable
ABOUT Jtable  My Project is Exsice Management in java swing Desktop Application. I M Use Netbeans & Mysql . How can retrive Data in Jtable from Mysql Database in Net Beans
Connecting to the Database Using JDBC and Pure Java driver
Connecting to the Database JDBC Driver In our search engine we are using MySQL database server and MM.MySQL Driver for connecting our application to the database. MM.MySQL Driver
Connecting jboss with sql 2005 - Struts
Connecting jboss with sql 2005  Hai, i have project that was developed in struts,backed is sqlserver 2005 and and i am using jboss. I want to connect another database (sqlserver 2005) with my project.could u please help me
JTable - JDBC
JTable   Hello..... I have Jtable with four rows and columns and i have also entered some records in MsSql database. i want to increase Jtable's... 10 records in the database the rows should increase with the data. i want
adding data to the database with the use of jtable - Java Beginners
adding data to the database with the use of jtable  how can i add data to the database with the use of jtable. and also can able to view the records in the database in the table.. tnx :G
adding data to the database with the use of jtable - Java Beginners
adding data to the database with the use of jtable  how can i add data to the database with the use of jtable. and also can able to view the records in the database in the table.. tnx :G
connecting servlet to db2 - JSP-Servlet
connecting servlet to db2  Hello sir, Iam new to db2.so I would like... the configuration we need to be done before connecting to the db2(such as what path we have to set and all).  If u are using the oracle Database 9i
connecting jsp to mysql - JSP-Servlet
connecting jsp to mysql  Hi, i am working on 'Web application development' project that uses JSP, MySQL and tomcat.i am not able to connect to the mysql database through jsp. After downloading the mysql-connector-java-5.0  
JTable in java - Java Beginners
JTable in java  Sir , I have created an application with a JTable showing the records of an MS Access database table. On the same frame I have... given one , JTable table; ....... .... table.print(); Here the error
doubt in connecting to mysql in flex - XML
doubt in connecting to mysql in flex  The ?Create application from database? is a Flex 3 feature that enable you to create simple applications in few... of all you have tosetupyourMySql datasource by creating a database and a table
doubt in connecting mysql in flex - XML
doubt in connecting mysql in flex  The ?Create application from database? is a Flex 3 feature that enable you to create simple applications in few... of all you have tosetupyourMySql datasource by creating a database and a table
Java JTable
database. i want once again i am open that application the change cell foreground
java connecting to oracle db - JDBC
java connecting to oracle db  how to connect oracle data base...) Connect to database:*********** a) If you are using oracle oci driver,you have... is the host,3306 is the port, roseindia is the database and root is the username and password
Jtable with servlet - Java Beginners
and will submit the values which will be saved in the database(MySql).At the same time I want the JTable to display the record saved in the database,the JTable...Jtable with servlet   Actually I have embedded the html
jtable query compare with date
in which i have to display database records in jtable .now I want to transfer particular data which month is over to another jtable. plz sir give me the code...jtable query compare with date  how to transfer daytable data
jtable query compare with date
in which i have to display database records in jtable .now I want to transfer particular data which month is over to another jtable. plz sir give me the code...jtable query compare with date  how to transfer daytable data
jtable query compare with date
in which i have to display database records in jtable .now I want to transfer particular data which month is over to another jtable. plz sir give me the code...jtable query compare with date  how to transfer daytable data
jtable displays search results
jtable displays search results   hi sir can u send me full source code for displaying search results into jtable from database n jtable n search button must be within same frame but in different Panel and the size of the frame
JTable populate with resultset.
JTable populate with resultset.  How to diplay data of resultset using JTable?   JTable is component of java swing toolkit. JTable class is helpful in displaying data in tabular format. You can also edit data. JTable
how update JTable after adding a row into database
in JTable, and it's OK, but after adding a row into database table does't update. How update JTable after adding a row into database? package djilepak.javaclss.for... which shows data in JTable from database import java.awt.*; import
JTable - Swing AWT
JTable  Hi Deepak, i m facing a problem with jtable. i am able to display the values from the database into the jtable. but not able to modifying multiple cell values in a row. also i want to store those modified
Show multiple identical rows into JTable from database
Show multiple identical rows into JTable from database In this tutorial, you will learn how to display the multiple rows from database to JTable. Here... rows from database on clicking search button to jtable. The given code accepts
JTable - Java Beginners
JTable Search Filter  Hi,i wanted to add a search filter in my JTable application.Thanks in Advance!!  i'means using database access,when...=============================================================================i press the enter button into JTable cell and focus
Connecting to MySQL database and retrieving and displaying data in JSP page
Connecting to MySQL database and retrieving and displaying data in JSP page...;org.gjt.mm.mysql.Driver").newInstance(); Connecting to your database To connect...; This tutorial shows you how to connect to MySQL database and retrieve the data
Connecting to a MySQL Database in Java
Connecting to a MySQL Database in Java   ... data form MySQL database. We are going to make a program on connecting to a MySQL... and APIs with which we can make use of the database as we like. Database plays
how to make JTable to add delete and update sql database table
how to make JTable to add delete and update sql database table  Hello all I want to know how to make JTable to act actively to add delete and update database table. i am struck ed here from long time please help me