The E
The E

Reputation: 747

Why won't my Java Class write to a database?

I'm having trouble getting Java to write to a database.

I have the following code that compiles and runs with no errors.

import java.sql.*;
import java.lang.reflect.*;
import java.lang.reflect.Array;

public class InquireRecord {

    private String submitter;

    public static void main(String[] args) {
        InquireRecord Stub = new InquireRecord();
        Stub.sendToDb("insert into inquiries (submitter) values ('Rodger Dunn')");
    }

    public InquireRecord() {
        super();
    }

    public void sendToDb(String queryString){
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String filename = "C:/Development/inquire.mdb";
            String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
            database+= filename.trim() + ";DriverID=22;READONLY=true}";
            Connection con = DriverManager.getConnection( database ,"","");
            Statement s = con.createStatement();
            s.execute (queryString);    
        }
        catch (Throwable e) {
            System.out.println(e);
        }
    }
}

The file C:/Development/inquire.mdb exists and is writeable. It is not being used by anything else.

The database has 2 fields: ID (which increments and is the index) and submitter which is a text field with a length of 255.

I don't get any errors when it runs or when it compiles. But no data ever appears in the database. I'm brand new to Java, but not to SQL. What am I missing?

Upvotes: 2

Views: 467

Answers (2)

Christian
Christian

Reputation: 1706

I guess you should close (con.close()) the connection before exiting the program.

Upvotes: 1

Costis Aivalis
Costis Aivalis

Reputation: 13728

Modify your catch:

try {
    Class.forName(....);
} catch (ClassNotFoundException e) {
    System.out.println(e.getMessage());
    System.exit(1);
}
try {        
   ...your SQL commands...
} catch (SQLException sqe) { 
   System.out.println(sqe.getMessage();
}

in order to see what happens.

As Howard also commented above the READONLY could be a problem...

Upvotes: 0

Related Questions