Connecting java to Excel

HI
Can anyone help me about the code.
I got the Exception:
Error while inserting to excel sheet!!!
java.sql.SQLException:[Microsoft][ODBC Excel Driver]Operation must use an updateable query.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class InsertExcel
static JFrame frame;
static JPanel panel;
static JTextField textuserid;
static JTextField textfirstname;
static JTextField textlastname;
static JButton submit;
static JButton exit;
public static void main(String args[])
frame = new JFrame("Inserting to excel sheet");;
panel = new JPanel();
JLabel labeluserid = new JLabel("User id ");
JLabel labelfirstname = new JLabel("First Name");
JLabel labellastname = new JLabel("Last Name");
textuserid = new JTextField(20);
textfirstname = new JTextField(20);
textlastname = new JTextField(20);
submit = new JButton("Submit to Excel sheet");
exit = new JButton("Exit");
panel.add(labeluserid);
panel.add(textuserid);
panel.add(labelfirstname);
panel.add(textfirstname);
panel.add(labellastname);
panel.add(textlastname);
panel.add(submit);
panel.add(exit);
frame.getContentPane().add(panel);
frame.setSize(1024,100);
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
submit.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
     try
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          Connection con = DriverManager.getConnection("jdbc:odbc:population");
          PreparedStatement stat2 = con.prepareStatement("insert into [Sheet1$ (USERID,FIRST_NAME,LAST_NAME) values (?,?,?)");
          stat2.setString(1,textuserid.getText());
          stat2.setString(2,textfirstname.getText());
          stat2.setString(3,textlastname.getText());
          stat2.executeUpdate();
          JOptionPane.showMessageDialog(frame,new String("Successfully entered to excel sheet !!!"));
     catch(Exception e1)
          JOptionPane.showMessageDialog(frame,new String("Error while inserting to excel sheet !!! \n" +
e1));
exit.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ex)
     System.exit(0);
Message was edited by:
lesbon

This works fine for me. Adapt it.
import java.sql.*;
public class ExcelInsert
   public static final String DEFAULT_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
   public static final String DEFAULT_URL = "jdbc:odbc:DRIVER={Microsoft Excel Driver (*.xls)};DriverID=22;READONLY=false;DBQ=";
   public static final String DEFAULT_PATH = "C:\\Documents and Settings\\Michael\\My Documents\\Projects\\Java\\Forum\\data\\ExcelInsert.xls";
   private static final String DEFAULT_SQL = "INSERT INTO [SHEET1$] VALUES(?, ?, ?)";
   private Connection conn;
   public static void main(String[] args)
      Connection c = null;
      try
         c = createConnection(DEFAULT_DRIVER, DEFAULT_URL+DEFAULT_PATH);
         ExcelInsert inserter = new ExcelInsert(c);
         String v1 = ((args.length > 0) ? args[0] : "foo");
         String v2 = ((args.length > 1) ? args[1] : "bar");
         String v3 = ((args.length > 2) ? args[2] : "baz");
         int numRows = inserter.insert(v1, v2, v3);
         System.out.println("# rows inserted: " + numRows);
      catch (Exception e)
         e.printStackTrace(System.err);
      finally
         close(c);
   public static Connection createConnection(String driver, String url) throws SQLException, ClassNotFoundException
      Class.forName(driver);
      return DriverManager.getConnection(url);
   public ExcelInsert(Connection conn)
      this.conn = conn;
   public static void rollback(Connection c)
      try
         if (c != null)
            c.rollback();
      catch (SQLException e)
         e.printStackTrace();
   public static void close(Connection c)
      try
         if (c != null)
            c.close();
      catch (SQLException e)
         e.printStackTrace();
   public static void close(Statement s)
      try
         if (s != null)
            s.close();
      catch (SQLException e)
         e.printStackTrace();
   public int insert(String a1, String a2, String a3) throws SQLException
      int numRows = 0;
      PreparedStatement stmt = null;
      try
         stmt = this.conn.prepareStatement(DEFAULT_SQL);
         stmt.setString(1, a1);
         stmt.setString(2, a2);
         stmt.setString(3, a3);
         numRows = stmt.executeUpdate();
      catch (SQLException e)
         e.printStackTrace();
      finally
         close(stmt);
      return numRows;
}%

