This is the actual error I'm getting:
NoInitialContextException: Need to specify class name in environment or system property
I'm trying to have a datasource connection working on a project without servlet but just a main to launch.
This is the main class:
package pacchetto;
import java.sql.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class testIt {
public static void main(String[] args) throws SQLException, NamingException {
Context ctx = new InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
Connection con = ds.getConnection();
try {
con = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null)
System.out.println("Connessione riuscita");
}
}
}
In the same project I also have a servlet file and using it everything works fine. This led me to thinking that the problem must be in this class and not in the servlet.xml or any other configuration file. Should I be wrong and should you need the whole scene I'll be happy to paste them here along with the main.
What am I doing wrong?
Related
I created the connection between java and mysql as follows:
package conexao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionFactory {
public Connection getConnection() {
try {
return DriverManager.getConnection("jdbc:mysql://localhost/projetojava","xxxxxxxxxx","xxxxxxxx");
}
catch(SQLException excecao) {
throw new RuntimeException(excecao);
}
}
}
to test the connection I used this code:
package conexao;
import java.sql.Connection;
import java.sql.SQLException;
public class TestaConexao {
public static void main(String[] args) throws SQLException {
Connection connection = new ConnectionFactory().getConnection();
System.out.println("Conexão aberta!");
connection.close();
}
}
But I always get this error:
In-place deployment at \192.168.1.70\Server\html\Pouco Comum\build\web GlassFish Server 4.1.1, deploy, null, false
\\192.168.1.70\Server\html\Pouco Comum\nbproject\build-impl.xml:1048: The module has not been deployed.
See the server log for details. BUILD FAILED (total time: 0 seconds)
How can I solve?
MySQL port seems to be missing in JDBC connection URL. The default port is 3306.
Try below code:
return DriverManager.getConnection("jdbc:mysql://localhost:3306/projetojava","xxxxxxxxxx","xxxxxxxx");
When i start the server this error comes :
I am using IntelliJ Idea and MySQL jar is added to the src and in the project modules.
Error pastebin
Here is my code
package com.okaam.jaajhome;
import org.bukkit.plugin.java.JavaPlugin;
import pro.husk.mysql.MySQL;
import java.sql.Connection;
import java.sql.SQLException;
public class JaaJHome extends JavaPlugin {
static JaaJHome instance = null;
MySQL MySQL = new MySQL("address", "port", "schema", "user", "password", "");
static Connection c = null;
#Override
public void onEnable() {
System.out.println("Plugin JaaJHome active");
getCommand("sethome").setExecutor(new SetHomeExecutor());
getCommand("home").setExecutor(new HomeExecutor());
try {
c = MySQL.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
instance = this;
}
public static JaaJHome getInstance() {
return instance;
}
}
It seems like you're missing on some dependencies, make sure you have them either in the plugins folder as a non plugin or in the classpath to make sure they're loaded.
I am creating a java console application that connects to a MySQL database. I have outlined below what I've done but the connection is not being established:
Things I have done:
1) I have added the mysql-connector-java-5.1.36.jar to my project bulid path.
2) I have written the code that tries to establish a connection
Can anyone suggest what I'm doing wrong?
The code is given below:
import java.sql.Connection;
import java.sql.DriverManager;
public class main {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:1234/first","root","");
System.out.println("Success fully Connected");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
I have a code that works fine. The important parts are as follows:
My model class:
package biz.tugay.sakila.model;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:48 */
public class Actor {
private long id;
private String firstName;
private String lastName;
// Getters, setters...
}
My dao class:
package biz.tugay.sakila.dao;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:12 */
import biz.tugay.sakila.model.Actor;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ActorDao {
protected static final Connection connection = DBConnector.getConnection();
public List<Actor> getAllActors() throws SQLException {
List<Actor> allActors = new ArrayList<Actor>();
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM Actor";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
// You get the idea... Setters again..
allActors.add(actor);
}
rs.close();
stmt.close();
return allActors;
}
}
and the DBConnector
package biz.tugay.sakila.dao;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:35 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnector {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/sakila";
static final String USER = "root";
static final String PASS = "";
private static Connection connection = null;
public static final Connection getConnection() {
if (connection != null) {
return connection;
} else {
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASS);
return connection;
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}
throw new UnsupportedOperationException();
}
}
}
My Servlet class:
package biz.tugay.sakila.servlet;
/* User: koray#tugay.biz Date: 26/06/15 Time: 14:31 */
import biz.tugay.sakila.dao.ActorDao;
import biz.tugay.sakila.model.Actor;
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 java.io.IOException;
import java.sql.SQLException;
import java.util.List;
#WebServlet(urlPatterns = "/actors")
public class ActorServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ActorDao actorDao = new ActorDao();
List<Actor> allActors = null;
try {
allActors = actorDao.getAllActors();
req.setAttribute("allActors",allActors);
req.getRequestDispatcher("/actors.jsp").forward(req, resp);
} catch (SQLException e) {
}
}
}
And /actors.jsp will show an HTML table to the user.
I have made this exercise myself with the sakila sample database MySQL provides.
My question is, without using any framework such as Spring or Struts, how can I achieve a better separation? For example, currently ActorServlet depends on ActorDao concretely, can I fix this, if so how? Also ActorDao depends heavily on DBConnector. For example, I want to be able to create a NoSQL connector and use it, but currently I can not I guess?
First step is to abstract out some interfaces. For example, make ActorDao an interface, move the implementation to ActorDaoImpl or whatever. Create an ActorDaoFactory that hands you an ActorDao which is, under the covers, an ActorDaoImpl, but the servlet doesn't need to know that.
Second step is more complex... if you want to only use Tomcat, then injection and the like is out, but you can configure Tomcat to create these new interfaces and put them in JNDI. This process is probably too complex to put in an answer here, but the Tomcat documentation on JNDI is really nice. The process basically involves creating a factory, like I advocated above, and then having Tomcat invoke that factory through configuration.
Once you do this, looking them up from JNDI is as simple as
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our DAO
ActorDao ad = (ActorDao)envCtx.lookup("dao/actor");
Good luck!
I have a Java application and i need it to connect with my MySQL database's SQL script using JDBC.
Here is my Java application:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package basic;
import basic.ScriptRunner;
import javax.swing.*;
import java.sql.*;
import java.io.*;
/**
*
* #author User
*/
public class javaconnect {
Connection conn = null;
public static Connection ConnectDb(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/new","login","pass");
/*As we are creating a connection on a local computer we will write the url as jdbc:mysql://localhost:3306 */
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.runScript(new BufferedReader(new FileReader("D://Java Lenti/EkonomiSoftware/src/basic/new.sql")));
return conn ;
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;}
}
}
The problem is that the Java application connects through MySQL Server, not through the SQL Script. I think the problem is at Connection parameters I gave. Can anyone guide me how to change the connection to make it connect to the SQL script not to the server?
It worked for me:
package com.spring.sample.controller;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager
.getConnection(
"",
"", "");
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.runScript(new BufferedReader(new FileReader("new.sql")));
} catch (Exception e) {
e.printStackTrace();
}
}
}
new.sql
insert into hello(name) values ('test');
May be there're some mistakes at your sql file.