Can't connect MySQL / Eclipse / iText last error: java.sql.SQLNonTransientConnectionException - java

I'm trying to connect to my database using Eclipse just to try to generate some values into a PDF. I'm using the external library iText which is imported on the "Referenced Libraries" folder on the project. The code:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.*;
public class GeneratePDF {
public static void main(String[] args) {
try {
String file_name = "E:\\Programas\\mypdf.pdf";
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(file_name));
document.open();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "a1s2d3f4g5");
System.out.println("Connection called");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from codes");
while (rs.next()) {
Paragraph para = new Paragraph(rs.getString("sl_no") + " " + rs.getString("name"));
document.add(para);
document.add(new Paragraph(" "));
}
con.close();
document.close();
} catch (DocumentException | FileNotFoundException | SQLException | ClassNotFoundException e) {
System.out.println("Wrong: " + e);
}
}
}
For me it was a pretty simple code for a first timer connecting to MySQL. Then the errors appeared.
First:
"java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"
I imported the "mysql-connector-java-8.0.11.jar" into the project and it replied Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver'.
So I switched the code to:
Class.forName("com.mysql.cj.jdbc.Driver"); // "Solved"
Second:
WARN: Establishing SSL connection without server's identity verification is not recommended.
Then I added "?autoReconnect=true&useSSL=false", the code went to:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?autoReconnect=true&useSSL=false", "root", "a1s2d3f4g5"); // "Solved"
Third:
java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
I thought it would be really simple to connect to MySQL but now I have no idea why it isn't connecting. I don't know if this might be a problem but I have two hard disks, Workbench and Connector are on C: and Eclipse as well as the projects are on E:. I tried importing the .jar connector to a folder on the project but no significant changes.

Related

H2 data added wont refresh until disconnect

