I am trying to connect to a mysql database using JDBC, but I am getting the ClassNotFoundException. How do I solve it? Below, is my code :
package PkgJDBC;
import java.sql.*;
class MysqlCon {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://172.16.7.19:3306/sb2016","sb2016","rspl123#");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery("select * from intern1_student");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
You need to add the MySQL Connector/J JAR file to your CLASSPATH.
The Class.forName("com.mysql.jdbc.Driver"); line has been obsolete since 2007.
Related
import java.sql.*;
public class Driver {
public static void main(String[] args) {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?autoReconnect=true&useSSL=false",
"root", "password");
Statement myStamement = myConn.createStatement();
ResultSet myRs = myStamement.executeQuery("SELECT * FROM table1");
while(myRs.next()) {
System.out.println("I GOT SOMETHING FROM DATABASE");
System.out.println(myRs.getString("id"));
}
}
catch (Exception exc) {
exc.printStackTrace();
}
}
}
and I have setup my SQL server and can see the same query in mySQL workbench here:
enter image description here
It doesn't give me an error connecting to the database else it would go to catch.
It returns an empty ResultSet else it would go into while loop once.
There is data in my database that I can see from using same command in photo photo.
using System;
using MySql.Data.MySqlClient;
namespace test2 {
class Program {
static void Main(string[] args) {
string connectionString = "Server=localhost;Database=login;Uid=root;Pwd=TheDarkest;";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
}
}
}
The exception occurs at connection.Open(). I cannot seems to find the solution though I looked everywhere.
Btw I can connect to the database using python.
Add try/catch block until database connection is closed in your code.
Like ,
static void Main(string[] args) {
try{
......
string connectionString ="Server=localhost;Database=login;Uid=root;Pwd=TheDarkest;";
MySqlConnection connection = new MySqlConnection(connectionString);
connection.Open();
.......
}
catch(Exception e)
{
....
}
Driver Not Foundjava.lang.ClassNotFoundException: com.mysql.jdbc.driver
I want to make connection between my java web application and mysql database through XAMP.
I also have added external jar file which is mysql-connector-java-6.0.2.jar but still i am getting this error.
I have done this code.
public static void main(String[] args)
{
try {
Class.forName("com.mysql.jdbc.driver");
System.out.println("Driver has been found..");
} catch (ClassNotFoundException ex) {
System.out.println("Driver Not Found"+ex);
}
String url="jdbc:mysql://localhost/hms";
String user="root";
String password="";
Connection con=null;
try {
con=DriverManager.getConnection(url, user, password);
System.out.println("Driver is successfully loaded.");
} catch (SQLException ex) {
System.out.println("Something is not good.");
}
}
Class names in Java are case-sensitive. You need to capitalize the "D" in "driver":
Class.forName("com.mysql.jdbc.Driver");
// Here ----------------------^
You should write this because because java is Case-Sensitive
public static void main(String[] args)
{
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver has been found..");
} catch (ClassNotFoundException ex) {
System.out.println("Driver Not Found"+ex);
}
String url="jdbc:mysql://localhost/hms";
String user="root";
String password="";
Connection con=null;
try {
con=DriverManager.getConnection(url, user, password);
System.out.println("Driver is successfully loaded.");
} catch (SQLException ex) {
System.out.println("Something is not good.");
}
}
I'm developping a RESTful API with Jersey and MySQL.
I'm actually using the JDBC driver to connect to the database and I create a new connection everytime I want to acess it. As it clearly is a memory leakage, I started to implement the ServletContextClassclass but I don't know how to call the method when I need to get the result of a SQL query.
Here is how I did it wrong:
DbConnection.java
public class DbConnection {
public Connection getConnection() throws Exception {
try {
String connectionURL = "jdbc:mysql://root:port/path";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
return connection;
}
catch (SQLException e) {
throw e;
}
}
}
DbData.java
public ArrayList<Product> getAllProducts(Connection connection) throws Exception {
ArrayList<Product> productList = new ArrayList<Product>();
try {
PreparedStatement ps = connection.prepareStatement("SELECT id, name FROM product");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Product product = new Product();
product.setId(rs.getInt("id"));
product.setName(rs.getString("name"));
productList.add(product);
}
return productList;
} catch (Exception e) {
throw e;
}
}
Resource.java
#GET
#Path("task/{taskId}")
#Consumes(MediaType.APPLICATION_JSON)
public Response getInfos(#PathParam("taskId") int taskId) throws Exception {
try {
DbConnection database= new DbConnection();
Connection connection = database.getConnection();
Task task = new Task();
DbData dbData = new DbData();
task = dbData.getTask(connection, taskId);
return Response.status(200).entity(task).build();
} catch (Exception e) {
throw e;
}
}
Here is where I ended up trying to implement the new class:
ServletContextClass.java
public class ServletContextClass implements ServletContextListener {
public Connection getConnection() throws Exception {
try {
String connectionURL = "jdbc:mysql://root:port/path";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
return connection;
} catch (SQLException e) {
throw e;
}
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
DbConnection database = new DbConnection();
try {
Connection connection = database.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
//con.close ();
}
}
But problem is, I don't know what to do next. Any help? Thanks
You need to set the Connection variable as an attribute of the ServletContext. Also, I would recommend using connection as a static class variable so you can close it in the contextDestroyed method.
You can retrieve the connection attribute in any of your servlets later on for doing your DB operations.
public class ServletContextClass implements ServletContextListener {
public static Connection connection;
public Connection getConnection(){
try {
String connectionURL = "jdbc:mysql://root:port/path";
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "password");
} catch (SQLException e) {
// Do something
}
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ServletContextListener started");
getConnection();
arg0.getServletContext().setAttribute("connection", connection);
}
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ServletContextListener destroyed");
try{
if(connection != null){
connection.close();
}
}catch(SQLException se){
// Do something
}
}
}
Finally access your connection attribute inside your Servlet (Resource). Make sure you pass #Context ServletContext to your Response method so you can access your context attributes.
#GET
#Path("task/{taskId}")
#Consumes(MediaType.APPLICATION_JSON)
public Response getInfos(#PathParam("taskId") int taskId, #Context ServletContext context) throws Exception {
try {
Connection connection = (Connection) context.getAttribute("connection");
Task task = new Task();
DbData dbData = new DbData();
task = dbData.getTask(connection, taskId);
return Response.status(200).entity(task).build();
} catch (Exception e) {
throw e;
}
}
Now that we have solved your current issue, we need to know what can go wrong with this approach.
Firstly, you are only creating one connection object which will be used everywhere. Imagine multiple users simultaneously accessing your API, the single connection will be shared among all of them which will slow down your response time.
Secondly, your connection to DB will die after sitting idle for a while (unless you configure MySql server not to kill idle connections which is not a good idea), and when you try to access it, you will get SQLExceptions thrown all over. This can be solved inside your servlet, you can check if your connection is dead, create it again, and then update the context attribute.
The best way to go about your Mysql Connection Pool will be to use a JNDI resource. You can create a pool of connections which will be managed by your servlet container. You can configure the pool to recreate connections if they go dead after sitting idle. If you are using Tomcat as your Servlet Container, you can check this short tutorial to get started with understanding the JNDI connection pool.
import java.sql.*;
class FirstProgram
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","password");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from data");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
connection is no Class make it Connection
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","password");
Always remember the naming convention of JAVA .The Class names should always start with Capital letter not small letter.So according to this convention the jdk developers are not going to name the class as connection
Increase the scope of Connection variable because again you will face the problem when you will use connection variable in finally block(future).
That is before try block write this.
Connection conn=null;
But in your code you have written connection which has c as small letter. That may be your problem.So make it to
Connection instead of connection
because name of class is always starts with Capital letters coding standards and naming conventions of Java.
So your code become with addition of finally block.
import java.sql.*;
class FirstProgram
{
public static void main(String[] args)
{
Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atul","root","password");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from data");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
catch(Exception e)
{
System.out.println(e);
}
finally{
con.close();
}
}
}