Similar Messages

  • Connect java to php web page

    Hello...
    I am new in this forum, so I am sorry if I post my question in wrong place.
    I have php web page and want to call my java classes i.e connect java to php. My java code will read from file some info. then will organize these info. finally, the java will write the organized info. in file, the php will display the content of the file.
    can help me please to achieve this goal...
    thanks in advance
    ibtesam saleh

    I do not how to use JPoller, put it looks very advanced.
    Or you can use a simple code in (java/perl/c/what so every u know)
    void main(){
    while (true) {
    checkDirectoryAndReadNewCommandsAndWriteNewOutputs();
    Thread.sleep(waitTime);
    }and put your program on your windows/linux startUp
    Or you can learn using sockets in java and write your own html service with port 80 (I did some experiments)
    Or you can try to use WebService example from Netbeans program (I tried it worked for me)
    Or you can learn J2EE (I have never find the time to look at)
    Or ... many ideas, to time :)

  • Can' t connect Java with MySQL

    My goal is to connect Java with MySQL. I found many solutions on Internet, but I always get the same mistake:
    SQLException: No suitable driver
    SQLState: 08001
    VendorError: 0MySQL works fine alone or with php.Only thing left me to think is that the installed versions are not compatible for this mysql-connector-java-5.0.4
    I don't believe that could be a reason.
    Installed versions are:
    Apache Tomcat 5.5.20 Server
    Apache HTTP Server 2.2.4
    PHP 5.2.0
    MySQL 5.2
    jre 1.5.0_11
    jdk1.5.0_11
    Apache Tomacat JK2 connector Version: 1.2.20 File Name: mod_jk-apache-2.2.3.so
    mysql-connector-java-5.0.4
    I also set connector in class path: C:\mysql-connector-java-5.0.4;C:\mysql-connector-java-5.0.4\mysql-connector-java-5.0.4-bin.jar;C:\mysql-connector-java-5.0.4\src\com\mysql\jdbc
    For installation I used manulas from:
    http://apacheguide.org/jsp.php
    http://doc.51windows.net/mysql/?url=/MySQL/ch23s03.html
    Here is also a test code in java:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
       public class Connect
           public static void main (String[] args)
               Connection conn = null;
               try {
        conn =
           DriverManager.getConnection("jdbc:mysql://localhost/first_test" +
                                       "user=monty&password=greatsqldb");
        // Do something with the Connection
    } catch (SQLException ex) {
        // handle any errors
        System.out.println("SQLException: " + ex.getMessage());
        System.out.println("SQLState: " + ex.getSQLState());
        System.out.println("VendorError: " + ex.getErrorCode());
       }i'm desperate, please help or tell me someone who'll know the answer.
    Thank You in advance

    hey buddy .. it seems yr code is wrong .. in getconnection () method u should also specify the port ,which u r not doing ...
    the default port for MySQL is 3306 ... see below i am giving you a sample code ... its working fine .. and dont forget to put the MySQL driver jar path in to classpath and also copy the jar into common/lib folder of your tomcat ....
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class MySQLConnectionTest {
         public static void main(String[] args) {
    new MySQLConnectionTest().connTest();
    public void connTest() {
              String tableName = "portfolio"; //change as per setting
              String hostName = "10.81.9.39"; // please change for the target database ip or hostname
              String dbPort = "3306"; //change if not using the default
              String dbName = "tradingsystem"; //change as per the given DB name
              String username = "root"; //change as per setting
              String password = "password"; //change as per setting
              System.out.println("before try");
              Double data=0.0;
         Double data1=0.0;
              try {
    Class.forName("org.gjt.mm.mysql.Driver");
                   System.out.println("before driver manager");
    Connection conn = DriverManager.getConnection("jdbc:mysql://"+hostName+":"+dbPort+"/"+dbName, username, password);
    String query1 = "select * from "+tableName+" where User_id='trader1' and Stock_Type='Equity'";
    System.out.println("quesry1="+query1);
    Statement stmt = conn.createStatement();
    ResultSet rs1 = stmt.executeQuery(query1);
    while(rs1.next())
         System.out.println("hiiiiii for rs1");
         System.out.println(rs1);
         Quantity=(Integer)rs1.getObject(5);
         MarketPrice=(Double) rs1.getObject(8);
         data=Quantity*MarketPrice;
         data1+=data;
         System.out.println("data1="+data1);
         i=0;
    rs1.close();
    stmt.close();
    conn.close();
    } catch (ClassNotFoundException e) {
    e.printStackTrace(System.err);
    } catch (SQLException e) {
    e.printStackTrace(System.err);
    i hope it will work for u...
    cheers,

  • Ghost connections "Java(TM) 2 Platform Standard Edition"

    We have a server application with multiple threads each using JDBC connections. On the Database server (MS SQL Server 7) we notice more and more connections with the SQLQueryAnalyzer-ProgramName "Java(TM) 2 Platform Standard Edition". But all our (known) connections have custom names or the default name of the JDBC driver (jTDS). The developer of jTDS answered that the driver only have connections that are requested by the application. But we don't have connections named dbc connections "Java(TM) 2 Platform Standard Edition" ... ?

    We don't use an application server, it's just a plain Java application. No frameworks and only 3rd party libs that don't handle any database connection - and the JDBC driver jTDS. As one of the developers got very angry about my bug report, because he insists that it's not the fault of jTDS, I have to rule out jTDS. That would mean that it's somewhere in my application. But I just have 1 single class that actually creates a JDBC connection, so it's not hard to debug this. And I can't see any additional connections as all of my connections get specific names and not "Java(TM) 2 Platform Standard Edition".
    I searched all source code of the Java SDK, jTDS and my source code for occurences of "Java(TM) 2 Platform Standard Edition" and can't find any. I hoped that somebody knows who is using this string (and when). It sounds like general Java (SDK/JRE) is setting this name, but I haven't found it.

  • BAPI step by step to connect JAVA for catsdb table

    BAPI step by step to connect JAVA for catsdb table,
    Points will be rewarded,
    full points with example of catsdb table in bapi for JCO JAVA
    Thank you,
    Regards,
    Jagrut BharatKumar Shukla

    Hi,
    Check the thread..
    https://forums.sdn.sap.com/click.jspa?searchID=3587428&messageID=3647918
    Regards,
    Omkar.

  • NullPointerException at com.sun.jndi.ldap.Connection.run(Connection.java:52

    We are using the Sun jndi 1.2.1 files from a Java client to
    access the IBM SecureWay Directory 3.2 server. Our test case is
    retrieving entries using the ctx.getAttributes (String, String[])
    method. Occasionally we are receiving the following error.
    java.lang.NullPointerException
    at com.sun.jndi.ldap.Connection.run(Connection.java:525)
    at java.lang.Thread.run(Thread.java:481)
    The java.lang.NullPointerException is coming from the Sun JNDI file.
    Our program is not catching this exception.
    Has anyone seen this problem before and have any ideas on how this can be resolved?

    Download and use LDAP 1.2.3 or JDK 1.3.1.
    The problem should go away.

  • The dreaded "Cannot connect to Microsft Excel..."

    Hello everyone,
    First time back in a couple of years apart from the sporadic visit. I am upgrading to SAP Dashoards 4.1 and currently running the SP5 trial.
    After trying a couple of templates to make sure all was ok, and it seemed to work fine, I first got a runtime error. Now I get the dreaded 3Cannot connect to Microsoft Excel...programme must close." error. I was running Dashboards standalone, as Admin. I don't seem to be able to get back in.
    I am finding it difficult to find my way around the forum format, but I did do a search and found a post that suggested Office 2013 was the issue (supposedly to be solved in SP5 but it obviously hasn't been) and it was best to downgrade Office. Surely there must be a more up to date answer.
    Would you please let me know what I should do? Or of course, point me in the direction of a prior post (I will get to grips with the way the forum displays and the search function, I promise).
    Thank you for your suggestions.
    Chris
    Windows 8.1 x64
    Excel 2013
    Dashboards 4.& SP5 Trial

    Hi Chris,
    Office 2013 is supported with Dashboards 4.1.
    Check if the issue is intermittent and if not then try below steps.
    Hi Petrut,
    Rename the strat page in folder Dashboards Installation dir\Program files\SAP BusinessObjects\Xcelsius 4.0\assets\startPage
    Also set value of
    HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer->NoRecentDocsHistory
    value to 0.
    Also uninstall microsoft office and install it once again.
    If it again fails then try below steps.
    1.Turn off the anti-virus and the firewall.
    2.Uninstall the Dashboards.
    3.Then take the backup of the registry.
    4.In the registry please go to hkeylocalmachine--->Software------>Wow6432node------>SAP BusinessObjects------>SuiteXI 4.0------>Xcelsius .Delete this Xcelsius folder
    5.Change the user account control settings to never notify in case when you are using Windows 7.
    6.Check in program files if there are any leftover installation folders for Xcelsius.If so delete them
    7.Run the setup by running it as administrator.
    8.Please use the key for the departmental edition of Dashboards.
    Regards,
    Amit Kulkarni
    Support Engineer
    SAP Active Global Support

  • How to connect Java and Microsoft SQL Server 2000

    hi,
    could anyone please teach me how to connect Java and SQL Sever 2000?? if possible could you guys provide me with an example??? i could hardly find any relevant resources about it...
    Thanks ~!

    thanks for the information...
    by the way hv any working module on it?? i'm new to
    both Java and Microsoft SQL Server... Thanks againFirst things first... you should read this:
    http://java.sun.com/docs/books/tutorial/jdbc/
    This is microsofts official JDBC Driver: http://www.microsoft.com/sql/downloads/jdbcregister.asp
    Install it and the documentation has some usage examples

  • An error occured when connecting java with Ms Access

    Hello Everybody
    I am a new developer in java and want to connect java with Microsoft Access
    i am using JCreator LE
    My code is to insert 3 records for 3 members and then save them in DB and retrieve the information
    Here is the code
    import java.sql.*;
    public class Project3 {
        public static void main(String[] args) {
             try {
                  System.out.println("Beginning Connection");
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                String accessFileName = "Information";
                String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ="+accessFileName+".mdb;PWD=";
                Connection con = DriverManager.getConnection( connURL ,"","");
                Statement stmt = con.createStatement();
                System.out.println("Connection done successfully");
                stmt.execute("Create table Member(Name String,ID Integer)");
                stmt.execute("insert into Member values ('Joe','1234')");
                stmt.execute(" select * from Member");
                ResultSet rs=stmt.getResultSet();
                if (rs != null)
                     while (rs.next()){
                          System.out.println("Name: "+rs.getString("Name")+ "ID: " + rs.getString("ID"));
                stmt.close();
                con.close();
                catch (Exception e) {
                System.out.println("An error Occurred in Connecting with the DB " );
    }and the error is
    Beginning Connection
    Connection done successfully
    An error Occurred in Connecting with the DB
    it didn't insert information in the DB

    Well, thank u i have traced the error and fx it
    but
    how to modify the code and keep the user entering 3 values and search for the entered values??
    Here is the correct code
    import java.sql.*;
    public class Project3 {
        public static void main(String[] args) {
             try {
                  System.out.println("Beginning Connection");
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                String accessFileName = "jdbc:odbc:Project";
                String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ="+accessFileName+".mdb;PWD=";
                Connection con = DriverManager.getConnection( accessFileName);
                Statement stmt = con.createStatement();
                System.out.println("Connection done successfully");
                stmt.execute("Create table Member(Name String,ID Integer)");
                stmt.execute("insert into Member values ('Joe','1234')");
                stmt.execute(" select * from Member");
                ResultSet rs=stmt.getResultSet();
                if (rs != null)
                     while (rs.next()){
                          System.out.println("Name: "+rs.getString("Name")+ "ID: " + rs.getString("ID"));
                stmt.close();
                con.close();
                catch (Exception err) {err.printStackTrace();}
    }

  • Unable to connect java to mysql

    I have installed mysql on my linux machine (i didnt modify any default configuration settings, just using the default settings). And in my lan, from another machine in windows from my java code i am trying to connect to mysql of linux, but donno why i get connection refused error. Can someone help me to figure what the steps i am missing or need to do?

    Thanks for your reply. I do not have any network managers. I have installed mysql on my linux machine and also started mysql. Now in remote machine i have downloaded mysql-connector-java-5.0.4-bin.jar file and using this jar file my java code is trying open a connection to mysql.
              try {
                   Class.forName("com.mysql.jdbc.Driver");
              }catch(Exception ce) {ce.printStackTrace();}
              try {
                   Connection conn = DriverManager.getConnection("jdbc:mysql://192.168.20.160:3306/mysql","root","new_password");192.168.20.160 is the linux machine where mysql is running.
    But of no use, i get connection refused error. following is stacktrace
    SQLException: Communications link failure due to underlying exception:
    ** BEGIN NESTED EXCEPTION **
    java.net.SocketException
    MESSAGE: java.net.ConnectException: Connection refused: connect
    STACKTRACE:
    java.net.SocketException: java.net.ConnectException: Connection refused: connect
         at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:156)
         at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
         at com.mysql.jdbc.Connection.createNewIO(Connection.java:2666)
         at com.mysql.jdbc.Connection.<init>(Connection.java:1531)
         at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266)
         at java.sql.DriverManager.getConnection(DriverManager.java:525)
         at java.sql.DriverManager.getConnection(DriverManager.java:171)
         at TestDriver.main(TestDriver.java:11)
    ** END NESTED EXCEPTION **
    Last packet sent to the server was 63 ms ago.
    SQLState: 08S01
    VendorError: 0

  • How to connect Java into BarTender Label Printing Software

    Hi,
    I have one problem, my company have bartender label printing software 32 bit version, previously they use VB6 for controlling the dublicate printing of lable,but the software is gone. Now i want to do this in Java, but i don't know how to connect java into Bartender software.
    my company using old version, it accept only VB6. My Boss said can buy new Bartender Software but i don't know how to link and control dublicate printing. if anybody knows this connection between Bartender and Java please help me.
    if bartender New version support this features please send the link and example source code please help me.
    AnbuAathi

    Hi , i have the similar task ,where i need to connect my web portal application with the bartender software .I did a hugh R&D to integrate Java application with Bartender software but did not find any luck .So i request to provide the needed help to integrate my Java Application with Bartender software .
    Thanks in Advance
    Mohan

  • How to connect JAVA API into  NACT- NTS 2000?(TELECOM)

    hai to all,
    i need help.if there is any one working in telecom Project . (will be more helpfull). i want to connect JAVA API into NACT-NTS2000 (it's (NTS2000) fully based on JAVA ).if anybody know the solution mail me ID [email protected]
    thanks
    dhana

    Hi,
    Could you give us some URL pointers to the NACT-NTS2000 technology so we have some sense of what we are talking about technically?
    Thanks,

  • Unable to connect JAVA with Oracle

    I have jdk1.6 and oracle installed on my machine but unable to connect java with database
    have classes12.jar and ojdbc14.jar
    my environmental variables in respect to this are :
    JAVA_HOME= C:\Java\jdk1.6.0_04
    JRE_HOME=C:\Java\jdk1.6.0_04
    PATH=J:\oracle\ora92\lib;
    J:\oracle\ora92\bin;
    C:\Program Files\Oracle\jre\1.3.1\bin;
    C:\Program Files\Oracle\jre\1.1.8\bin
    CLASSPATH=J:\oracle\ora92\jdk\jre\bin\JdbcOdbc.dll;
    J:\oracle\ora92\jdbc\lib\classes12.jar;
    J:\oracle\ora92\jdbc\lib\ojdbc14.jar
    The code is
    import java.sql.*; public class dat1 {               public static void main(String[] args)throws SQLException,ClassNotFoundException {         try     {     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");     Class.forName("com.oracle.jdbc.OracleDriver");     } catch (ClassNotFoundException e) { System.out.println("unable to load driver"); return; }     } }
    the error message is
    Error in thread "main" java.lang.NoClassDefFoundError
    Please Help Me
    Thanks For Reading
    Thanks a lot in Advance For your ANSWERS

    maybe if you asked nicely instead of ordering people around we might tell you.
    As it is all you're going to hear is that you don't need both those jars, as they contain different versions of the same driver.
    I'm not going to tell you which you need, as you should have the documentation to tell you that. But then you also should have the documentation to tell you how to set your classpath properly and you failed to read that too.

  • How to connect Java to oracle Database Express Edition?

    Anyone can help me?
    How to connect JAVA TO ORACLE DATABASE EXPRESS EDITION?

    I suggest you to read this article:
    http://wiki.oracle.com/page/JDBC
    Regards,
    Ricky

  • How to connect java with database without any dsn.

    is there any way to connect java with database with out creating any dsn..like we do in ado in vb by providing provider.

    Sure use a type 4 driver. No DSN.

Maybe you are looking for

  • Can you have more than one phone (same number) on Find my phone?

    My new IPhone 5s has been stolen and I've activated it on Find my phone, it's still not been recovered! However I need a phone, so I want to use my old Iphone 4 but will this overwrite the phone thats been stolen on find my phone Im hoping my new pho

  • Can't see timecode from transcoded footage

    I shot some HD footage on a Lumix GH3, with audio recorded on a Zoom H4N. I synced it all up in Pluralize, and exported / transcoded into Prores 422 in Compressor. Now when I import the ProRes clips into Final Cut Pro 7, I cannot see the GH3's timeco

  • Don't have write access iTunes media folder or folder within it

    I have recently restored my iTunes media from a two week old version from a Time machine backup I deleted all the files in my MUSIC folder, and then restored the version that I last used two weeks ago. Now when I try to burn a CD into iTunes I get th

  • Redirection when browsing

    Sometimes when I am clicking on web pages in Safari, a new widow will pop up randomly and redirect me to a random site. This new page though isn't like a normal safari page-its shorter and stretches to both sides of my screen, which makes me worried

  • Uninstalling Corrupt Software Update Patch

    Hi, I was checking for the method to uninstall any software update patch in case need be. I came across one of the switch to use with the task sequence as below to uninstall any specific patch from systems : C:\Windows\System32\wusa.exe /uninstall /k