This is my code:
package logic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:./Database/Data", "Gustavo", "123456");
stmt = conn.createStatement();
stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY,NAME VARCHAR(255));");
stmt.execute("INSERT INTO TEST VALUES(1, 'John');");
ResultSet rs = stmt.executeQuery("select * from test");
while (rs.next()) {
System.out.println("id " + rs.getInt("id") + " name " + rs.getString("name"));
}
conn.close();
}
}
I can add the data and display it and if I run the code again (commenting the CREATE TABLE and INSERT INTO) it displays the data.
The problem is that when I go to the H2 console, it doesn't show anything unless I disconnect and reconnect. After I do that, it shows any changes made or data added to the database.
Is there a problem or that's how the H2 console works?
(I'm on Ubuntu 20.04, using vs code and gradle)
Edit: I solved it
The problem was in the code I was using it in embebed mode and it only allows one connection at a time. Once I changed it to server mode using:
String url = System.getProperty("user.dir") + "/Database/Data";
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/" + url, "Gustavo", "123456");
I solved it
The problem was in the code I was using it in embebed mode and it only allows one connection at a time. I changed it to server mode using:
String url = System.getProperty("user.dir") + "/Database/Data";
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/" + url, "Gustavo", "123456");

Connecting to SQL Server 2014 from Android Studio

I have a problem connecting to SQL-server database through from my android project. I have added sqljdbc41.jar file to my /app/libs directory and I have added it to dependencies in my android studio project.
I use following code:
package com.konrad.rezerwacje1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Database_Console {
public static void openConnection(){
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"‌​);
String url = "jbdc:sqlserver://127.0.0.1:1433;databaseName=my_db";
Connection con = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
openConnection();
}
}
yet i still get this error
java.sql.SQLException: No suitable driver found for jbdc:sqlserver://127.0.0.1:1433;databaseName=my_db
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
Instead of this :
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"‌​);
String url = "jbdc:sqlserver://127.0.0.1:1433;databaseName=my_db";
You have to use this :
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=my_db";
Connection con = DriverManager.getConnection(url, "username", "password");
Note the different classname, and the fact that prefix jbdc in the URL has been changed to jdbc.
If it is not a requirement to go with sqljdbc41.jar, then you might consider using the jtds driver for your requirement to connect to SQL Server 2014 with Android Studio. There are tons of articles that can help you start with this set of technologies.
For a primer, here are the details:
Download the JTDS driver from here
Then import this jar into your Android Studio, eg: jtds-1.2.5.jar
Use the following details in your code:
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/DATABASE;user=sa;password=p#ssw0rd");

Connection to sqlite database [duplicate]

I am using one simple code to access the SQLite database from Java application .
My code is
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectSQLite
{
public static void main(String[] args)
{
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try
{
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
statement = connection.createStatement();
resultSet = statement
.executeQuery("SELECT EMPNAME FROM EMPLOYEEDETAILS");
while (resultSet.next())
{
System.out.println("EMPLOYEE NAME:"
+ resultSet.getString("EMPNAME"));
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
resultSet.close();
statement.close();
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
But this code gives one exception like
java.lang.ClassNotFoundException: org.sqlite.JDBC
How can I slove this,please help me.
You need to have a SQLite JDBC driver in your classpath.
Taro L. Saito (xerial) forked the Zentus project and now maintains it under the name sqlite-jdbc. It bundles the native drivers for major platforms so you don't need to configure them separately.
If you are using netbeans Download the sqlitejdbc driver
Right click the Libraries folder from the Project window and select Add Library ,
then click on the Create button enter the Library name (SQLite) and hit OK
You have to add the sqlitejdbc driver to the class path , click on the
Add Jar/Folder.. button and select the sqlitejdbc file you've downloaded previously
Hit OK and you are ready to go !
If you are using Netbeans using Maven to add library is easier. I have tried using above solutions but it didn't work.
<dependencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
</dependencies>
I have added Maven dependency and java.lang.ClassNotFoundException: org.sqlite.JDBC error gone.
I'm using Eclipse and I copied your code and got the same error. I then opened up the project properties->Java Build Path -> Libraries->Add External JARs...
c:\jrun4\lib\sqlitejdbc-v056.jar
Worked like a charm. You may need to restart your web server if you've just copied the .jar file.
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import org.sqlite.SQLiteDataSource;
import org.sqlite.SQLiteJDBCLoader;
public class Test {
public static final boolean Connected() {
boolean initialize = SQLiteJDBCLoader.initialize();
SQLiteDataSource dataSource = new SQLiteDataSource();
dataSource.setUrl("jdbc:sqlite:/home/users.sqlite");
int i=0;
try {
ResultSet executeQuery = dataSource.getConnection()
.createStatement().executeQuery("select * from \"Table\"");
while (executeQuery.next()) {
i++;
System.out.println("out: "+executeQuery.getMetaData().getColumnLabel(i));
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
return initialize;
}
You have to download and add the SQLite JDBC driver to your classpath.
You can download from here https://bitbucket.org/xerial/sqlite-jdbc/downloads
If you use Gradle, you will only have to add the SQLite dependency:
dependencies {
compile 'org.xerial:sqlite-jdbc:3.8.11.2'
}
Next thing you have to do is to initialize the driver:
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException eString) {
System.err.println("Could not init JDBC driver - driver not found");
}
connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
Instead of this put
connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb");
Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :
http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class Connectdatabase {
Connection con = null;
public static Connection ConnecrDb(){
try{
//String dir = System.getProperty("user.dir");
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
return con;
}
catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,"Problem with connection of database");
return null;
}
}
}

Issue in running code using JasperReports API on different machines

I created a Java project which will use JasperReports API. I have tested this inside and outside NetBeans (same machine) and it works fine. But when I try to run it on another machine the report wont load.
My code is:
package reportmonitory;
import java.sql.*;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.swing.JRViewer;
import javax.swing.*;
public class monthlyreport extends JFrame {
Connection con;
Statement stmt;
ResultSet rs;
void showReport() {
try {
String host = "jdbc:mysql://192.168.10.11/rmcdb";
String uName = "root";
String uPass = "";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String reportName = "reports/finalreport.jasper";
java.io.InputStream is = this.getClass().getClassLoader().getResourceAsStream(reportName);
JasperPrint print = JasperFillManager.fillReport(is, null, con);
JRViewer viewer = new JRViewer(print);
viewer.setOpaque(true);
viewer.setVisible(true);
this.add(viewer);
this.setSize(1000, 1000);
this.setVisible(true);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
} catch (Exception ex) {
System.out.println("CAUSE: " + ex.getCause());
System.out.println("MESSAGE" + ex.getMessage());
System.out.println("LOCAL MESSAGE" + ex.getLocalizedMessage());
ex.printStackTrace();
}
}
public static void main(String args[]) {
new monthlyreport().showReport();
}
}
Here are some suggestions / things to look into:
Port forwarding for databases behind firewalls
Specify port in case the database's connection port has been changed
Make sure 'reports/finalreport.jasper' exists
Packaging (due to project moving around)
Ensure all .jar's / JasperReport API files are there
All other files this project calls are there
Network problem / not finding hostname: 192.168.10.11
EDIT:
The error comes from being unable to find 'npa logo.jpg'. Make sure it exists on the correct path. I notice you are looking for it on 'C:\Users\mwaluda' and you are running JaspterReports on C:\Users\Aboud. If this is a different machine, would that path still be valid?

How to connect SQLite with Java?

I am using one simple code to access the SQLite database from Java application .
My code is
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectSQLite
{
public static void main(String[] args)
{
Connection connection = null;
ResultSet resultSet = null;
Statement statement = null;
try
{
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
statement = connection.createStatement();
resultSet = statement
.executeQuery("SELECT EMPNAME FROM EMPLOYEEDETAILS");
while (resultSet.next())
{
System.out.println("EMPLOYEE NAME:"
+ resultSet.getString("EMPNAME"));
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
resultSet.close();
statement.close();
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
But this code gives one exception like
java.lang.ClassNotFoundException: org.sqlite.JDBC
How can I slove this,please help me.
You need to have a SQLite JDBC driver in your classpath.
Taro L. Saito (xerial) forked the Zentus project and now maintains it under the name sqlite-jdbc. It bundles the native drivers for major platforms so you don't need to configure them separately.
If you are using netbeans Download the sqlitejdbc driver
Right click the Libraries folder from the Project window and select Add Library ,
then click on the Create button enter the Library name (SQLite) and hit OK
You have to add the sqlitejdbc driver to the class path , click on the
Add Jar/Folder.. button and select the sqlitejdbc file you've downloaded previously
Hit OK and you are ready to go !
If you are using Netbeans using Maven to add library is easier. I have tried using above solutions but it didn't work.
<dependencies>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
</dependencies>
I have added Maven dependency and java.lang.ClassNotFoundException: org.sqlite.JDBC error gone.
I'm using Eclipse and I copied your code and got the same error. I then opened up the project properties->Java Build Path -> Libraries->Add External JARs...
c:\jrun4\lib\sqlitejdbc-v056.jar
Worked like a charm. You may need to restart your web server if you've just copied the .jar file.
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import org.sqlite.SQLiteDataSource;
import org.sqlite.SQLiteJDBCLoader;
public class Test {
public static final boolean Connected() {
boolean initialize = SQLiteJDBCLoader.initialize();
SQLiteDataSource dataSource = new SQLiteDataSource();
dataSource.setUrl("jdbc:sqlite:/home/users.sqlite");
int i=0;
try {
ResultSet executeQuery = dataSource.getConnection()
.createStatement().executeQuery("select * from \"Table\"");
while (executeQuery.next()) {
i++;
System.out.println("out: "+executeQuery.getMetaData().getColumnLabel(i));
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
return initialize;
}
You have to download and add the SQLite JDBC driver to your classpath.
You can download from here https://bitbucket.org/xerial/sqlite-jdbc/downloads
If you use Gradle, you will only have to add the SQLite dependency:
dependencies {
compile 'org.xerial:sqlite-jdbc:3.8.11.2'
}
Next thing you have to do is to initialize the driver:
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException eString) {
System.err.println("Could not init JDBC driver - driver not found");
}
connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
Instead of this put
connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb");
Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :
http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
public class Connectdatabase {
Connection con = null;
public static Connection ConnecrDb(){
try{
//String dir = System.getProperty("user.dir");
Class.forName("org.sqlite.JDBC");
Connection con = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");
return con;
}
catch(ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,"Problem with connection of database");
return null;
}
}
}

Categories

Resources