I am trying to connect with My company's database which is 'MariaDB', using Java, I am using following code:
package co.companyname.helpers;
import java.sql.*;
public class DatabaseConnectivity {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
String query = "select * from time_clock limit 10";
try {
Class.forName("org.mariadb.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(
"jdbc:mariadb://host_url:3306", "root", "password");
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = query;
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
At above I have used host_url, but I am using actual host within string, now I am getting following error:
java.lang.ClassNotFoundException: org.mariadb.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:315)
at co.company_name.helpers.DatabaseConnectivity.main(DatabaseConnectivity.java:10)
Goodbye!
I need to know, if I am doing anything wrong.
Thanks.
Related
i am new in database want to run first database program with Access but getting SQLException message "DB linking failed!"
i wrote following code with Java 8,and i have configured ucanaccess's libraries.
Java build path
<i>
import java.sql.*;
public class Db {
public static void main(String[] args)throws SQLException
{
Connection con =null;
try{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String dataSource = "jdbc:ucanaccess://D:/Database.accdb";
con=DriverManager.getConnection(dataSource,"","");
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO Table1 (ID, Name) VALUES ('4','ann')");
st.execute("SELECT * FROM Table1");
ResultSet rs = st.getResultSet();
while(rs.next())
{
System.out.println(rs.getString("ID")+rs.getString("Name"));
}
st.close();
con.close();
}
catch(SQLException e)
{
System.out.println("DB linking failed!");
} catch (ClassNotFoundException e) {
System.out.println("Driver loading failed!");
}
}
}
i have added "e.printStackTrace()" in the catch block as following
catch(SQLException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Driver loading failed!");
}
and got following error messages
error messages
I am writing application which work with database. I have such class for Connection to mysql database:
public class DataBaseConnector {
private static final String URL = "jdbc:mysql://localhost:3306/dataBase";
private static final String USER = "user";
private static final String PASSWORD = "password";
private Connection connection;
private static DataBaseConnector instance;
public synchronized static DataBaseConnector getInstance() {
if (instance == null) {
instance = new DataBaseConnector();
}
return instance;
}
private DataBaseConnector() {
}
public Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
System.out.println("Database connected!");
this.connection = connection;
return connection;
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
}
And test method which perform SQL query:
public static void main(String[] args) {
try {
Connection connection = DataBaseConnector.getInstance().openConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT * FROM hotel_administrators WHERE login=?");
stmt.setString(1, "lll");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
And I don't understand why appears such exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
Database connected!
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:918)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1187)
at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1182)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4035)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4004)
at model.DataBaseManager.main(DataBaseManager.java:81)
What's wrong?
When you create the connection you use a try-with-resources statement which automatically closes the new connection.
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
return connection;
}
/* this is automatically executed:
finally {
connection.close();
}
*/
Now when you execute the query MySQL simply complains that the connection was already closed. To avoid the error you could write:
try {
this.connection = DriverManager.getConnection(URL, USER, PASSWORD));
System.out.println("Database connected!");
return this.connection;
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
Following is my Java code. In linux, it is working fine but in Windows I'm unable to insert data into the database on local disk. In NetBeans get it all right but .jar file not. JDBC driver see be good.
Connecting to database:
public static Connection connectToDb() {
try {
Connection connection = null;
DriverManager.registerDriver(new org.sqlite.JDBC());
//LINUX PATH
if (OSDetector.isLinux()) {
connection = DriverManager.getConnection("jdbc:sqlite:/home/" + userNameLinux + "/PDFMalwareDataAnalyser/DatabaseSQLite/database.db", NAME, PASSWORD);
//WINDOWS PATH
} else {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\PDFMalwareDataAnalyser\\DatabaseSQLite\\database.db", NAME, PASSWORD);
}
connection.setAutoCommit(true);
if (connection != null) {
System.out.println("Otvorená.");
}
return connection;
} catch (SQLException e) {
System.err.println(e.getClass().getName() + e.getMessage());
// System.exit(0);
}
return null;
}
Insertion:
public void insertDataToDatabase(int idReport) throws SQLException {
connection = new SQLiteJDBC().connectToDb();
PreparedStatement insertCommunication = connection.prepareStatement("insert into table_communication values(?,?);");
insertCommunication.setString(2, communicationsFinal.toString());
try {
insertCommunication.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
insertCommunication.close();
connection.close();
System.out.println("1. --- Insert do tabuľky TABLE_COMMUNICATION OK ---");
}
Try this:
connection = DriverManager.getConnection("jdbc:sqlite:C:/PDFMalwareDataAnalyser/DatabaseSQLite/database.db")
Useful piece of code for Hive JDBC:
Connection con = null;
Statement stmt = null
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
con = DriverManager.getConnection(connectionUri, userName, password);
stmt = con.createStatement();
stmt.executeUpdate(query);
} catch (ClassNotFoundException cex) {
cex.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I want to remove try - catch in finally block.
So I tried The try-with-resources Statement.
try (Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection(connectionUri, userName, password);
Statement stmt = con.createStatement();){
stmt.executeUpdate(query);
} catch (ClassNotFoundException cex) {
cex.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
I think this is not the right way.
Class.forName("org.apache.hive.jdbc.HiveDriver") should not be in try. Should I make a separate try-catch for this?
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
} catch (ClassNotFoundException cex) {
cex.printStackTrace();
}
try (Connection con = DriverManager.getConnection(connectionUri, userName, password);
Statement stmt = con.createStatement();){
stmt.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
Is this right way or am I missing any thing?
The idea behind try-with-ressource is to close an AutoCloseable class.
So every usage of a class which should be closed after using it (a Ressource) can be used with try-with-ressource (like Connection for example). You don't have to take care of closing it manually (in an finally block for example).
So yes, your idea is right:
try/catch for Class.forName("org.apache.hive.jdbc.HiveDriver"); - because this is not AutoCloseable
try-with-ressource for Connection con = DriverManager.getConnection(connectionUri, userName, password);
Statement stmt = con.createStatement();- because Connection and Statement implement AutoCloseable
Reference:
https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html
When you're using Java 6 or better and the Apache Hive JDBC driver is JDBC 4 compliant or better* then you do not need the Class.forName("org.apache.hive.jdbc.HiveDriver") stuff at all.
Therefore you can just remove the entire try/catch block from your second solution and you're good to go with just:
try (Connection con = DriverManager.getConnection(connectionUri, userName, password);
Statement stmt = con.createStatement()) {
stmt.executeUpdate(query);
} catch (SQLException e) {
e.printStackTrace();
}
* Which is the case for version 1.2.0 or newer of the Hive JDBC driver
I have been trying this for a few hours now but with no success. I downloaded the JDBC driver and it shows that it is one of my referenced libraries under my Package Explorer in Eclipse but every time I try to run my code I get errors. My database is fine as I can change it and view it from the MySQL Command Line Client.
I actually followed a guides directions on how to do it, only replacing the information from their database to information about mine.
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle Errors For JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle Errors for Class.forName
e.printStackTrace();
} finally {
//Finally Block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
//Nothing We Can Do
}
try {
if (conn != null)
conn.close();
} catch (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
Here is the error I get http://pastebin.com/hLSxV3aq