How to connect to the MySQL8.x database using java 10? - java

First of all, sorry for my bad English.
I have scheme and table in base and I would like to make connect to it.
1) Name of scheme - user.
2) Name of user - root
3) Password - banana.
I wrote this code by using MySQL's tutorial
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JavaNioServer {
public static void main (String [] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/user?"
+ "user=root&password=banana");
}catch (Exception ex) {
ex.printStackTrace();
return;
}
}}
But code throws Exceptions
> java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source)
at java.base/java.lang.ClassLoader.loadClass(Unknown Source)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Unknown Source)
at JavaNioServer.JavaNioServer.main(JavaNioServer.java:9)
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/user?user=root&password=88224148
at java.sql/java.sql.DriverManager.getConnection(Unknown Source)
at java.sql/java.sql.DriverManager.getConnection(Unknown Source)
at JavaNioServer.JavaNioServer.main(JavaNioServer.java:24)
I used standard java.sql libs and I can't understand what I do wrong...

ClassNotFoundException throws because you haven't added the relevant MySQL connector. Add the MySQL 8 Connector for Java.
MySQL Connector/J ยป 8.0.11 - jar

Download This Jar add in buildpath/classpath .

Related

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.how to solve?

i have mysql database on aws when i try to access to through java progarm it give exception some time and some times its working
here is my java code
package com.iseva.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Connectionfactory.ConnectionFactory;
/**
* Servlet implementation class ValidateUser
*/
#WebServlet("/ValidateUser")
public class ValidateUser extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection cn=null;
public void init()
{
cn=ConnectionFactory.getConnection();
System.out.println("connection");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String logintype=request.getParameter("t1");
String username= request.getParameter("t2");
String password= request.getParameter("t3");
PreparedStatement ps=null;
ResultSet rs=null;
String result="";
try {
ps=cn.prepareStatement("select * from mydb.isevausers where logintype=? and passwords=? and username=?");
ps.setString(1,logintype);
ps.setString(2,password);
ps.setString(3,username);
rs=ps.executeQuery();
boolean b=rs.next();
// RequestDispatcher dispatcher=null;
if(b==true)
{
/* response.sendRedirect("form_1_IRCTC_PaymentEntry.html");*/
result="form1";
/*dispatcher =getServletContext().getRequestDispatcher("/form_1_IRCTC_PaymentEntry.html");
dispatcher.forward(request,response);*/
System.out.println("entered");
}
else{
result="notfound";
System.out.println("not found");
}
response.getWriter().write(result);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(cn!=null)
{
try {
cn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null)
{
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
when i try to access data base it gives following exception
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
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:4071)
at com.mysql.jdbc.ConnectionImpl.prepareStatement(ConnectionImpl.java:4040)
at com.iseva.Servlet.ValidateUser.doGet(ValidateUser.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:94)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:502)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1104)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:684)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1519)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1475)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
how to solve this issue ?
is it the problem of database or my code, please help me out.
i closed all connection in finally block as suggested by sites, even it gives same .
this exception may occur when our mysql data base idle for some time. is it?
if yes, what should i do. or how to solve it.
this Exception also coming when i refresh server
java.lang.Object.wait(Native Method)
java.lang.ref.ReferenceQueue.remove(Unknown Source)
com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:64)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
Dec 04, 2017 3:34:01 PM org.apache.catalina.loader.WebappClassLoaderBase checkStateForResourceLoading
INFO: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load []. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1353)
at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1029)
at com.mysql.jdbc.AbandonedConnectionCleanupThread.checkContextClassLoaders(AbandonedConnectionCleanupThread.java:90)
at com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:63)
After one doGet() invocation your connection object are being closed so invoking it any next time after first usage will cause error because you won't have an opened connection.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//opening a connection before accessing db
cn=ConnectionFactory.getConnection();
String logintype=request.getParameter("t1");
String username= request.getParameter("t2");
String password= request.getParameter("t3");
PreparedStatement ps=null;
ResultSet rs=null;
String result="";
try {
ps=cn.prepareStatement("select * from mydb.isevausers where logintype=? and passwords=? and username=?");
ps.setString(1,logintype);
ps.setString(2,password);
ps.setString(3,username);
rs=ps.executeQuery();
boolean b=rs.next();
// RequestDispatcher dispatcher=null;
if(b==true)
{
/* response.sendRedirect("form_1_IRCTC_PaymentEntry.html");*/
result="form1";
/*dispatcher =getServletContext().getRequestDispatcher("/form_1_IRCTC_PaymentEntry.html");
dispatcher.forward(request,response);*/
System.out.println("entered");
}
else{
result="notfound";
System.out.println("not found");
}
response.getWriter().write(result);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(cn!=null)
{
try {
cn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null)
{
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(rs!=null)
{
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

No suitable driver found for jdbc.sqlite,more complicated

I am writing a program to connect to a database using java and SQLite. I have tried anything I came across but nothing seems to help.
The code looks like this:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.sqlite.JDBC;
/**
*
* #author sqlitetutorial.net
*/
#SuppressWarnings("unused")
public class SQLiteJDBCDriverConnection {
/**
* Connect to a sample database
*/
public static void connect() {
Connection conn = null;
try {
// db parameters
String url = "jdbc:sqlite:C:\\Users\\marks\\Desktop\\sqlite-tools-win32-x86-3180000\\SQLiteStudio\\chinook.db";
// create a connection to the database
conn = DriverManager.getConnection(url);
System.out.println("Connection to SQLite has been established.");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connect();
}
}
And the error I am getting is:
org.sqlite.JDBC
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 SQLiteJDBCDriverConnection.main(SQLiteJDBCDriverConnection.java:42)
I have followed the exact steps from http://www.sqlitetutorial.net/sqlite-java/sqlite-jdbc-driver/ and it doesn't work for me!
I am using Eclipse Java Neon(latest) on Widows 10 64-bit.
EDITED
As your tutorial show, you just need to call connect() method on main void.
public static void main(String[] args) {
connect();
}
You are trying to retrieve the class Class.forName("org.sqlite.JDBC"); and you are not using it later.

Unable to connect Cassandra using jdbc driver

Hi I am trying to connect with Cassandra using jdbc driver. I am getting the following exception.
java.sql.SQLNonTransientConnectionException: Connection url must specify a host, e.g., jdbc:cassandra://localhost:9170/Keyspace1
at org.apache.cassandra.cql.jdbc.Utils.parseURL(Utils.java:190)
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 com.sub.cas.CqlJdbcTestBasic.main(CqlJdbcTestBasic.java:14)
My cassandra server is running fine and can be accessed from cql shell in windows 10 OS.
This is the java class that I have written.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CqlJdbcTestBasic {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
con = DriverManager.getConnection("jdbc:cassandra:/root/root#localhost:9160/hr");
String query = "SELECT empid, emp_first, emp_last FROM User WHERE empid = 1";
Statement stmt = con.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
System.out.println(result.getString("empid"));
System.out.println(result.getString("emp_first"));
System.out.println(result.getString("emp_last"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
con = null;
}
}
}
}
I have gathered my jars from this url :: https://code.google.com/archive/a/apache-extras.org/p/cassandra-jdbc. Unable to find any possible solution. Please help.
Please, check if you have two slashes before your user name. According to
http://www.dbschema.com/cassandra-jdbc-driver.html

I want to write and read from a file and I have this error when I run : java.io.EOFException

I have this class Dictionar , implements Serializable and the class ScriereCitire
package controler;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ScriereCitire {
public void scriere(Dictionar dictionar){
try (FileOutputStream fileOut = new FileOutputStream("dict.txt")){
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
objOut.writeObject(dictionar);
objOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public Dictionar citire(){
try(FileInputStream fileInput = new FileInputStream("dict.txt")){
ObjectInputStream objInput = new ObjectInputStream(fileInput);
#SuppressWarnings("unused")
Dictionar dictionar = (Dictionar)objInput.readObject();
objInput.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
I created a file named dict.txt in the project. I have a class maine where I call my GraphicInterface which calls ScriereCitire. But when I run it points to this as a error:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at controler.ScriereCitire.citire(ScriereCitire.java:27)
at view.GUI.<init>(GUI.java:46)
at controler.Main.main(Main.java:11)
You have created an empty file somehow. Possibly you got an exception creating it and have ignored it.
I created a file named dict.txt in the project
How? Why?
NB serialized data is not text and should not be placed in a file named .txt.

How to connect ORACLE DB [duplicate]

This question already has answers here:
connect to sql server using jdbc
(2 answers)
Closed 9 years ago.
Here I'm trying to connect oracle which is installed in local machine with DSN bam.
I'm getting java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver Exception. Anybody please help me to fix this issue.
public class JdbcConnectionExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager
.getConnection("jdbc:oracle:thin:#localhost:1521:bam"
,"system","tiger");
Statement stmt = con.createStatement();
System.out.println("Created DB Connection....");
ResultSet rs = stmt.executeQuery("select * from tt");
while(rs.next()){
System.out.println(rs.getString("ename"));
System.out.println(rs.getInt("age"));
}
rs.close();
con.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The Log is here
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
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 java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.bam.sqlex.JdbcConnectionExample.main(JdbcConnectionExample.java:14)
May be u have not added jar of oracle driver download jar from here
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
Undoubtedly, you are lack of Oralce jar, improt it into your project
Class.forName("oracle.jdbc.driver.OracleDriver");
You have to check if this class is added to the classpath.

Categories