java.sql.SQLNonTransientConnectionException: java.net.ConnectException: Error connecting to server localhost on port 1527 with message Connection refused: connect.
I am using Netbeans. If I go to the Services Tab and rightclick Java DB and start Server it works fine.
How can I do this programmatically at Runtime? I just need whatever method will start the Java DB Server.
public class login extends javax.swing.JFrame {
public void close() {
WindowEvent close = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(close);
}
public login() {
try {
initComponents();
((JLabel) jComboBox1.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
Calendar currentdate = new GregorianCalendar();
int year1 = currentdate.get(Calendar.YEAR);
for (int i = 2000; i <= year1; i++) {
jComboBox1.insertItemAt(i, jComboBox1.getItemCount());
}
NetworkServerControl server = new NetworkServerControl();
server.start(null);
} catch (Exception ex) {
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
}
} private void loginbtnActionPerformed(java.awt.event.ActionEvent evt) {
try {
String url = "jdbc:derby://localhost:1527/PreSchool";
String user = "admin1";
String pass = "admin1";
Connection con = DriverManager.getConnection(url, user, pass);
Statement stat = con.createStatement();
String query = "SELECT * FROM admin1.login WHERE username ='" + usertxt.getText() + "'";
ResultSet rs = stat.executeQuery(query);
while (rs.next()) {
if ((usertxt.getText().equalsIgnoreCase(rs.getString("username"))) && (passtxt.getText().equalsIgnoreCase(rs.getString("password")))) {
switch (rs.getString("department")) {
case "0": {
manager man = new manager();
man.setVisible(true);
break;
}
case "1": {
program pr = new program();
pr.setVisible(true);
break;
}
}
}
}
close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
}
and this is derby.log:
An exception was thrown during network server startup. org.apache.derby.impl.drda.NetworkServerControlImpl.<init>(java.lang.String, java.lang.String)
java.security.PrivilegedActionException: java.lang.NoSuchMethodException: org.apache.derby.impl.drda.NetworkServerControlImpl.<init>(java.lang.String, java.lang.String)
at java.security.AccessController.doPrivileged(Native Method)
at org.apache.derby.iapi.jdbc.DRDAServerStarter.boot(Unknown Source)
at org.apache.derby.impl.drda.NetworkServerControlImpl.start(Unknown Source)
at org.apache.derby.drda.NetworkServerControl.start(Unknown Source)
at login.<init>(login.java:33)
at login$3.run(login.java:231)
at java.awt.event.InvocationEvent.dispatch(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.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)
Caused by: java.lang.NoSuchMethodException: org.apache.derby.impl.drda.NetworkServerControlImpl.<init>(java.lang.String, java.lang.String)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at org.apache.derby.iapi.jdbc.DRDAServerStarter$1.run(Unknown Source)
... 20 more
Related
I am getting this error while executing my java swing code.
How to solve this? I have found some questions similar to this but didn't got the required answers.
I am making a desktop application which will read tables from excel sheet and will update the table values in a database.
Here is the code snippet:
Main code from where I am reading and calling the database query
if (flag) {
int j=0;
String[] productArray= new String[2];
for (int i = 0; i < cr.getPhysicalNumberOfCells(); i++) {
String colKeyOrTabName = getCellValueAsString((cr
.getCell(firstCell + i)));
colKeyOrTabName=colKeyOrTabName.replaceAll(" ", "");
//colKeyOrTabName=colKeyOrTabName.replaceAll("[^a-zA-Z0-9-]", "");
productArray[j]=colKeyOrTabName;
j++;
//System.out.println(" "+ colKeyOrTabName);
}
if(!productArray[0].equalsIgnoreCase("code")){
DBConfig.insertCodes(productArray[0], productArray[1]);
}
/*Ends Here*/
rowNo++;
continue;
}
DB Code :
public class DBConfig {
private static BasicDataSource bds = null;
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// logger.error("Error - " + String.valueOf(e), e);
throw new RuntimeException(
"Error setting connection with SyntBots database");
}
bds = new BasicDataSource();
// set driver class name
bds.setDriverClassName("com.mysql.jdbc.Driver");
// Define Server URL
bds.setUrl(Config.get("config.db.url"));
// Define Username
bds.setUsername(Config.get("config.db.user"));
// Define Your Password
bds.setPassword(Config.get("config.db.password"));
}
public static void insertCodes(String code, String value) {
// TODO Auto-generated method stub
Connection con = null;
Statement stmt = null;
try {
// Connection conn = null;
con = bds.getConnection();
stmt = con.createStatement();
String sql = "insert into table(code,value) value('" + code+ "','"+ value+"')";
try{
stmt.executeUpdate(sql);
}
catch(SQLException e){
if(e.getErrorCode() == MYSQL_DUPLICATE_PK ){
System.out.println("Duplicate Entry"); }
}
// con.close();
} catch (Exception e) {
//logger.error("Ignore Error - " + String.valueOf(e), e);
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
}
}
if (null != con) {
try {
con.close();
} catch (SQLException e) {
}
}
}
}
}
And here is the error(Console output) :
Button clicked
D:\DesktopApplicationInputSheet
Sample.xlsx
D:\DesktopApplicationInputSheet/Sample.xlsx
Reading sheet: 0, Name: Sheet1
i: 1
0
Display Name :-Polaris Code rowNO - 1
Display Name :-AOO1 rowNO - 2
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at
com.dataentry.excel.MainDataEntry.readRequestTable(MainDataEntry.java:249)
at
com.dataentry.excel.MainDataEntry.readExcelandWriteonDB(MainDataEntry.java:149)
at
com.dataentry.excel.MainDataEntry.readExcelPath(MainDataEntry.java:79)
at
com.dataentry.excel.MainDataEntry$1.actionPerformed(MainDataEntry.java:57)
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)
Caused by: java.lang.RuntimeException: Error setting connection with SyntBots database
at com.dataentry.excel.DBConfig.<clinit>(DBConfig.java:26)
... 40 more
Update :
The Issue is fixed. It was of the case of missing JAR for MySQL driver.
But after that I am facing a new issue.
Have a look at the console output:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: org.apache.commons.pool2.impl.GenericObjectPool.setTestOnCreate(Z)V
at org.apache.commons.dbcp2.BasicDataSource.createConnectionPool(BasicDataSource.java:2074)
at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:1920)
at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1413)
at com.dataentry.excel.DBConfig.insertCodes(DBConfig.java:59)
at com.dataentry.excel.MainDataEntry.readRequestTable(MainDataEntry.java:249)
at com.dataentry.excel.MainDataEntry.readExcelandWriteonDB(MainDataEntry.java:149)
at com.dataentry.excel.MainDataEntry.readExcelPath(MainDataEntry.java:79)
at com.dataentry.excel.MainDataEntry$1.actionPerformed(MainDataEntry.java:57)
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)
Well I have found the answer to my problem.
In my case it was related to the version of commons-pool2-2 jar file.
Instead of 2.4.2, I was using 2.0.
After changing the JAR to 2.4.2 it started working as expected.
Also I have used the mysql-connector-java-5.1.18 to resolve my previous issue.
NOTE : What I have found from the internet is that JAR compatibility is also need to fix the program.
I'm trying to create an multithreaded app (Java) in which some threads insert further rows to database. I use Embedded Derby from JDK.
This is code that concerns establishing connection to database and inserting.
public class DatabaseConnection
{
private static String dbURL = "jdbc:derby:./Database/DB;create=true;user=fafejs;password=fafejs";
private Connection conn;
private DatabaseUpdateContent duc;
private DatabaseUpdateView duv;
public synchronized void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); // load the driver
conn = DriverManager.getConnection(dbURL); // make Derby JDBC connection
duc = new DatabaseUpdateContent(conn);
duv = new DatabaseUpdateView(conn);
System.out.println(conn);
}
catch (Exception except) // TODO - obsluga
{
except.printStackTrace();
}
}
public synchronized void recreateConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
conn = DriverManager.getConnection(dbURL);
duc = new DatabaseUpdateContent(conn);
duv = new DatabaseUpdateView(conn);
System.out.println("Reconnect:" + conn);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public boolean updatePlayer(PlayerService player)
{
try
{
int ID = player.getID();
String firstName = player.getFirstName();
String lastName = player.getLastName();
Date birthdate;
if(!(player.getDate() == null))
birthdate = new java.sql.Date(player.getDate().getTime());
else
birthdate = null;
String league = newLeagueName(player.getLeagueName()).toUpperCase();
String team = player.getTeamName();
int apps = player.getApps();
int firstSquad = player.getFirstSquad();
int minutes = player.getMinutes();
int goals = player.getGoals();
int yellowCards = player.getYellowCards();
int redCards = player.getRedCards();
duc.updatePlayersTable(ID, firstName, lastName, birthdate);
duc.updateLeagueTable(league, ID, team, apps, firstSquad, minutes, goals, yellowCards, redCards);
return true;
}
catch (SQLException sqlExcept)
{
//shutdown();
sqlExcept.printStackTrace();
return false;
}
}
public synchronized void shutdown()
{
try
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
//System.gc();
}
catch (SQLException sqlExcept)
{
//sqlExcept.printStackTrace();
}
}
}
public void updatePlayersTable(int ID, String firstName, String lastName, Date birthdate) throws SQLException // z klasy DatabaseUpdateContent
{
PreparedStatement pstmt = conn.prepareStatement("UPDATE APP.PLAYERS SET FIRST_NAME = ?, LAST_NAME = ?, BIRTHDATE = ? WHERE ID = ?");
pstmt.setString(1,firstName);
pstmt.setString(2,lastName);
pstmt.setDate(3,birthdate);
pstmt.setInt(4,ID);
if(pstmt.executeUpdate() == 0)
{
pstmt = conn.prepareStatement("INSERT INTO APP.PLAYERS VALUES (?,?,?,?)");
pstmt.setInt(1, ID);
pstmt.setString(2, firstName);
pstmt.setString(3, lastName);
pstmt.setDate(4, birthdate);
pstmt.execute();
}
pstmt.close();
}
public void updateDB() // procedura, która zajmuje się aktualizacją zawartości bazy danych
{
DatabaseConnection database = new DatabaseConnection();
database.createConnection();
for(PlayerService player: players)
{
while(!database.updatePlayer(player))
{
database.recreateConnection();
}
}
database.shutdown();
}
On the whole, strongly most rows are inserted to appropriate table properly, but sometimes i get SQLNonTransientConnectionException:
java.sql.SQLNonTransientConnectionException: No current connection.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.noCurrentConnection(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkIfClosed(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.setupContextStack(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at DatabaseService.DatabaseUpdateContent.updateLeagueTable(DatabaseUpdateContent.java:39)
at DatabaseService.DatabaseConnection.updatePlayer(DatabaseConnection.java:68)
at DataService.TeamService.updateDB(TeamService.java:66)
at DataService.TeamService.getPlayers(TeamService.java:56)
at DataService.TeamService.getPlayersUrls(TeamService.java:44)
at DataService.LeagueService.getTeams(LeagueService.java:52)
at DataService.LeagueService.run(LeagueService.java:35)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR 08003: No current connection.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 17 more
java.sql.SQLException: Database './Database/DB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at DatabaseService.DatabaseConnection.recreateConnection(DatabaseConnection.java:35)
at DataService.TeamService.updateDB(TeamService.java:69)
at DataService.TeamService.getPlayers(TeamService.java:56)
at DataService.TeamService.getPlayersUrls(TeamService.java:44)
at DataService.LeagueService.getTeams(LeagueService.java:52)
at DataService.LeagueService.run(LeagueService.java:35)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR XJ004: Database './Database/DB' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
This exception occurs many times in a row, because if updating player fails, function updatePlayer will return false and we repeat loop in function updateDB. But after a while (about 50 attempts of inserting row), it's possible to establish connection and insert a row.
Certainly i've looked for solution of this problem. I tried way associated with System.gc(), what is suggested in some documentation but it doesn't help in my case.
I was considering also fact that my problem could be connected with multithreading of my app but in Embedded Derby's documentation they say in short that Embedded Derby should deal with it.
Thanks for your support in advance.
EDIT
This is error information that I get after adding code from http://wiki.apache.org/db-derby/UnwindExceptionChain:
----- SQLException -----
SQLState: 08003
Error Code: 40000
Message: No current connection.
java.sql.SQLNonTransientConnectionException: No current connection.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.noCurrentConnection(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.checkIfClosed(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.setupContextStack(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at DatabaseService.DatabaseUpdateContent.updatePlayersTable(DatabaseUpdateContent.java:17)
at DatabaseService.DatabaseConnection.updatePlayer(DatabaseConnection.java:73)
at DataService.TeamService.updateDB(TeamService.java:64)
at DataService.TeamService.getPlayers(TeamService.java:53)
at DataService.TeamService.getPlayersUrls(TeamService.java:39)
at DataService.LeagueService.getTeams(LeagueService.java:50)
at DataService.LeagueService.run(LeagueService.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR 08003: No current connection.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 17 more
java.sql.SQLException: Database './Database/DB' not found.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleDBNotFound(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.<init>(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.InternalDriver.connect(Unknown Source)
at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at DatabaseService.DatabaseConnection.recreateConnection(DatabaseConnection.java:39)
at DataService.TeamService.updateDB(TeamService.java:67)
at DataService.TeamService.getPlayers(TeamService.java:53)
at DataService.TeamService.getPlayersUrls(TeamService.java:39)
at DataService.LeagueService.getTeams(LeagueService.java:50)
at DataService.LeagueService.run(LeagueService.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: ERROR XJ004: Database './Database/DB' not found.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 20 more
It seems to me that error associated with not finding database (to be more precise, I mean problem connected with loading the driver of Embedded Derby) is caused by SQLNonTransientConnectionException and there is the rub.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm creating a software in Java which should be able to register artists, Albums and Tracks as well.
Everything is connected to a MySQL DB, the software requires only artist name, I show you the methods I created. I'm sorry many of the names are in Spanish, but this
is for my school and I can't use too many english words. I think you can understand it
This is the class Conexión which makes the connection to the DB:
public class Conexion {
Connection conexion=null;
/*Conectamos a la Base de Datos*/
public Conexion(){
try{
Class.forName("com.mysql.jdbc.Driver");
conexion=DriverManager.getConnection("jdbc:mysql://localhost/chinook", "root", "");
}catch(Exception excepcion){
excepcion.printStackTrace();
}
}
/*Devolvemos la conexion*/
public Connection getConnection(){
return conexion;
}
/*Cerramos la conexión a la Base de Datos*/
public void desconectar(){
try{
conexion.close();
}catch(Exception excepcion){
excepcion.printStackTrace();
}
}
}
This is the class Coordinador, this class is used to make the union among different classes (following model MVC), I paste you the part from adding the artist, the others are just related to views:
public void addArtista(ArtistaVO artistaVO){
miLogica.validarRegistroArtista(artistaVO);
}
The class ArtistaVO where I create get and set of the artist:
public class ArtistaVO {
private int idArtista;
private String nombreArtista;
public int getIdArtista(){
return idArtista;
}
public void setIdArtista(int idArtista){
this.idArtista=idArtista;
}
public String getNombreArtista(){
return nombreArtista;
}
public void setNombreArtista(String nombreArtista){
this.nombreArtista=nombreArtista;
}
}
Method to register the artist:
public void addArtista(ArtistaVO artistaVO){
Conexion conexion=new Conexion();
try{
//Insertamos los datos del Artista
PreparedStatement sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
ResultSet resultado=sqlAddArtist.executeQuery();
while(resultado.next()){
sqlAddArtist.setString(1, artistaVO.getNombreArtista());
sqlAddArtist.setInt(2, getMaxId()+1);
}
JOptionPane.showMessageDialog(null, "Se ha añadido exitosamente","Información",JOptionPane.INFORMATION_MESSAGE);
sqlAddArtist.close();
conexion.desconectar();
}catch(SQLException excepcion){
System.out.println(excepcion.getMessage());
JOptionPane.showMessageDialog(null,"No se registro", "Error", JOptionPane.ERROR_MESSAGE);
}
}
This method is used to create Artist ID:
public int getMaxId(){
int id=0;
Conexion conexion=new Conexion();
try{
Statement sqlMaxId=conexion.getConnection().createStatement();
ResultSet resultado=sqlMaxId.executeQuery("SELECT max(ArtistId) from artist");
if(resultado.next()){
id=resultado.getInt(0);
}
conexion.desconectar();
sqlMaxId.close();
}catch(SQLException excepcion){
System.out.println(excepcion.getMessage());
}
return id;
}
This belongs to the window which register the artist after clicking the button:
public void actionPerformed(ActionEvent evento) {
if(evento.getSource()==botonAñadir){
try{
ArtistaVO artistaVO=new ArtistaVO();
artistaVO.setNombreArtista(campoTextoArtista.getText());
miCoordinador.addArtista(artistaVO);
}catch(Exception excepcion){
JOptionPane.showMessageDialog(null, "Error al añadir Artista", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
The error I get is Error al añadir Artista (Error adding Artist), I don't know where the failure can be.
This is the exception I get:
java.lang.NullPointerException
at controlador.Coordinador.addArtista(Coordinador.java:108)
at vista.VistaArtistasAdd.actionPerformed(VistaArtistasAdd.java:70)
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$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.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$1.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)
This is the method validarRegistroArtista:
public void validarRegistroArtista(ArtistaVO artistaVO){
ArtistaDAO artistaDAO;
if(artistaVO.getIdArtista()>=0){
artistaDAO=new ArtistaDAO();
artistaDAO.addArtista(artistaVO);
}else{
JOptionPane.showMessageDialog(null, "Debe de introducirse algún numero de ID", "Advertencia", JOptionPane.WARNING_MESSAGE);
}
}
You are executing the database query before binding the values
PreparedStatement sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
ResultSet resultado=sqlAddArtist.executeQuery();
while(resultado.next()){
sqlAddArtist.setString(1, artistaVO.getNombreArtista());
sqlAddArtist.setInt(2, getMaxId()+1);
}
This should look like this:
PreparedStatement sqlAddArtist=conexion.getConnection().prepareStatement("INSERT into artist values(?,?)");
sqlAddArtist.setString(1, artistaVO.getNombreArtista());
sqlAddArtist.setInt(2, getMaxId()+1);
sqlAddArtist.execute();
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.PrintWriter;
import java.sql.*;
import java.net.*;
public class connection {
JTextField textfeild;
JButton button;
String text;
Socket sock;
PrintWriter writer;
JButton button1;
public static void main(String[] args) {
connection user1 = new connection();
user1.go();
}//main method close
public void go() {
JFrame frame12 = new JFrame();
JPanel centerpanel12 = new JPanel();
centerpanel12.setLayout(new BoxLayout(centerpanel12, BoxLayout.Y_AXIS));
textfeild = new JTextField(20);
centerpanel12.add(textfeild);
//textfeild.addActionListener(new textfeildlitner());
frame12.add(centerpanel12);
button = new JButton("Click Me");
centerpanel12.add(button);
button.addActionListener(new buttonlitner());
button1 = new JButton("DataDisplay");
centerpanel12.add(button1);
button1.addActionListener(new buttonlitner1());
frame12.getContentPane().add(BorderLayout.CENTER, centerpanel12);
frame12.pack();
frame12.setVisible(true);
frame12.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}//go method close
/*class textfeildlitner implements ActionListener{
public void actionPerformed(ActionEvent ev){
}
}//inner class textfeildlitner close*/
class buttonlitner implements ActionListener {
public void actionPerformed(ActionEvent ev) {
button.setText("I AM Clicked");
String name = textfeild.getText();
System.out.println(name);
textfeild.setText("");
textfeild.requestFocus();
}//method close
}//inner class close
class buttonlitner1 implements ActionListener {
void connection() {
try {
String user = "SQlUI";
String pass = "123456";
String db = "jdbc:sqlserver://localhost:1234;" + ";databaseName=SQlUI";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(db, user, pass);
Statement s1 = con.createStatement();
ResultSet r1 = s1.executeQuery("select * from Table_1");
String[] result = new String[20];
if (r1 != null) {
while (r1.next()) {
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result.length; j++) {
result[j] = r1.getString(i);
System.out.println(result[j]);
break;
}//for j close
}//for i close
}//if closeclose
}//try close
} catch (Exception ex) {
ex.printStackTrace();
}//catch close
}//connection() close
public void actionPerformed(ActionEvent ev) {
button1.setText("Processing");
new buttonlitner1().connection();
}//method close
}//inner class close
}//outer class close
And the exception which i am getting for this code-
com.microsoft.sqlserver.jdbc.SQLServerException: The index 0 is out of range.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.verifyValidColumnIndex(SQLServerResultSet.java:531)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getterGetColumn(SQLServerResultSet.java:2049)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getValue(SQLServerResultSet.java:2082)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getValue(SQLServerResultSet.java:2067)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getString(SQLServerResultSet.java:2392)
at connection$buttonlitner1.connection(connection.java:76)
at connection$buttonlitner1.actionPerformed(connection.java:89)
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$200(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$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.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$1.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)
When i am changing the value of i from 0 to 1 then it displays result for 1st row but again it throws exception saying that the index 3 is out of range.
I have posted the same code and after making the changes (as suggested by the experts on stackoverflow) it gave me a new type of exception.
I am putting the link of the previous question-Getting Checked Exception while running a SQL Program and the question was Getting Checked Exception while running a SQL Program
In SQL (unlike generally in Java) evrything is indexed starting from 1 - both rows and columns.
Why do you have 2 loops inside your r1.next() loop?
Think what your code
for (int j = 0; j < result.length; j++) {
result[j] = r1.getString(i);
System.out.println(result[j]);
break;
}
actually does.
I have tried with the following code to connect CASSANDRA Database on my local system.
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnect {
public static void main(String[] args) throws Exception{
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/mykeyspace");
String query = "select * from users";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("user_id"));
System.out.println(result.getString("fname"));
System.out.println(result.getString("lname"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
}
}}
and here is a error message which i recieve.
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/thrift/TEnum
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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 org.apache.cassandra.cql.jdbc.Utils.<clinit>(Utils.java:62)
at org.apache.cassandra.cql.jdbc.CassandraDriver.connect(CassandraDriver.java:85)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnect.main(DBConnect.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.thrift.TEnum
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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)
... 17 more
I have added following Jar files.
apache-cassandra-thrift-1.2.5.jar
cassandra-jdbc-1.2.5.jar
slf4j-api-1.7.5.jar
slf4j-jdk14-1.7.5.jar
Please help me to solve this issue.
Thanks
The apache-cassandra-thrift depends on libthrift artifact. You need to add this jar in your classpath. You can find it here.