Here is my code:
package dsnless;
import java.sql.*;
////////////////////////////////////////////////////////////
//This class will be used to fire queries to the database
////////////////////////////////////////////////////////////
public class Query {
public Query(){
String pathToDatabase = "E:/Eclipse Projects/JDBC/src/datasouce/School.mdb";
String database = "jdbc:odbc:Driver="+
"{Microsoft Access Driver(*.mdb,*.accdb)};" +
":DBQ=" + pathToDatabase;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(database);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
new Query();
}
Connection con;
Statement s;
ResultSet r;
}//class Query end
Here is the exception:
java.sql.SQLException: [Microsoft][ODBC Driver Manager] DRIVER keyword syntax error
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at dsnless.Query.<init>(Query.java:14)
at dsnless.Query.main(Query.java:20)
And there is a new exception, too:
[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at dsnless.Query.<init>(Query.java:14)
at dsnless.Query.main(Query.java:20)
Question
Please tell me what is wrong. I suspect it is the String database but stil it is only a guess.
Nailed it, myself
I changed the extensions supported from (*.mdb,*.accdb) to only (*.mdb) and it worked. Any idea as to why that happened???
You have an additional colon here, remove it
String database = "jdbc:odbc:Driver="+
"{Microsoft Access Driver(*.mdb,*.accdb)};" +
":DBQ=" + pathToDatabase;
^
Related
I've been scratching my head for the past few hours wondering what is wrong. I want to edit a Date/Time format on my access database and it'a just keeps on confusing me as to why I cant update it. This is my code and I will explain. . .
This is the Main class where there's a button that says update and when clicked will lead to another class called UpdateBooking_Run()
public MainInterface() {
JButton updateBookings = new JButton("UPDATE");
updateBookings.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
UpdateBooking_Run ub = new UpdateBooking_Run();
ub.setVisible(true);
}
});
}
This is UpdateBooking_Run() without the textboxes only the button inside this class...As you can see from string, I converted the date to java.sql.Date
public class UpdateBooking_Run extends JFrame {
public static java.sql.Date sqldate;
public UpdateBooking_Run() {
JButton btnAdd = new JButton("UPDATE");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Integer.parseInt(yearBookings.getText().trim());
}
catch (NumberFormatException na) {
JOptionPane.showMessageDialog(null, "Please input year", "Error", JOptionPane.ERROR_MESSAGE);
}
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
String mu = monthBookings.getSelectedItem().toString();
String da = dayBookings.getSelectedItem().toString();
String ye = yearBookings.getText().trim();
String dat = ye + "/" + mu + "/" + da ;
java.util.Date date = null;
try {
date = df.parse(dat);
} catch (ParseException e) {
e.printStackTrace();
}
sqldate = new java.sql.Date(date.getTime());
try {
UpdateConn_Run uc = new UpdateConn_Run();
uc.updateDate();
}
catch (Exception en) {
en.printStackTrace();
}
}
});
}
}
As you can see in the code above, I set sqldate as static mainly because it worked with updating string on my other classes but I just cant seem to update Date. . .
Then this is the connection... Or UpdateConn_Run()
public class UpdateConn_Run {
Connection con;
Statement st;
ResultSet rs;
StringBuffer results;
String url = "jdbc:ucanaccess://C://DATABASE//DATA.accdb";
PreparedStatement ps;
public void updateBooking() {
try {
int i = 1;
UpdateBooking_Run ubr = new UpdateBooking_Run();
MainInterface mi = new MainInterface();
Date da = UpdateBooking_Run.sqldate;
con = DriverManager.getConnection(url);
//theres actually an uneditable textbox in MainInterface that shows the ID of the selected row
int id = Integer.parseInt(mi.idstringBookings);
String sql = "UPDATE bookings SET date ='"+da+"' WHERE ID ='"+id+"'";
ps = con.prepareStatement(sql);
ps.executeUpdate();
ps.close();
con.close();
if (i == 1) {
JOptionPane.showMessageDialog(null, "Database has been updated please click Refresh");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
I also seem to get the error...
net.ucanaccess.jdbc.UcanaccessSQLException: data exception: invalid datetime format
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.executeUpdate(UcanaccessPreparedStatement.java:261)
at interfaceSystem.UpdateConn_Run.updateBooking(UpdateConn_Run.java:109)
at interfaceSystem.UpdateBooking_Run$2.actionPerformed(UpdateBooking_Run.java:284)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(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.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(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)
But it still confuses me . . .
It says invalid datetime format so I went ahead and changed the format again and again. Even tried the format in MS Access the problem still persists.
Tried not putting in the date as static. I just get "null".
Can someone explain why static is used for updating databases in PreparedStatements? Still confuses me to this day... (Everyone in my class seems to be using it although I have no idea why)
I am sorry for my English. I am not a native speaker so I appreciate it if you have questions regarding grammar...
Since you're using a PreparedStatement, you should be using placeholders and your code should be as follow:
query = "UPDATE bookings SET date = ? WHERE id = ?";
preparedStatement = con.prepareStatement(query);
preparedStatement.setDate(1, da);
preparedStatement.setInt(2, id);
preparedStatement.executeUpdate();
Because you're including a Date object into a String, it will be parsed using its toString() method, and your statement will look like:
"UPDATE bookings SET date = 2000-01-12 WHERE id = 22"
I don't do Java, but your final SQL for Access must look like this:
"UPDATE bookings SET date = #2017/03/21# WHERE ID = '1'";
or, if ID is numeric:
"UPDATE bookings SET date = #2017/03/21# WHERE ID = 1";
Thus, something like:
//datestring = da formatted as "2017/03/20"
String sql = "UPDATE bookings SET date =#"+datestring+"# WHERE ID ='"+id+"'";
I'm trying to connect to an external database and no matter what I do I keep getting the following error:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at DbCon.main(DbCon.java:10)
My code to set up the driver:
import java.sql.*;
public class DbCon {
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
I've tried omitting the driver entirely, and just trying to connect with:
String connectionUrl = "jdbc:sqlserver://xxx.xxx.xxx.xxx:1433;databaseName=xxxx;user=xxxx;password=xxxx;";
try {
Connection con = DriverManager.getConnection(connectionUrl);
} catch (SQLException e) {
e.printStackTrace();
}
This only gets me the following error:
java.sql.SQLException: No suitable driver found for xxxx
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DbCon.main(DbCon.java:15)
I've tried adding the jar to Eclipse's classpath, I've added the folder to the project's build path as an external class folder.
Is there something I'm missing?
I do not want to install a database server on target machine. It is possible that we can simply ship a jar file with the database embedded in it, and not worry about installing a database server separately?
I created one application in netbeans using derby and it is working fine in my pc but when i am running on other machine it is giving me an Exception
My code is
System.setProperty("derby.drda.startNetworkServer", "true");
try {
NetworkServerControl serverControl = new NetworkServerControl();
serverControl.start(new PrintWriter(System.out, true));
} catch (Exception e) {
e.printStackTrace();
}
For connection i wrote this code
public static Connection getderbyConnection() throws ClassNotFoundException, SQLException
{
String url = "jdbc:derby://localhost:1527/XLS_Uniquewordlist;create=true";
String user = "root";
String password = "mantra";
Class.forName("org.apache.derby.jdbc.ClientDriver");
return (Connection) DriverManager.getConnection(url, user, password);
}
I am getting this exception
Exception in thread "DRDAConnThread_2" java.lang.NoSuchMethodError:
org.apache.derby.iapi.jdbc.EnginePreparedStatement.getVersionCounter()J
at org.apache.derby.impl.drda.DRDAStatement.prepare(Unknown Source)
at org.apache.derby.impl.drda.DRDAStatement.explicitPrepare(Unknown
Source)
at org.apache.derby.impl.drda.DRDAConnThread.parsePRPSQLSTT(Unknown
Source)
at org.apache.derby.impl.drda.DRDAConnThread.processCommands(Unknown
Source)
at org.apache.derby.impl.drda.DRDAConnThread.run(Unknown Source)
May 12, 2015 5:17:59 PM xls_parser.Main_panel btnokActionPerformed
SEVERE: null
java.sql.SQLSyntaxErrorException: DERBY SQL error: SQLCODE: -20001, SQLSTATE: 42X05, SQLERRMC: APP.UNIQUEWORDLIST42X05
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown
Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown
Source)
at org.apache.derby.client.am.Connection.prepareStatement(Unknown Source)
I'm trying to connect to HSQL using java. I'm using a tutorial to work with JDBC and hibernate. It's the lynda tutorials. Anyway, here's the code below:
package com.lynda.javatraining.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
private static final String USERNAME = "dbuser";
private static final String PASSWORD = "dbpassword";
private static final String CONN_STRING =
"jdbc:hsqldb://data/explorecalifornia";
public static void main(String[] args) throws SQLException {
//Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
System.out.println("A");
System.out.println(conn == null);
System.out.println(CONN_STRING);
try {
System.out.println("B1");
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("B1-2");
System.out.println("Connected!");
} catch (SQLException e) {
System.out.println("B2");
System.err.println(e);
} finally {
System.out.println("B3");
if (conn != null) {
conn.close();
}
}
System.out.println("C");
}
}
Here's the error I'm getting:
A
true
jdbc:hsqldb://data/explorecalifornia
B1
2014-06-27T15:26:27.430-0400 SEVERE could not reopen database
org.hsqldb.HsqlException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile#76d682a[file =/data/explorecalifornia.lck, exists=false, locked=false, valid=false, ] method: openRAF reason: java.io.FileNotFoundException: /data/explorecalifornia.lck (No such file or directory)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.persist.LockFile.newLockFileLock(Unknown Source)
at org.hsqldb.persist.Logger.acquireLock(Unknown Source)
at org.hsqldb.persist.Logger.openPersistence(Unknown Source)
at org.hsqldb.Database.reopen(Unknown Source)
at org.hsqldb.Database.open(Unknown Source)
at org.hsqldb.DatabaseManager.getDatabase(Unknown Source)
at org.hsqldb.DatabaseManager.newSession(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.lynda.javatraining.db.Main.main(Main.java:24)
B2
java.sql.SQLException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile#76d682a[file =/data/explorecalifornia.lck, exists=false, locked=false, valid=false, ] method: openRAF reason: java.io.FileNotFoundException: /data/explorecalifornia.lck (No such file or directory)
B3
C
Can anyone tell e what I"m doing wrong? Thanks.
A database has a lock file explorecalifornia.lck that prevents communication. You should delete lock file and restart the database. This may happens from time to time when you accidentally shutdown the database or system.
See the syntax of the command used from the command line to invoke shutdown. There's also an option how to shutdown server in Java.
Please have a look at the following code
package normal;
//This class if s for checking the database. If the database doesn't exists, this class will create one
import java.sql.*;
public class DatabaseCheck
{
private Connection con;
public DatabaseCheck()
{
createConnection();
try
{
Statement st = con.createStatement();
st.executeQuery("select * from PhoneData");
}
catch(Exception e)
{
System.out.println(e.getLocalizedMessage());
if(e.getLocalizedMessage().equals("Schema 'SA' does not exist"))
{
try
{
PreparedStatement ps = con.prepareStatement("create table PhoneData(ids int identity constraint pkId primary key,names varchar(20),mobileNumber1 varchar(20),mobileNumber2 varchar(20),landNumber1 varchar(20),landNumber2 varchar(20),address varchar(100),category varchar(20),nickName varchar(20),email varchar(20),middleName varchar(20),lastName varchar(20),city varchar(20),country varchar(20))");
ps.execute();
PreparedStatement ps2 = con.prepareStatement("create table Emails(accountType varchar(10) constraint pk_user primary key,userName varchar(50) ,passwords varchar(50))");
ps2.execute();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
}
finally
{
closeConnection();
}
}
public void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
con = DriverManager.getConnection("jdbc:derby:PhoneBook;create=true","sa","sasasa");
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void closeConnection()
{
try
{
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This class is capable of programmatically creating tables in embedded apache derby database. But, it gives the following error
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement20.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement30.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement40.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver40.newEmbedPreparedStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at normal.DatabaseCheck.<init>(DatabaseCheck.java:27)
at normal.MyPhoneBookApp.main(MyPhoneBookApp.java:25)
Caused by: java.sql.SQLException: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 15 more
Caused by: ERROR 42X01: Syntax error: Encountered "identity" at line 1, column 32.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.ParserImpl.parseStatement(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
... 9 more
When I remove the "identity" keyword from the table creation code, this work fine. But, auto generation of ID's is mandatory. Please help!
Derby has no identity column type (as documented in the manual). You need to define a generated column. For the generation definition, Derby indeed knows an identity attribute, but that's not a datatype.
So the column definition for ids should be
ids integer generated always as identity constraint pkId primary key
Note that you can also use generated by default instead of always. Then a value will only be generated if you don't specify a value for that column during insert. generated always will overwrite any value you provide.
The Apache Derby documentation indicates you can replace the identity keyword with:
NOT NULL GENERATED ALWAYS AS IDENTITY