MSAccess DB Exception

I have Customer table in which i have CustomerNumber and CustomerName and i put the name in session and want to retrieve CustomerNumber associated with that Name but when i run the query i get the following exception . here my snippet code:
HttpSession session=req.getSession(true);
String fName = (String)session.getAttribute("name");
out.println(fName); // Here it displays name but problem in Query
PreparedStatement pstmt=con.prepareStatement("Select CustomerNumber from Customer where FirstName=" +fName);
ResultSet rs=pstmt.executeQuery();
while (rs.next()){
out.println(rs.getInt("CustomerNumber"));
}               I get following error
Exception caught : [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.

So here's the whole lot with the edit:
HttpSession session=req.getSession(true);
String fName = (String)session.getAttribute("name");
out.println(fName); // Here it displays name but problem in Query
PreparedStatement pstmt=con.prepareStatement("Select CustomerNumber from Customer where FirstName = ?");
pstmt.setString(1, fName);
ResultSet rs=pstmt.executeQuery();
while (rs.next()){
out.println(rs.getInt("CustomerNumber"));
}          

Similar Messages

  • Getting a Runtime Exception while inserting value in MSAccess 2000

    I am using below mentioned code to insert values in MSAccess 2000 which having table structure as mentioned below:-
    Field Name
    Data Type
    TodaysDate
    Date/Time
    Cart ID
    Number
    Client Name
    Text
    Team & Segment
    Text
    Duration
    Number
    Tape ID
    Text
    Start Date
    Date/Time
    End Date
    Date/Time
    Code:-
    private boolean enterDataIntoMSAccessDatabaseusingPreparedStatement()
            try {
                ps = connection.prepareStatement("INSERT INTO [Cart ID Details] VALUES (?,?,?,?,?,?,?,?)");
                System.out.println("After Query");
            catch (SQLException se) {
                generateErrorMessage("Error in Prepared Statement \n " + se.getMessage() );
                return false;
            catch (Exception e)
                generateErrorMessage("Unexpected Error Occured \n " + e.getMessage());
            String todaysDate = cartIDApplicationAddCartIDDatejTextField.getText().trim();
            String cartID = cartIDApplicationAddCartIDCartIDjTextField.getText().trim();
            String clientName = cartIDApplicationAddCartIDClientNamejTextField.getText().trim();
            String teamSegment = cartIDApplicationAddCartIDTeamAndSegmentjTextField.getText().trim();
            String duration = cartIDApplicationAddCartIDDurationjTextField.getText().trim();
            String tapeID = cartIDApplicationAddCartIDTapeIDjTextField.getText().trim();
            String startDate = cartIDApplicationAddCartIDStartDatejTextField.getText().trim();
            String endDate = cartIDApplicationAddCartIDEndDatejTextField.getText().trim();
            try {
                //System.out.println("Before ps.setString()");
                ps.setString(1, todaysDate);
                ps.setString(2, cartID );
                ps.setString(3, clientName);
                ps.setString(4, teamSegment);
                ps.setString(5, duration);
                ps.setString(6, tapeID);
                ps.setString(7, startDate);
                ps.setString(8, endDate);
                //System.out.println("After ps.setString()");
                    ps.executeUpdate();
            catch (SQLException se) {
                generateErrorMessage("Error while inserting data in database \n " + se.getMessage());
                return false;
            catch (Exception e)
                generateErrorMessage("Unexpected Error Occured \n" + e.getMessage() );
            return true;
    The above boolean function is called in "Save Button" action event, but when I click Save I am getting as Runtime Exception.
    Kindly help me to sort out this issue.

    Print stack traces not just messages.  And it will tell you what is wrong.  And if you posted the stack trace someone else might be able to tell you.
    If you get an exception DO NOT CONTINUE.  You can't do an update if the prepared statement failed so there is no point in trying.  (Of course that depends on what 'generateErrorMessage' does)
    Other than that note that you are using strings for everything even though the data types are not all text fields.

  • Strange exception with msAccess

    Hi,
    I'm building an application that uses MS Access 2000 database and I'm getting strange exception when I'm trying to update database with cursor.
    MYTABLE has three attributes:
    Text is a memo,
    Int is an integer,
    Id is an autonumber.
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = stmt.executeQuery("select * from MYTABLE");
    rs.moveToInsertRow();
    rs.updateString("Text", "some text");
    rs.updateInt("Int", 5);
    rs.insertRow();The code above throws
    java.lang.ArrayIndexOutOfBoundsException.
    The exception is thrown when rs.insertRow() is executed.
    Thanks

    Out of curiosity:
    the API for moveToInsertRow() acutally specifies that ALL of the columns for a row be set using an updateXXX method. You have an autoId field in your table, have you tried setting a value for it in your code?
    It would be nice if you tried this, and told us the result you get.
    Regards,
    Manuel Amago.

  • SELECT with WHERE clause for MSAccess from JDBC

    Hi,
    I am new user of MSAccess.I am getting exception: Invalid user type when i was trying the following code:
    String name1=nameTextfield.getText().trim();
    String query="SELECT ID from Suppliers WHERE name=name1;"
    Statement stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery(query);
    while(rs.next())
    String id1=rs.getInt(1);
    System.out.println(id1);
    nameTextField is JTextField in my GUI.
    ID id auto field in table Suppliers.
    I am using MSAccess 97.
    I came to know that the JDBC SQL queries will be different for Access.
    Any body help me how to write SELECT statement?
    Thanks in advance,
    Sai Ram

    name or ID might be reserved words in access. Either change the name of the column or put [] around them. Also, you ar looking for a record where fields name and name1 are equal. You probably don't have a name1 field.
    String name1=nameTextfield.getText().trim();
    String query="SELECT [ID] from Suppliers WHERE [name]='"+name1+"';"
    Pay attention to the single and double quotes I have.

  • Inserting into MsAccess Database

    Hi,
    I am having problem with inserting a row into the MsAccess Database. I am getting error like
    "SQLException: Occurred while performing Database Operations ---> method Main() java.sql.SQLException
    : [Microsoft][ODBC Microsoft Access 97 Driver] Syntax error in INSERT INTO statement.[Microsoft][ODB
    C Microsoft Access 97 Driver] Syntax error in INSERT INTO statement".
    My code is as under:
    please help me out.
    Smitha
    ==========================================
    package dao;
    import utils.GeneralFailureException;
    import dbConnection.dbConnection;
    import java.util.*;
    import java.sql.*;
    public class GeneralExpenses {
    dbConnection dbCon = new dbConnection();
    public GeneralExpenses() {
         super();
    public static java.sql.Timestamp getTstamp() {
    java.util.Date date = (Calendar.getInstance()).getTime();
    java.sql.Timestamp tStamp = new java.sql.Timestamp(date.getTime());
    System.out.println("The Time Stamp : " + tStamp);
    return tStamp;
    public void insertExpenseTable(String sExphead, double dAmount, String sMode)
         throws GeneralFailureException, SQLException, ClassNotFoundException {
         String inssql = "INSERT INTO EXPENSES(tnum, date , " + sExphead + ", " + sMode + ") VALUES(?,?,?,?)";
         Connection conn = null;
         PreparedStatement pstmt = null;
         try {
              conn = dbCon.getConnection();
              pstmt = conn.prepareStatement(inssql);
              pstmt.setInt(1, 100);
              pstmt.setTimestamp(2, getTstamp());
              pstmt.setDouble(3, dAmount);
              pstmt.setString(4, sMode);
              pstmt.executeUpdate();
         } finally {
              dbCon.closeAll(pstmt, conn);
    public static void main(String[] args) {
         try {
    GeneralExpenses ge = new GeneralExpenses();
         ge.insertExpenseTable("xxxxxxx", 250.35, "yyyyyyyy");
         System.out.println("worked");
         } catch(ClassNotFoundException sqlex) {
         System.err.print("SQLException: Occurred while performing Database Operations ---> method Main() " + sqlex);
         System.err.println(sqlex.getMessage());
         catch(SQLException sqlex) {
         System.err.print("SQLException: Occurred while performing Database Operations ---> method Main() " + sqlex);
         System.err.println(sqlex.getMessage());
    } catch(GeneralFailureException e) {
         System.err.print("GeneralFailureException: Occurred while Establishing Connection ---> method getConnection() " + e);
         System.err.println(e.getMessage());
    } catch(Exception e) {
         System.err.print("GeneralFailureException: Occurred while Establishing Connection ---> method getConnection() " + e);
         System.err.println(e.getMessage());

    I'm so happy to finally found the answer of my problem with that message Kurt.
    Thank you very much... !
    I will now remember that date cannot be the name of a field when using jdbc-odbc. I called my field TransDate and it is now working perfectly!

  • Sql - Insert problem in MsAccess

    Hello!!!
    J have problem with INSERT function, I use MsAccessm as database. My query is :
    INSERT INTO [Produkty-www] ( Id,Nazwa,Kod,Cena)
    VALUES 6646545,"Zlaczka
    prosta 22mm 1/2 ' z (KRoCIEC)",'JGK22-1/2Z',10.00)
    this is very import symbol ' in 1/2 ' z must be at the place. When I execute this query I have exception. In maaccess I create query and also msaccesse show me when is the bad part of query the sybmol ' is underline.
    So I create a new query but in access :
    INSERT INTO [Produkty-www] ( Id,Nazwa,Kod,Cena) VALUES (6646545,"Zlaczka prosta 22mm 1/2 ' z (KRoCIEC)",'JGK22-1/2Z',10.00)
    and ok access add record, now I copy this query to my java application and I also have exception.
    Why this query don`t work.. ?

    Ok, it`s done :     
    PreparedStatement statement = podlaczenie.prepareStatement("INSERT INTO [Produkty-www] (id, Nazwa, Kod, Cena) VALUES (?,?,?,?)");
    statement.setInt(1,2);
    statement.setString(2,"ffsdfds'fdsfs");
    statement.setString(3,"kod");
    statement.setInt(4,124);
    statement.execute();
    But I need a sql query print to console, a search a method of statement but I dont find that I look for, it is some method that give my sql query in string ?
    Thank`s for help

  • How to insert data in to msaccess through jsp

    i am doin a project in jsp, which i am new to. i have completed the design part in jsp now i am supposed to work with backend and stuffs.
    yesterday i had asked how to connect jsp with msaccess and Mr sharma had helped me in that and now that part is up and running. i am able to retrieve data from the table
    now my problem is how to insert data that i get from the user through the forms in to a table
    i have a registration form in jsp that contains the username, password, age etc. how can i get add these informations in to access.pls help me
    thanks in advance

    Hi....
    Simply obtain a jdbc connection to your ms access database.
    one u have a connection u can use , Statement Or PreparedStatement to
    execute queries against database
    Here is an example of mysql...
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    public class SqlAuthenticationHandler{
         private Connection conn;
         private PreparedStatement statement;
         private ResultSet rs;
         public SqlAuthenticationHandler(){
    /** Load ur JDBC driver **/
    try{
                   Class.forName("com.mysql.jdbc.Driver");
    conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/JDrive","root","password");
              }catch(Exception ex){
                   ex.printStackTrace();
    public void insertUser(String name, String password){
    try{
    /** Create a statement **/
    statement=conn.prepareStatement("INSERT into user values(?,?)");
    statement.setString(1,name);
    statement.setString(2,password);
    statement.executeUpdate();
    statement.close()
    }catch(SQLException e){
                        e.printStackTrace();
    Here replace "com.mysql.jdbc.Driver" with class name of your type 4 Ms Access Driver.
    replace jdbc:mysql://localhost:3306/JDrive","root","password" with url of ur access database
    check out this jdbc tutorial
    http://java.sun.com/docs/books/tutorial/jdbc/overview/index.html
    Sudhir Nimavat (Sudhir_nimavat at yahoo dot com)

  • Null pointer exception without any reason

    Can anybody tell me why the following portin of code is throwing null pointer exception
    Connection con=null;
              ResultSet rs;
              Statement stmt=null;
    try{
                        //----------------- Driver -------------------
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        //----------------- URL WITHOUT DSN ----------------------------               
                        String conString = "jdbc:odbc:DRIVER={MicroSoft Access Driver (*.mdb)};" +
                       "DBQ=./data/RMS.mdb";
                        con = DriverManager.getConnection(conString,"","");
                        stmt = con.createStatement();
                                    String sql="SELECT * FROM Employee";
                           stmt.executeQuery(sql);
                           rs.next();
    catch(ClassNotFoundException cnfe){     System.out.println("Driver Not Found !!!");                    }
                   catch(SQLException sqle){
                        System.out.println("DSN Not Found !!!");                    }

    Thanks a lot brother, how could I do such mistake!!
    One more thing, can you tell me how to delete the trace of PK auto-number from MsAccess DB.I mean, if I delete all the data from the table and insert again, yet it does not start from Pk id- 1, auto-number starts from after the previously deleted data.How can I make it start from -" 1 " , if there is no data in the table.
    THANKS in advance.
    Edited by: Tanvir007 on Oct 26, 2008 12:29 PM

  • MSAccess problem    with websphere??

    i have the Ms access database
    i am trying to connecting to the msaccess through websphere IDE
    can u tell me which driver will support for connecting msaccess
    i am using sun.jdbc.odbc.JdbcOdbcDriver
    its throwing the following exceptions
    driver is not found
    whethere the websphere support the msaccess database or not

    i am using sun.jdbc.odbc.JdbcOdbcDriver
    its throwing the following exceptions
    driver is not found
    whethere the websphere support the msaccess database or not Check your code:
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:yourDSN4MSAccess","","");
    You shouldn't meet too much issue since most of MSAccess connections're using jdbc odbc bridge.
    can u tell me which driver will support for connecting msaccessHXTT Access is a type 4 JDBC driver, but it's a commerical package.
    Yonghong Zhao
    System Analyst
    www.hxtt.net

  • Missing Primary Keys after migartion of a MSAccess 2003 DB to oracle 9.i

    I migrate a MS Access 2003 DB to Oracle 9.i with the Oracle Migration Workbench 10.1.0.4.0. on a Windows 2k PC. All the Primary Keys of my tables are missed after migration and no Foreign Key is created.
    In the MS Access Source Model Window of OMWB are the Primary Keys detected but in migration script or in oracle db after migration there is no Primary Key applied.
    Dos anyone kows the reason for this behavior.
    Thanks for help in advance.
    Message was edited by:
    user468547
    Message was edited by:
    user468547

    Here the summary of the Model.
    Not mentioned parts are sero in the Oracle Model
    MS Access Source Model
    Table Violation Rules (0)
    Relations ( 48)
    Indexes (96)
    Primary Keys (38)
    Queries (0)
    Tables (38)
    Oracle Model
    Database (1)
    Check Constraints (0)
    Foreign Keys (48)
    Indexes (96)
    Primary Keys /Unique ... (0)
    Tables (38)
    Types (2)
    In the migration scripts the commands for creation of Foreign Keys are avaliable and delievers the error message ORA-02270. e.g.
    REM
    REM Message : Failed to create foreign key: dbwines.TBL_SERVICEPROFILESTBL_UETYPES; ORA-02270: no valid Primr- o. eindeutiger Key for this column
    Here the content of the error.log
    ** Workbench Repository : Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    Repository Connection URL: jdbc:oracle:thin:@pcathlon17002:1521:ORCL
    ** The following plugins are installed:
    ** Microsoft Access 2.0/95/97/2000/2002/2003 Plugin, Production Release 10.1.0.4.0
    ** Active Plugin : MSAccess
    oracle.mtg.migration.MigrationSQLException: Failed to get information about Oracle Model Object.
    Erschpfte Ergebnismenge:Failed to get information about Oracle Model Object.
    Erschpfte Ergebnismenge
         at oracle.mtg.oracleModel.server.OracleModelImpl.getObjectInformation(OracleModelImpl.java:476)
         at oracle.mtg.oracleModel.ui.OracleModelTypes.getAllChildren(OracleModelTypes.java:95)
         at oracle.mtg.plugin.ui.WorkbenchAllTreeNode.getChildren(WorkbenchAllTreeNode.java:133)
         at oracle.mtg.migrationUI.TreeDataSource.getItemCount(TreeDataSource.java:128)
         at oracle.ewt.dTree.DTreeDeferredParent.getItemCount(Unknown Source)
         at oracle.ewt.dTree.DTreeBaseItem.isExpandable(Unknown Source)
         at oracle.ewt.dTree.DTreeButtonDecoration.getHasButton(Unknown Source)
         at oracle.ewt.dTree.DTreeButtonDecoration.paintDecoration(Unknown Source)
         at oracle.ewt.dTree.DTreeStackingDecoration.paintDecoration(Unknown Source)
         at oracle.ewt.dTree.DTree.paintCanvasInterior(Unknown Source)
         at oracle.ewt.EwtComponent.paintInterior(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter._paintInterior(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.EwtComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent._paintComponent(Unknown Source)
         at oracle.ewt.lwAWT.LWComponent.paint(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paintExtents(Unknown Source)
         at oracle.ewt.lwAWT.SharedPainter.paint(Unknown Source)
         at oracle.ewt.lwAWT.BufferedApplet.paint(Unknown Source)
         at oracle.ewt.lwAWT.BufferedApplet.update(Unknown Source)
         at sun.awt.RepaintArea.paint(Unknown Source)
         at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    ** Shutdown : Mon Apr 10 18:36:10 CEST 2006
    ** Oracle Migration Workbench
    ** Production
    ** ( Build 20050629 )
    ** OMWB_HOME: C:\oracle\ora92\omwb
    ** user language: de
    ** user region: null
    ** user timezone:
    ** file encoding: Cp1252
    ** java version: 1.4.2_04
    ** java vendor: Sun Microsystems Inc.
    ** o.s. arch: x86
    ** o.s. name: Windows 2000
    ** o.s. version: 5.0
    ** Classpath:
    ..\lib\boot.jar
    ** Started : Mon Apr 10 18:36:14 CEST 2006
    ** Workbench Repository : Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    Repository Connection URL: jdbc:oracle:thin:@pcathlon17002:1521:ORCL
    ** The following plugins are installed:
    ** Microsoft Access 2.0/95/97/2000/2002/2003 Plugin, Production Release 10.1.0.4.0
    ** Active Plugin : MSAccess
    EXCEPTION : query()java.sql.SQLException: Stream wurde schon geschlossen
    select MESSAGE_TYPE, LOG_ID, TO_CHAR(LOG_DATE, 'dd-MM-yyyy hh24:mi:ss') LOG_DATE, PROJECT_ID, PHASE, SUBPHASE, LOG_MESSAGE, OBJECT_TYPE, OBJECT_ID, CONTEXT_DATA from MTG_LOG_TABLE WHERE PROJECT_ID = 1 and (MESSAGE_TYPE != 9999) ORDER BY LOG_ID ASC
    java.lang.NullPointerException
         at oracle.mtg.migration.LogDisplayUtility.convertToDisplayStrings(LogDisplayUtility.java:185)
         at oracle.mtg.migrationServer.LoggingImpl.getLogs(LoggingImpl.java:482)
         at oracle.mtg.migrationUI.LoggingPane.setupLogTable(LoggingPane.java:291)
         at oracle.mtg.migrationUI.LoggingPane.setupLogTable(LoggingPane.java:280)
         at oracle.mtg.migrationUI.ProgressDialog.commandStarting(ProgressDialog.java:117)
         at oracle.mtg.migrationUI.MigrationUI.commandStarting(MigrationUI.java:2427)
         at oracle.mtg.migrationUI.MigrationWizard.doMigrate(MigrationWizard.java:401)
         at oracle.mtg.migrationUI.MigrationWizard.runDialog(MigrationWizard.java:293)
         at oracle.mtg.migrationUI.ActionMenuHandler._migrate(ActionMenuHandler.java:340)
         at oracle.mtg.migrationUI.ActionMenuHandler._capture(ActionMenuHandler.java:291)
         at oracle.mtg.migrationUI.ActionMenuHandler.run(ActionMenuHandler.java:85)
         at oracle.mtg.migration.WorkerThread.run(Worker.java:268)
    ** Workbench Repository : Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.1.0 - Production
    Repository Connection URL: jdbc:oracle:thin:@pcathlon17002:1521:ORCL
    ** The following plugins are installed:
    ** Microsoft Access 2.0/95/97/2000/2002/2003 Plugin, Production Release 10.1.0.4.0
    ** Active Plugin : MSAccess
    Thaks for help in advance
    Regards Steffen

  • To retrive console data of MSAccess .How to dispaly  result on a Component

    hai there
    Im new to Java programming.I dont know how to get the result of following query "select SUM(Total) from Records where Date=adate AND MedicalName=somename"
    This query results Expr1000
    30,4589.7
    Expr1000 is not a cloumn name.How can i retrive the figure above and to dispaly in a JTextField.
    if i execute the code below to retrive required,it generates SQL Exception.
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:ashok", " ", " ");
    pstat=con.prepareStatement("select SUM(Total) from Record where Date=? AND MedicalName=?");
    pstat.setString(1,(String)jList11.getSelectedValue());
    pstat.setString(1,(String)jComboBox1.getSelectedItem());
    r1=pstat.executeQuery();
    jTextField1.setText(r1.getString("Total"));
    catch(Exception e)
    System.out.println("GRAND T :"+e);
    if i execute the above code it generates SQL Exception:COUNT Field Incorrect.
    Plz help to solve this problem.

    hi zhaoyh
    This is ashok.Thanks a lot for ur reply.I corrected my mistake.
    I have a problem on setting the result in a JTextField for the following query.
    "select SUM(Total) from Record where Date=? AND MedicalName=?"
    if execute this query in MSAccess or in Oracle as
    SELECT SUM(Total) FROM Record WHERE Date=06/10/2005 AND MedicalName='Sakthi'
    Cosole shows Expr1000
    34000.5
    Expr1000 is not a column in my table.But i need to set 34000.5 in my JTextField.
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:ashok", " ", " ");
    pstat=con.prepareStatement("select SUM(Total) from Record where Date=? AND MedicalName=?");
    pstat.setString(1,(String)jList11.getSelectedValue());
    pstat.setString(2,(String)jComboBox1.getSelectedItem());
    r1=pstat.executeQuery();
    jTextField1.setText(// HERE I NEED THE RESULT WHICH IS DISPLAYED ABOVE IN CONSOLE OF MS ACCESS OR IN ORACLE
    catch(Exception e)
    System.out.println("GRAND T :"+e);
    Pls help to solve this problem .

  • How to store and retrieve image in a MsAccess DB using JDBC

    I want to store images in a MsAccess DB using JDBC and also want retrieve them from DB. please don't tell to store the path of image..I want to store the image not the path...pls reply..thanx in advance

    zakircse, you should read more about Java's API.
    import java.io.*;
    import java.sql.*;
    import java.util.Properties;
    import java.awt.*;
    import javax.swing.*;
    public class ImageDemo{
    public static void main(String argv[]){
    try{
    String url="jdbc:access:/c:/test";
    Class.forName("com.hxtt.sql.access.AccessDriver").newInstance();
    Properties properties=new Properties();
    Connection connection = DriverManager.getConnection(url,properties);
    Statement stmt = connection.createStatement();
    stmt.execute("create database if not exists imagedatabase;");
    connection.setCatalog("imagedatabase.mdb");
    stmt.execute("create table if not exists imagetable (imageid int,IMAGE_DATA blob);");
    File file=new File("c:/pic.jpg");
    FileInputStream in=new FileInputStream(file);
    PreparedStatement ps=connection.prepareStatement("insert into imagetable (imageid,IMAGE_DATA) values(?,?);");
    ps.setInt(1,1234);
    ps.setBinaryStream(2,in,(int)file.length());
    ps.execute();
    ps.close();
    ResultSet rs =stmt.executeQuery("select IMAGE_DATA from imagetable where imageid=1234");
    byte[] imgbytes=null;
    if(rs.next()) {
    imgbytes=rs.getBytes(1);
    rs.close();
    stmt.close();
    connection.close();
    if(imgbytes!=null){
    JFrame fr = new JFrame();
    fr.setTitle("Simple Demo for Load Image from MS Access");
    Image image = fr.getToolkit().createImage(imgbytes);
    fr.getContentPane().add(new PaintPanel(image));
    fr.setSize(200,400);
    fr.setVisible(true);
    Thread.sleep(10000);
    System.exit(0);
    catch( SQLException sqle )
    do
    System.out.println(sqle.getMessage());
    System.out.println("Error Code:"+sqle.getErrorCode());
    System.out.println("SQL State:"+sqle.getSQLState());
    sqle.printStackTrace();
    }while((sqle=sqle.getNextException())!=null);
    catch( Exception e )
    System.out.println(e.getMessage());
    e.printStackTrace();
    class PaintPanel extends JPanel {
    private Image image;
    public PaintPanel(Image image) {
    this.image = image;
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, this);
    }

  • Wierd behavior of jdbc:odbc using MSACCESS 2002

    I'm using msaccess 2002, java version 1.4.0, Windows XP.
    I configured ODBC driver for my database "MailDB" using "odbcad32".
    I have no problem retrieving data from my database to my program, however I can't insert data to my database.
    I've checked my SQL syntax, it works fine within Access.
    Does anyone have an idea what could be the problem?
    Code:
    import java.sql.*;
    public class AccessConnection
         public static void main(String[] args){
              try {
                   //Connecting to database
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection conn = DriverManager.getConnection("jdbc:odbc:MailDB");
                   //Select Query - WORKS FINE!!!
                   ResultSet rS = conn.createStatement().executeQuery("Select * from MAIL" );
                   while (rS.next())
                        System.out.println(rS.getString("A"));               
                   rS.close();
                   //Insert Query - DOESNT WORK!!!!!!!!!!
                   conn.createStatement().executeUpdate("Insert Into MAIL (A,B,C) VALUES ('a','b','c') ;");
              catch (ClassNotFoundException e1){}
              catch (SQLException e){}

    1. Remove the semi-colon.
    2. Close the connection
    3. Do something with the exceptions - don't just discard them.

  • ODBC 10.2 test connection success but MSAccess/Office throws ORA-12154

    I've run into a difficult-to-solve problem. I'm troubleshooting an MSAccess to Oracle connection via Oracle ODBC driver issue.
    MSAccess was giving ORA "long" datatype error (can't remember error number) when using 11.2.1 driver against a years-old, tried-n-true app that was previously well behaved (only diff is use of that app with newer Oracle ODBC driver). Web search revealed problems with 11.2 ODBC driver and MSOffice tools so decided to swith to older ODBC driver. Had 10.2 ODBC driver also installed so switched to that. Now get ORA-12154 every time I try to connect with MSAccess via Oracle ODBC. Using the ODBC Admin (32 bit) allows SUCCESSFUL connection as does tnsping & other tools that use Oracle Net. Only MSAccess (or other MSOffice tools) do not.
    I've verified no other tnsnames.ora files or sqlnet.ora files available and have even gone as far as completely removing all things Oracle from the PC and reinstalling only the 10.2 client (custom mode; installed only the Oracle NET and ODBC 10.2 driver). I've turned on tracing to ADMIN level and read the trace files. trace for MSAccess call vs trace for ODBC administrator call yields nearly identical trace files till "niotns" step where the ODBC admin proceeds to connect and the MSAccess call just gives a few other coments then stops. NO apparent error messages. tnsnames IS found so don't understand why giving ORA-12154.
    All tools connect (tnsping works, SQL*Plus connects, ODBC admin test sucessful, TOAD connects) EXCEPT MSAccess. Problem is I have many, many MSAccess legacy apps/tools and cannot go without the fully working ODBC connection between MSAccess and Oracle.
    Help... desparate for new ideas to try since I've spent many hours searching and tried all known troubleshooting steps.
    Any ideas appreciated.
    Thanks,
    Mike

    Hi Mike,
    I have a similar error. I can connect to database with TNSPING, and I can also connect with SQL Developer. But I am unable to connect with Access using ODBC, I get ORA-12154 error. Am also completely stumped. So if anyone can help, I would appreciate it too.
    (P.S. I have tried on a number of PCs here in the office, on one PC I have here I can connect using Access and ODBC, I can see the tables, I pick on a table, it says "linking", but it never links - it just hangs forever.)
    Thanks for any pointers,
    Tom

  • If image file not exist in image path crystal report not open and give me exception error problem

    Hi guys my code below show pictures for all employees
    code is working but i have proplem
    if image not exist in path
    crystal report not open and give me exception error image file not exist in path
    although the employee no found in database but if image not exist in path when loop crystal report will not open
    how to ignore image files not exist in path and open report this is actually what i need
    my code below as following
    DataTable dt = new DataTable();
    string connString = "data source=192.168.1.105; initial catalog=hrdata;uid=sa; password=1234";
    using (SqlConnection con = new SqlConnection(connString))
    con.Open();
    SqlCommand cmd = new SqlCommand("ViewEmployeeNoRall", con);
    cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    da.Fill(dt);
    foreach (DataRow dr in dt.Rows)
    FileStream fs = null;
    fs = new FileStream("\\\\192.168.1.105\\Personal Pictures\\" + dr[0] + ".jpg", FileMode.Open);
    BinaryReader br = new BinaryReader(fs);
    byte[] imgbyte = new byte[fs.Length + 1];
    imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length)));
    dr["Image"] = imgbyte;
    fs.Dispose();
    ReportDocument objRpt = new Reports.CrystalReportData2();
    objRpt.SetDataSource(dt);
    crystalReportViewer1.ReportSource = objRpt;
    crystalReportViewer1.Refresh();
    and exception error as below

    First: I created a New Column ("Image") in a datatable of the dataset and change the DataType to System.Byte()
    Second : Drag And drop this image Filed Where I want.
    private void LoadReport()
    frmCheckWeigher rpt = new frmCheckWeigher();
    CryRe_DailyBatch report = new CryRe_DailyBatch();
    DataSet1TableAdapters.DataTable_DailyBatch1TableAdapter ta = new CheckWeigherReportViewer.DataSet1TableAdapters.DataTable_DailyBatch1TableAdapter();
    DataSet1.DataTable_DailyBatch1DataTable table = ta.GetData(clsLogs.strStartDate_rpt, clsLogs.strBatchno_Rpt, clsLogs.cmdeviceid); // Data from Database
    DataTable dt = GetImageRow(table, "Footer.Jpg");
    report.SetDataSource(dt);
    crv1.ReportSource = report;
    crv1.Refresh();
    By this Function I merge My Image data into dataTable
    private DataTable GetImageRow(DataTable dt, string ImageName)
    try
    FileStream fs;
    BinaryReader br;
    if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + ImageName))
    fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + ImageName, FileMode.Open);
    else
    // if photo does not exist show the nophoto.jpg file
    fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + ImageName, FileMode.Open);
    // initialise the binary reader from file streamobject
    br = new BinaryReader(fs);
    // define the byte array of filelength
    byte[] imgbyte = new byte[fs.Length + 1];
    // read the bytes from the binary reader
    imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length)));
    dt.Rows[0]["Image"] = imgbyte;
    br.Close();
    // close the binary reader
    fs.Close();
    // close the file stream
    catch (Exception ex)
    // error handling
    MessageBox.Show("Missing " + ImageName + "or nophoto.jpg in application folder");
    return dt;
    // Return Datatable After Image Row Insertion
    Mark as answer or vote as helpful if you find it useful | Ammar Zaied [MCP]

Maybe you are looking for