To write in an Access Database

Here is my code:
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(Exception e){
System.out.println("Erreur lors du chargement du driver:"+ e.getMessage());}
try {
Connection con = DriverManager.getConnection("jdbc:odbc:user_data");
catch(Exception e){
System.out.println("echec d'ouverture:"+e.getMessage());
ResultSet results;
try {
Connection con = DriverManager.getConnection("jdbc:odbc:user_data");
Statement stmt=con.createStatement();
int NbIns ;
NbIns = stmt.executeUpdate("INSERT INTO Ex-Shapes (num_shape,num_ex) VALUES (8,2) ");
System.out.println(NbIns+" ligne inseree");
catch(Exception e){
System.out.println("exception du a la requete "+e.getMessage());
and I don't manage to write this in the MS Access database.
Here is the message in the Output window:
[Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.
I don't understand why the syntax is uncorrect.
Thank you to help me.

You're right !!!
It's very a stupid thing ! I lost time because of that.
Thank you.

Similar Messages

  • Labview using access database

    "I need to use labview in order to read and write to an access database (8 columns per entry). I'm not too familiar with the program, but i know that we have the database connectivity toolset and the sql toolset installed. Does anyone have any simple examples laying around for someone who isn't labview savvy?"

    I did a search of the examples on the web site and found 100s of examples on LabVIEW and an access database. Do a search at this link for "microsoft access database labview" Example Code Library
    The top example I found is titled "Write Table in Columns to an Access Database" which sounds pretty close to what you are looking for.
    Hope these help.

  • The Microsoft Access database engine cannot open or write to the file in Report Builder 3.0

    I am trying to build a report in Report Builder 3.0.  I created the Data Source to point to my Excel file and the Data Set.  I drag a couple of fields on to the canvas and then choose Run.  I get the error:  "The Microsoft Access
    database engine cannot open or write to the file.  It is already opened exclusively by another user".  I am using the Excel driver.  Why am I getting this message?  How can I fix this?

    No, now I am getting the error message again.  It is quite long:
    ERROR [HY000] [Microsoft][ODBC Excel Driver] The Microsoft Access database engine cannot open or write to the file '(unknown)'. It is already opened exclusively by another user, or you need permission to view and write its data.
    ERROR [01S00] [Microsoft][ODBC Excel Driver]Invalid connection string attribute Trusted_Connection
    Please help

  • The Microsoft Access database engine cannot open or write to the file \\fileserver\db\access.mdb

    Hi,
    I have Windows Server 2012 with SQL 2012 Standard SP1. I am using linked server, and Access Database Engine 2010 Redistributable to access my database file made in Microsoft Access (.mdb) from network file server.
    EXEC master.dbo.sp_addlinkedserver @server = N'MyLinkedServer', @srvproduct=N'MyLinkedServer', @provider=N'Microsoft.ACE.OLEDB.12.0', @datasrc=N'\\myfileserver.mydomain.com\files\mydatabase.mdb'
    My SQL service is running with domain service account MYDOMAIN\SQL1$ , i have added Full control for file share and NTFS permission on my file server folder (C:\Files).
    When I open (as domain admin with UAC elevated permissions) on my DB server SQL Management studio, I can browse tables and everything works.
    The problem is, if I open SQL management studio (as domain admin with UAC elevated permissions) on my File server or any other computer, when trying to browse my linked server i got error:
    TITLE: Microsoft SQL Server Management Studio
    Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)
    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&LinkId=20476
    ADDITIONAL INFORMATION:
    An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
    Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "Synesis_3PRO2013". (Microsoft SQL Server, Error: 7303)
    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=11.00.3000&EvtSrc=MSSQLServer&EvtID=7303&LinkId=20476
    When I try to place simlpe Select SQL query I got error:
    OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "MyLinkedServer" returned message "The Microsoft Access database engine cannot open or write to the file '\\myfileserver.mydomain.com\files\mydatabase.mdb'. It is already opened exclusively by another
    user, or you need permission to view and write its data.".
    I do not have any other program using my access database, and user has full control. I am trying to use in security mode - "For a login not defined in the list above, connections will be made without using a security context", i have also tried all four options.
    I am confused becouse it works from SQL server but from any SQL client domain member computer/server it does not work.
    I have same problem in another environment where I have Windows Server 2008 R2 and SQL 2008 R2 SP2.
    Please help.
    -- Hrvoje Kusulja

    NTFS must be fine since it works from same server using same accounts.
    As I understand, adding my access file to Access trusted location could be a problem. I have tried now to add my access database file location to trusted locations for user which is my SQL service user (Windows Service - AD managed service account MYDOMAIN\SQL1$)
    and my test user which I use to connect to sql server as a client from sql management studio. (Account is Domain Admins and have full permissions on SQL server also)
    I have added this .reg:
    Windows Registry Editor Version 5.00
    [HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security]
    [HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security\Trusted Documents]
    "LastPurgeTime"=dword:01592874
    "DisablePromptOpenNetworkTrustedDocuments"=dword:00000000
    [HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security\Trusted Locations]
    "AllowNetworkLocations"=dword:00000001
    [HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security\Trusted Locations\Location0]
    "Description"="My file server"
    "AllowSubFolders"=dword:00000001
    "Path"="\\\\myfileserver.mydomain.com\\files\\"
    I have done this for SQL service account user and my personal test account as I said. I have tried to logoff and restart sql service and all servers also.
    The same problem still persists.
    Anyway, thank you for giving me a hint.

  • How to read/write from Access database

    Hi everybody
    I need a little help for doing what I wrote in the topic!
    I use LabVIEW 6i student edition, do Ireally need to install the Database
    connectivity toolkit?

    Hi Vicio,
    There are a couple of different methods to communicate with Access in LabVIEW, and some are more difficult than others. You can use ActiveX Automation to open Microsoft Access and control many aspects of the Access Application. For actual database manipulation however, the Access automation classes rely upon the Microsoft DAO (Data Access Object) and/or ADO (ActiveX Data Object) classes. These classes can be used independently or through the Access automation classes to read and write data into an Access database. These classes can be difficult to use and may require a fair amount of SQL knowledge to accomplish a complicated task. Attached is a very simple example of how you can use DAO from the Access automation classes to read an Access table.
    For more information about the Microsoft Access automation classes, DAO or ADO classes refer to the Microsoft website and Developer Network:
    MSDN
    It is also possible to use Dynamic Data Exchange (DDE) communication between LabVIEW and Access. DDE is a Microsoft technology that preceded COM and ActiveX. DDE is NOT recommended as it is considered by most to be obsolete. However, examples still ship with LabVIEW that demonstrate how to communicate with MS Access using DDE. The examples are located in ..\LabVIEW\examples\comm\access.llb
    Note: The LabVIEW Database Connectivity Toolset is the preferred method of database communication with LabVIEW. The LabVIEW Database Connectivity Toolset offers many powerful tools and extended capabilites for quickly accessing databases. The LabVIEW Database Connectivity Toolset offers connectivity to most popular databases through Microsoft ADO technology, complete SQL Functionality, and the ability to save records in XML format. It provides both easy-to-use and advanced functions to allow common database operations as well as detailed database accessibility. The LabVIEW Database Connectivity Toolset is sold separately or in the LabVIEW Enterprise Connectivity Toolset along with the LabVIEW Statistical Process Toolkit and the LabVIEW Internet Developers Toolkit.
    Sincerely,
    Feroz
    National Instruments
    Attachments:
    Access_ActiveX.vi ‏43 KB

  • How to Protect your Custom Access Database Product - so that you can sell & distribute it?

    I'm looking for an update on this topic as I have been away from Access for a couple of years and have not kept up with the latest.
    Hopefully they have made it easier to design, develop, sell and distribute custom database solutions. So here goes...
    Question A:
    If one develops a custom database product with Access 2013 what is the current best way to...
    1 - Prevent it from being (too easily) copied
    2 - Prevent it from being (too easily) reverse engineered
    3 - Prividing a time limited free demo copy?
    4 - Providing a demo copy with limited functionality... like limiting the number of records in an important table, or whatever?
    5 - What have I left out of this list that should be considered for protecting ones investment in the development of the product? (other than copyright, of course.)
    Question B:
    What is the latest on being able to migrate an Access database to the cloud?
    1 - Entirely online
    2 - Part in the cloud and part on the users machine
    3 - And what about all that VBA code - is there no way to make that work in the cloud and/or on a web server... or does it all have to be tossed and all the coding redone?
    Question C:
    What are other alternatives solutions for selling your custom database application while protecting all your investment in developing it?
    1 - Write the front end in C++  (so that it is fully compiled) and the back end in ASP with MS SQL Server? (or alternative server side solutions)
    2 - Write the whole thing as a server side solution with browser interface?
    3 - Or what?
    Thanks for any help.

    Hi Fran_3,
    >>What is the latest on being able to migrate an Access database to the cloud?
    In my option, the Access Web app would be a better choise.
    Regards,
    Tony
    Help each other

  • Is it possible to Install the 64-bit Microsoft Access Database Engine 2010 if we are running Microsoft Office 2010 32-bit?

    So we are running Microsoft Office Professional Plus 2010, Version 14.0.7015.1000
    (32-bit)
    This is what is installed via our Network and Network licensing.
    I am trying, in vain, to read and write a .xlsx file via a C# Edit Script in a SSIS Package. And I have tried using...
    string StringConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\"";
    And this tells me that this has not been installed. So when I go and try and get the Microsoft Access Database Engine 2010 64-bit, which would allow me to use Microsoft.ACE.OLEDB.12.0 and allow me to read, write, and process this .xlsx file, it tells me
    I cannot install it because I already have 32-bit installed and it wants me to un-install Microsoft Office 2010. Why? Because it is 32-bit? And I can't do that because this is what we have and what we're licensed for and from what I've read seems to be the
    industry standard because most software vendors are ill equipped to process 64-bit right now.
    So my question is this...How can I use a C# Edit Script to read and process a .xlsx file? Because if I try using...
    string StringConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
    It then tells me that the file is not in that format.
    Please excuse me for asking this question in a couple of different ways out here but I cannot for the life of me seem to be able to get an answer as to how I can process a .xlsx file with a C# script and which driver to use that will make this work.
    Thanks for your review and am hopeful for a reply.
    ITBobbyP85

    Hi ITBobby85,
    If the excel version in the Connection Manager is Microsoft Excel 2010 (.xlsx), we should use Microsoft.ACE.OLEDB provider.
    We can't install 32bit and 64bit parts of office on the same machine. We will get an error as you said when we run the installer to install the 64bit version of the Microsoft Access Database Engine 2010 Redistributable in the machine where a 32bit version
    of Microsoft Office installed. To fix this issue, please download and install the 32bit version of the Microsoft Access Database Engine 2010 Redistributable with the link below:
    http://www.microsoft.com/en-us/download/details.aspx?id=13255
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Only one user at a time allowed to open MS Access database on a Mac share

    I have an issue trying to open a Microsoft Access database from our Mac OS X Server running on XServe.
    The MS Access file is stored on a Share Point on the XServe. Windows XP clients open the database. The problem is that it will only allow one user at a time to open the file. The has previously been operating fine when it was stored on a Windows server.
    The Group's permissions for this Share Point allow Read & Write.
    Any thoughts would be much appreciated.

    I think you're being misled a bit by the interface: the checkbox labelled "Strict locking" doesn't just allow strict locking, it requires it (and thus disallows byte-range locking). That is, with strict locking enabled, any client that tries to lock any part of the file actually locks the entire file. Access normally depends on byte-range locking to allow different clients to share the database (as long as they aren't trying to modify the same part of it at the same time), but with strict locking the first client locks all others out.

  • Getting the table names in an MS Access database

    Hi,
    I am new to JDBC and making a client/server application that updates a MS Access database through jdbc:odbc.
    I need to get a list of existing user tables in the db. I have found a great document on the net which has the code, however the code doesn't work. I have tried different ways and looked every where with no success. (link to the doco: http://www-128.ibm.com/developerworks/opensource/library/j-jdbc-objects/)
    Here is my dbManager class that handles all db related services in my application. I would appreciate any help I can get as I have exhusted all my avenues.
    Thanks
    Sep,
    * dbManager.java
    * Created on 31 October 2005, 10:20
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    import java.io.*;
    import java.sql.*;
    import java.util.regex.*;
    * @author AUMahdavSe
    public class dbManager {
        /** Constant Declaration                */
        public static final String Driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        public static final
            String sqlCreateTable = "create table TABLENAME (" +
                "name varchar (100)," +
                "surname varchar(100)," +
                "computerType integer," +
                "computerNAL varchar(20)," +
                "haveMonitor integer," +
                "monitorNAL varchar (20)," +
                "auditDate varchar(10) );";
        public static final String sqlUpdateTable = "insert into TABLENAME values" +
                " (NAMEHOLDER, SURNAMEHOLDER, COMPTYPE, COMPNAL, HAVEMON, MONNAL);";
        /** Attributes                          */
        private String dbURL = "jdbc:odbc:";
        private String Username = "admin";  // user input
        private String Password = "purina123";  // user input
        private String ODBCDataSource;  // config file
        private String dbPath;  // set through config file or defaults to current folder
        private String configFile = "config.txt"; // set either at commandline or defaults to current folder
        private Connection con = null;
        private Statement stmt = null;
        private ResultSet tables;
        private DatabaseMetaData dma;
        private ResultSetMetaData rsmd;
        private String CurrentAuditTable = "TestTable2";
        int numCols, i;
        /** Set Methodes                        */
        public void setUsername( String usr ) {
            this.Username = usr;
        public void setPassword( String pswd ) {
            this.Password = pswd;
        public void setDbPath( String path ) {
            this.dbPath = path;
        public void setODBCDataSource( String ds ) {
            this.ODBCDataSource = ds;
        public void setDbURL( String dsname ) {
            this.dbURL = this.dbURL + dsname;
        /** Get Methodes                        */
        public String getDriver() {
            return this.Driver;
        // can be run only after a connection obj is setup
        public void getMDA() {
            try {
                this.dma = this.con.getMetaData();           
            catch (SQLException ex) {
                System.err.println("database connection: " + ex.getMessage());
        public void getDBTables() {
            //now dump out the names of the tables in the database
            String[] types = new String[1];
            types[0] = "TABLES"; //set table type mask
            //note the %-sign is a wild card (not '*')
            try {
                this.tables = this.dma.getTables(null, null, "%", types);
                dumpResults("--Tables--");
                this.tables.close();
                //this.listTables();
            catch (SQLException ex) {
                System.err.println("database connection: " + ex.getMessage());
            // listing tables
            /*int count = 0;
            int numCols = 0;
            //ResultSetMetaData rsmd;
            try {
                System.out.println("Listing db tables ...");
                //this.tables.beforeFirst();
                rsmd = this.tables.getMetaData();
                numCols = rsmd.getColumnCount();
                System.out.println("number of cols: " + numCols);
                boolean more = this.tables.first();
                System.out.println("this is why: " + more);
                while ( more ) {
                    count++;
                    for (int i = 1; i <= numCols; i++)
                        System.out.print( "Table-" + count + " -> " + this.tables.getString(count)+"    " );
                    System.out.println();
                    more = this.tables.next();
            catch ( SQLException ex ) {
                System.out.println( "problem listing db tables: " + ex.getMessage() );
        /** Other Methodes                      */
        // Initialize the db parameters, like driver, username, passwd, etc.
        public void dbInitialize() {
            // load configuration from config.txt (dbPath and ODBC Data Source name)
            this.loadDbConfig();
            // loadDriver
            this.loadDriver();
            // get username and password for the ODBC from user
            this.getDSSecurity();
            // populate dbURL, username and password
            this.setDbURL( this.ODBCDataSource );
            // connect to db
            this.dbConnect();
            // get db metadata
            this.getMDA();
            // get a list of tables in db
            this.getDBTables();
        // load JDBC driver
        public void loadDriver() {
            try {
                Class.forName( getDriver() );
            } catch (Exception e) {
                System.out.println("Failed to load JDBC/ODBC driver.");
                return;
        // connects to db and create a Connection obj and a Statement obj
        public void dbConnect() {
           try {
                this.con = DriverManager.getConnection (
                    this.dbURL,
                    this.Username,
                    this.Password);
                this.stmt = con.createStatement();
            } catch (Exception e) {
                System.err.println("problems connecting to "+this.dbURL);
        // creates table tblname in db
        public void CreateTable( String tblname ) {
            try {
                String sqlcommand = mergeTblName(sqlCreateTable, tblname);
                this.stmt.execute( sqlcommand );
            catch (SQLException ex) {
                System.err.println("problems with SQL statement sent to "+this.dbURL+
                    ": "+ex.getMessage());
                System.out.println("SQL Command: " + mergeTblName(sqlCreateTable, tblname) );
        // updates db with new record(s) by executing the SQL query sqlstmt
        // and closes db connection
        public void dbUpdate( String sqlstmt ) {
            try {
                // execute SQL commands to create table, insert data
                this.stmt.execute( sqlstmt );
                this.con.close();
            } catch (Exception e) {
                System.err.println("problems with SQL sent to "+this.dbURL+
                    ": "+e.getMessage());
        // list all user tables in the db
        public void listTables() {
            //now dump out the names of the tables in the database
            int count = 0;       
            try {
                System.out.println("Listing db tables ...");
                //this.tables.beforeFirst();
                while ( this.tables.next() ) {
                    count++;
                    System.out.print( "Table-" + count + " -> " + this.tables.getString(1) );
                    System.out.println();
            catch ( SQLException ex ) {
                System.out.println( "problem listing db tables: " + ex.getMessage() );
        // checks whether tbname exist in db as a table
        // this function has to be called after dbConnect
        public boolean tableExists( String tbname ) {
            boolean tbexists = false;
            //get the database metadata
            try {
                dma = con.getMetaData();           
            catch (SQLException ex) {
                System.err.println("database connection: " + ex.getMessage());
            //now dump out the names of the tables in the database
            String[] types = new String[1];
            types[0] = "TABLES"; //set table type mask
            //note the %-sign is a wild card (not '*')
            try {
                tables = dma.getTables(null, null, "%", types);
            catch (SQLException ex) {
                System.err.println("database connection: " + ex.getMessage());
            try {
                while ( tables.next() ) {
                    if ( tbname.equalsIgnoreCase( tables.getString(1) ) ) {
                        tbexists = true;
            catch ( SQLException ex ) {
                System.err.println("database connection: " + ex.getMessage());
            return tbexists;
        // merge tablename using REGEX
        public String mergeTblName( String sqlcommand, String tbname ) {
            String REGEX = "TABLENAME";
            String INPUT = sqlcommand;
            String REPLACE = tbname;
            Pattern p = Pattern.compile(REGEX);
            Matcher m = p.matcher(INPUT); // get a matcher object
            INPUT = m.replaceAll(REPLACE);
            //System.out.println(INPUT);
            return INPUT;
        // merge feildnames specific terms using REGEX
        public String mergeFldName( Message msg ) {
            String sqlcommand;
            sqlcommand = "insert into TABLENAME values" +
                    " ('" + msg.getName() + "', '" + msg.getSurname() + "', " +
                    msg.getComputerType() + ", '" + msg.getComputerNAL() + "', " +
                    msg.getHaveMonitor() + ", '" + msg.getMonitorNAL() + "', '" +
                    msg.getDateOfMsg() + "');";
            sqlcommand = mergeTblName( sqlcommand, CurrentAuditTable );
            return sqlcommand;
        // get users input char
        /**public char getChar() {
            int i = System.in.read();
            while (i != -1) {
              // here's your character
              char c = (char) i;
              i = System.in.read();
            return (char) i;
        // load the config parameters from config.txt
        public void loadDbConfig() {
            // make a file obj pointing to the config file config.txt
            File configFile = new File( this.configFile );
            //...checks on configFile are elided
            StringBuffer contents = new StringBuffer();
            //declared here only to make visible to finally clause
            BufferedReader input = null;
            try {
              //use buffering
              //this implementation reads one line at a time
              input = new BufferedReader( new FileReader(configFile) );
              String line = null; //not declared within while loop
              int count = 0;
              while (( line = input.readLine()) != null){
                //first line in config file is dbPath
                if(count == 0) this.setDbPath( line.trim() );
                //second line in config file is ODBCDataSource
                if(count == 1) this.setODBCDataSource( line.trim() );
                count++; 
                //contents.append(line);
                //contents.append(System.getProperty("line.separator"));
            catch (FileNotFoundException ex) {
                System.err.println("the file congif.txt cannot be found ...");
                System.err.print("Enter the path to db file (e.g. c:\\temp): ");
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                //  read the db path from the command-line; need to use try/catch with the
                //  readLine() method
                try {
                    this.setDbPath( br.readLine() );
                catch (IOException ioe) {
                    System.out.println("IO error trying to read user input.");
                    System.exit(1);
                System.err.print("Enter the name of the ODBC Data Source: ");
                //  read the ODBC Data Source name from the command-line; need to use try/catch with the
                //  readLine() method
                try {
                    this.setODBCDataSource( br.readLine() );
                catch (IOException ioe) {
                    System.out.println("IO error trying to read user input.");
                    System.exit(1);
                ex.printStackTrace();
            catch (IOException ex){
              //ex.printStackTrace();
            finally {
              try {
                if (input!= null) {
                  //flush and close both "input" and its underlying FileReader
                  input.close();
              catch (IOException ex) {
                //ex.printStackTrace();
            //return contents.toString();
        // get datasource security details i.e. username and password
        public void getDSSecurity() {
            // get username
            System.out.print("Enter username for the ODBC DataSource: ");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            //  read the username from the command-line; need to use try/catch with the
            //  readLine() method
            try {
                this.setUsername( br.readLine() );
            catch (IOException ioe) {
                System.out.println("IO error trying to read username.");
                System.exit(1);
            // get password
            System.out.print("Enter password: ");
            //  read the username from the command-line; need to use try/catch with the
            //  readLine() method
            try {
                this.setPassword( br.readLine() );
            catch (IOException ioe) {
                System.out.println("IO error trying to read password.");
                System.exit(1);
        private void dumpResults(String head)
         //this is a general routine to print out
         //column headers and the contents of each column
         System.out.println(head);
          try
           //get the number of columns from the metadata
           this.rsmd = this.tables.getMetaData();      
           numCols = this.rsmd.getColumnCount();
           //print out the column names
           for (i = 1; i<= numCols; i++)
             System.out.print(rsmd.getColumnName(i)+"     ");
           System.out.println();
           //print out the column contents
           boolean more = this.tables.next();
           while (more)
             for (i = 1; i <= numCols; i++)
               System.out.print(this.tables.getString(i)+"     ");
             System.out.println();
             more = this.tables.next();
         catch(Exception e)
           {System.out.println(e.getMessage());}
        /** Creates a new instance of dbManager */
        public dbManager() {
            this.dbInitialize();
    }here is the result when I make a new dbManager obj from my server class which is a multithreaded one.
    H:\java>java EchoServer
    Enter username for the ODBC DataSource: admin
    Enter password: purina123
    Tables
    TABLE_CAT TABLE_SCHEM TABLE_NAME TABLE_TYPE REMARKS
    Listening for clients on 12111...
    here is the code of my server class called EchoServer:
    import java.net.*;
    import java.io.*;
    public class EchoServer
        ServerSocket m_ServerSocket;
        dbManager haDB;
        public EchoServer() 
            // db methods to setup a jdbc connection to the database
            haDB = new dbManager();
            // list tables
            //haDB.listTables();       
            //haDB.getDBTables();
            // create table
            //haDB.CreateTable("TestTable2");
            // update table
            // server code
            try
                // Create the server socket.
                m_ServerSocket = new ServerSocket(12111);
            catch(IOException ioe)
                System.out.println("Could not create server socket at 12111. Quitting.");
                System.exit(-1);
            System.out.println("Listening for clients on 12111...");
            // Successfully created Server Socket. Now wait for connections.
            int id = 0;
            while(true)
                try
                    // Accept incoming connections.
                    Socket clientSocket = m_ServerSocket.accept();
                    // accept() will block until a client connects to the server.
                    // If execution reaches this point, then it means that a client
                    // socket has been accepted.
                    // For each client, we will start a service thread to
                    // service the client requests. This is to demonstrate a
                    // multithreaded server, although not required for such a
                    // trivial application. Starting a thread also lets our
                    // EchoServer accept multiple connections simultaneously.
                    // Start a service thread
                    ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++, haDB);
                    cliThread.start();
                catch(IOException ioe)
                    System.out.println("Exception encountered on accept. Ignoring. Stack Trace :");
                    ioe.printStackTrace();
        public static void main (String[] args)
            new EchoServer();    
        class ClientServiceThread extends Thread
            Socket m_clientSocket;        
            int m_clientID = -1;
            dbManager m_db;
            boolean m_bRunThread = true;
            ClientServiceThread(Socket s, int clientID, dbManager db)
                m_clientSocket = s;
                m_clientID = clientID;
                m_db = db;
            public void run()
                // Obtain the input stream and the output stream for the socket
                // A good practice is to encapsulate them with a BufferedReader
                // and a PrintWriter as shown below.
                BufferedReader in = null; 
                PrintWriter out = null;
                Message msg = new Message();
                // Print out details of this connection
                System.out.println("Accepted Client : ID - " + m_clientID + " : Address - " + 
                                 m_clientSocket.getInetAddress().getHostName());
                try
                    in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
                    out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
                    // At this point, we can read for input and reply with appropriate output.
                    // Run in a loop until m_bRunThread is set to false
                    while(m_bRunThread)
                        // read incoming stream
                        String clientCommand = in.readLine();
                        if ( clientCommand.indexOf(",") != -1 ) {
                            msg.deserialize( clientCommand );
                            System.out.println("SQL command: " + m_db.mergeFldName(msg) );
                            m_db.dbUpdate( m_db.mergeFldName(msg) );
                            //System.out.println("Name :" + msg.getName() );
                            //System.out.println("Surname :" + msg.getSurname() );
                            //System.out.println("ComputerType :" + msg.getComputerType() );
                            //System.out.println("ComputerNAL :" + msg.getComputerNAL() );
                            //System.out.println("HaveMonitor :" + msg.getHaveMonitor() );
                            //System.out.println("Monitor NAL :" + msg.getMonitorNAL() );
                            //System.out.println("AuditDate :" + msg.getDateOfMsg() );                       
                        System.out.println("Client Says :" + clientCommand);
                        if(clientCommand.equalsIgnoreCase("quit"))
                            // Special command. Quit this thread
                            m_bRunThread = false;   
                            System.out.print("Stopping client thread for client : " + m_clientID);
                        else
                            // Echo it back to the client.
                            out.println(clientCommand);
                            out.flush();
                catch(Exception e)
                    e.printStackTrace();
                finally
                    // Clean up
                    try
                        in.close();
                        out.close();
                        m_clientSocket.close();
                        System.out.println("...Stopped");
                    catch(IOException ioe)
                        ioe.printStackTrace();
    }

    I find that taking any problem and reducing it to the simplest thing is the best way to approach it.
    Why you had to post all that bloody code (especially since you didn't write it) is beyond me.
    This will list all the tables in an Access database (or any other, for that matter):
    import java.sql.Connection;
    import java.sql.DatabaseMetaData;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import org.jdom.Element;
    import org.jdom.Document;
    import org.jdom.output.XMLOutputter;
    public class TableLister
        public static final String DRIVER   = "sun.jdbc.odbc.JdbcOdbcDriver";
        public static final String DATABASE = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
        public static final String USERNAME = "admin";
        public static final String PASSWORD = "";
        public static void main(String [] args)
            try
                String driver           = ((args.length > 0) ? args[0] : DRIVER);
                String url              = ((args.length > 1) ? args[1] : DATABASE);
                String username         = ((args.length > 2) ? args[2] : USERNAME);
                String password         = ((args.length > 3) ? args[3] : PASSWORD);
                Class.forName(driver);
                Connection conn         = DriverManager.getConnection(url, username, password);
                DatabaseMetaData meta   = conn.getMetaData();
                // Bring back ALL tables and views, including SYSTEM tables.
                ResultSet tables        = meta.getTables(null, null, null, null);
                ResultSetMetaData rsmd  = tables.getMetaData();
                int numColumns          = rsmd.getColumnCount();
                List columnNames        = new ArrayList();
                for (int j = 0; j < numColumns; ++j)
                    columnNames.add(rsmd.getColumnName(j+1));
                Element root = new Element("tables");
                int tableCount = 0;
                while (tables.next())
                    Element table = new Element("table");
                    table.setAttribute("id", Integer.toString(++tableCount));
                    for (int j = 0; j < numColumns; ++j)
                        Element column = new Element((String)columnNames.get(j));
                        column.setText(tables.getString((String)columnNames.get(j)));
                        table.addContent(column);
                    root.addContent(table);
                conn.close();
                Document doc = new Document(root);
                XMLOutputter outputter = new XMLOutputter("   ", true);
                System.out.println(outputter.outputString(doc));
            catch (ClassNotFoundException e)
                System.err.println("Couldn't load JDBC driver class");
                e.printStackTrace();
            catch (SQLException e)
                System.err.println("SQL state: " + e.getSQLState());
                System.err.println("SQL error: " + e.getErrorCode());
                e.printStackTrace();
            catch (Exception e)
                e.printStackTrace();
    }Run it and see if it works for you. If it does, put the essence of the code into your stuff.
    %

  • Query MS Access Database

    OK - I have a customer that wants to write out to an MS Access Database from Livecycle.  I know this is BAD but they have their reasons - i.e. they have a sever shortage of skills for anything more complex.
    Firstly - I created a Java program to test the JDBC ODBC connection - this worked fine - ran queries and updated OK (code is attached)
    Howver I have tried connecting to Access from within Livecycle in two different ways - both are failing
    Firstly - using the JNDI setup for JDBC ODBC e.g.
    <datasources>
      <local-tx-datasource>
        <jndi-name>MSAccess_DS</jndi-name>
        <!-- format of URL is "jdbc:odbc:DSNNAME" -->
        <connection-url>jdbc:odbc:DBFormData</connection-url>
        <driver-class>sun.jdbc.odbc.JdbcOdbcDriver</driver-class>
        <user-name></user-name>
        <password></password>
      </local-tx-datasource>
    </datasources>
    Calling this within a Livecycle process does not return an error to the process, but the log generates an error:
    2009-08-29 23:01:30,768 WARN  [org.jboss.resource.connectionmanager.JBossManagedConnectionPool] Throwable while attempting to get a new connection: null
    org.jboss.resource.JBossResourceException: Could not create connection; - nested throwable: (java.sql.SQLException: General error)
    I also tried creating a Java Component and importing it - by creating a very basic jar and importing it to livecycle (based on the same code I used in my Java testing)
    It also gave me the general error - and I can see it is happening on the line:
            Connection con = DriverManager.getConnection(dbURL, "","");
    Any ideas on what is going wrong, or a workaround?  (Assuming that I have to use Access)
    Thanks
    Tim

    OK I solved this.  This was only happening on the Win2K3 server - not on my local dev instance
    On the server I set the JBoss service to run under the local admin account (in the Services Panel) - after a service restart the jdbc odbc connection worked fine.  It must have been some permissions with the system account

  • How to create a ms-access database at runtime using java

    hi, this is ravi kiran,
    i have a situation where i need to create a new ms-access database with one table in it at runtime(when user clicks on some button).
    i have been searching many sites to know how to do this in java, but i didnot find any thing useful.
    plz tell me how to do this in java.
    plz help me, its urgent
    thanx in advance.

    Here's how I did it. Research does help, but sometimes looking at others code does too... You do have to have a dummy file that you made with access though. You can't just make a file file.mdb (it will be corrupt)
         public void createDatabase(String database) throws SQLException{
              try{
                   // This file needs to have been created with MS Access
                   File dbfile = new File(this.dataBaseDir + "dummy.mdb");
                   // This is the new database file being made
                   File newFile = new File(this.dataBaseDir + database + ".mdb");
                   // Copy all bytes from dummy file to new DB file.
                   FileInputStream instream = new FileInputStream(dbfile);
                   FileOutputStream ostream = new FileOutputStream(newFile);
                   int numBytes = instream.available();
                   byte inBytes[] = new byte[numBytes];
                   instream.read(inBytes, 0, numBytes);
                   ostream.write(inBytes, 0, numBytes);
              catch(FileNotFoundException e) { e.printStackTrace();}
              catch(IOException e) { e.printStackTrace();}
              if(DEBUG) System.out.println("creating the " + database + " database");
         }

  • Best Practice to Atomic Read and Write a Field In Database

    I am from Java Desktop Application background. May I know what is the best practice in J2EE, to atomic read and write a field in database. Currently, here is what I did
    // In Servlet.
    synchronized(private_static_final_object)
        int counter = read_counter_from_database();
        counter++;
        write_counter_back_to_database(counter);
    }However, I suspect the above method will work all the time.
    As my observation is that, if I have several web request at the same time, I am executing code within single instance of servlet, using different thread. The above method shall work, as different thread web request, are all referring to same "private_static_final_object"
    However, my guess is "single instance of servlet" is not guarantee. As after some time span, the previous instance of servlet may destroy, with another new instance of servlet being created.
    I also came across [http://code.google.com/appengine/docs/java/datastore/transactions.html|http://code.google.com/appengine/docs/java/datastore/transactions.html] in JDO. I am not sure whether they are going to solve the problem.
    // In Servlet.
    Transaction tx = pm.currentTransaction();
    tx.begin();
        int counter = read_counter_from_database();  // Line 1
        counter++;                                                  // Line 2
        write_counter_back_to_database(counter);    // Line 3
    tx.commit();Is the code guarantee only when Thread A finish execute Line 1 till Line 3 atomically, only Thread B can continue to execute Line 1 till Line 3 atomically?
    As I do not wish the following situation happen.
    (1) Thread A read counter from Database as 0
    (2) Thread A increment counter to 1
    (3) Thread B read counter from Database as 0
    (4) Thread A write counter as 1 to database
    (5) Thread B increment counter to 1
    (6) Thread B write counter as 1 to database
    What I wish is
    (1) Thread A read counter from Database as 0
    (2) Thread A increment counter to 1
    (4) Thread A write counter as 1 to database
    (3) Thread B read counter from Database as 1
    (5) Thread B increment counter to 2
    (6) Thread B write counter as 2 to database
    Thanks you.
    Edited by: yccheok on Oct 27, 2009 8:39 PM

    This is my understanding of the issue (you should research it further on you own to get a better understanding):
    I suggest you use local variables (ie, defined within a function), and keep away from static variables. Those local variables are thread safe. If you call functions within functions, its still thread safe. If you read or write to one record in a database using sql, its thread safe (you dont need a transaction). If you read/write to multiple tables and/or records, you probably need a transaction. Servlets are thread safe. You usually dont need the 'synchronized' word anywhere unless you have a function updating/reading a static variable and therefore want to ensure only one user is accessing the static varible at a time. Also do so if you are writing to some resource (such as a file, a variable in applicaton scope, session scope, or resource that everyone uses such as email server). You dont want more than one person at a time to write to it). Note the database is one of of those resources that is handled by transactions rather than the the synchronized keyword (the synchronized keyword is applied to your application only (not other applications that someone is running), whereas the transaction ensures all applications are locked out while you update those records in the database).
    By the way, if you have a static variable, you should have one and only one function (synchronized) that updates it that everyone uses. If you have more than one synchronized function, that updates it, its probably not thread safe.
    An example of a static variable you would use is a Datasource object (to obtain your database connections). You only need one connection pool in your application and you access it via the datasource variable.
    If you're unsure your code is thread safe, you can create two seperate threads that call the same block of functions repeatedly to ensure it works as expected.

  • How to extract the budget data from essbase to Ms access database

    Hi,
    i want to know how to extract budget dat fro hyperion to Ms access database
    please help me in this regard how to proceed, and what are the process i need to follow
    Regards
    Hypuser

    You can write a Calc script to export only the 'Budget' data and loaded back the exported file into MS Database via Loader or import.
    Cheers
    Cnee:)

  • Insert Image file from java to ms access database

    Are there any ways to insert image file or any files into microsoft access database and retrieve the file from the database. Guild will be helpful.Thank you.
    regards
    Singaravelan

    The right answer? Don't do it. You should not be putting images in any database.
    Better to write the image to the server's file system and add the path/link to the database instead.
    %

  • Getting image from Microsoft Access database to display in browser

    Hey! anybody please help me
    I've been trying with no success to get an image from a microsoft access database
    so far this is what i have:
    package Servlets;
    import java.io.*;
    import java.net.*;
    import utils.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class serv extends HttpServlet {
        java.sql.ResultSet rs=null;
        ClsConexion conexion=new ClsConexion("Nedermex");
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            conexion.conectate("1", "1");
            rs=conexion.obtenRegSelect("SELECT * FROM Flores WHERE ID=1");
            try{
                rs.next();
                System.out.println("sadfsadf " + rs.getString("ID"));
            }catch(Exception e){
                e.printStackTrace();
            String ubicGIF = request.getParameter("ubicGIF");
            if((ubicGIF==null) || ubicGIF.length() == 0 ){
                indicarError(response, "Archivo de imagen no establecido");
                return;
            //String archivo = getServletContext().getRealPath(ubicGIF);
            try{
                if(rs.next()){
                    System.out.println("sadfsadf " + rs.getString("ID"));
                    BufferedInputStream ingreso = new BufferedInputStream(rs.getBinaryStream("Imagen"));
                   // BufferedInputStream ingreso = new BufferedInputStream(new FileInputStream(getServletContext().getRealPath("1.jpg")));
                    ByteArrayOutputStream flujoBytes = new ByteArrayOutputStream(512);
                    int byteImagen;
                    while ((byteImagen= ingreso.read()) != -1){
                        flujoBytes.write(byteImagen);
                    ingreso.close();
                    String indiPersistencia = request.getParameter("usePersistence");
                    boolean usePersistence = ((indiPersistencia == null) || (!indiPersistencia.equals("no")));
                    response.setContentType("image/jpeg");
                    if(usePersistence){
                        response.setContentLength(flujoBytes.size());
                    flujoBytes.writeTo(response.getOutputStream());
            }catch(IOException ioe){
                indicarError(response, "Error: " + ioe);
            }catch(java.sql.SQLException sqle){
                indicarError(response, "Error: " + sqle);
        public void indicarError(HttpServletResponse response, String mensaje) throws IOException {
            response.sendError(response.SC_NOT_FOUND, mensaje);
        // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
        /** Handles the HTTP <code>GET</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Handles the HTTP <code>POST</code> method.
         * @param request servlet request
         * @param response servlet response
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
        // </editor-fold>
    }i have a class Conexion wich controls the connection and resultsets
    As you can see, i tested accessing a jpeg file: 1.jpg with FileInputStream, and it works perfectly, but when i try to get an image from Microsoft Access using the resultset the way i did, the browser shows the following message
    The image �http://localhost:8084/Nedermex/serv� cannot be displayed, because it contains errors.
    My table in the database in Access is configured as following
    FieldName::::::::::::::DataType
    ID::::::::::::::::::::::::::::::Number
    Imagen::::::::::::::::::::OLE Object
    Now, when i insert an image in the Imagen field, i select the option "Create from file" and select the jpg file (the one that worked with the FileInputStream) and uncheck the Link option (to save the data in the db
    maybe there is something wrong with the sizes or something....
    please help me here!!!
    thank you!

    Yes it is an sql question
    Consider this as my condition need to fetch records collected in database on 16-4-2012 
    Table name =TEST_REPORT
    i have passed the following query
    Select Serial_Number,System_Date,System_Time,Department,O​perator_Name,Serial_Number,Test_Case,Pass_Fail from TEST_REPORT  where System_Date = 4-16-2012, it displays the entire record from database. i have my vi along with this mail.
    Attachments:
    Report Viewer.vi ‏24 KB

Maybe you are looking for