Java, Maven, connect SQL , no suitable driver - java

I am building a project using Netbeans IED, with java. The project is using maven and I am attempting to connect it to sql database which I am having issue's. The code works in java but not with maven.
Here the error:
No suitable driver found for jdbc:derby://localhost:1527/Database
Java Code:
public class DatabaseTest {
public static Connection ConnectionObj = null;
public static Statement SqlStatement = null;
public static ResultSet Sqlresult = null;
public static ResultSetMetaData MetaData = null;
public static String query = "Select * from Wallet";
public static String url = "jdbc:derby://localhost:1527/Database";
public static String user = "ABM";
public static String pass = "password2";
public static void main(String[] args) {
try {
//Allows you to connect the database
ConnectionObj = DriverManager.getConnection(url, user, pass);
SqlStatement = ConnectionObj.createStatement();
Sqlresult = SqlStatement.executeQuery(query);
MetaData = Sqlresult.getMetaData();
System.out.println("Connection worked");
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Prom depency's:
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.14.1.0</version>
</dependency>
https://gyazo.com/8937aada3bd4a8f5b108b5dc9b386dd7

This part of your POM file is incorrect:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
Your program is attempting to use JDBC to connect to a Derby database, so you should be using a Derby JDBC driver, not a MySQL JDBC driver.
Replace the above with the following:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.14.1.0</version>
</dependency>
(Use the same version as your main Derby version ...)
The code works in Java but not with Maven.
Curious. Perhaps you are setting the runtime classpath correctly in the Java case.

Related

How to connect to Neo4j 3.0 database with neo4j-jdbc?

Hi,
I've created a maven project in eclipse and added the dependency:
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc</artifactId>
<version>3.0</version>
</dependency>
I'm just trying to get a connection to my db working so that I can move on to integrate the connection with my main project but I'm having trouble getting things off the ground.
I've used the code example given on the official repo:
import org.neo4j.jdbc.Connection;
import org.neo4j.jdbc.PreparedStatement;
import org.neo4j.jdbc.ResultSet;
public class Neo4jConnectionTest {
public static void main(String[] args) {
// Connect
Connection con = DriverManager.getConnection(
"jdbc:neo4j:bolt://localhost");
// Querying
String query = "MATCH (u:User)-[:FRIEND]-(f:User)
WHERE u.name = {1}
RETURN f.name, f.age";
try {
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1,"John");
ResultSet rs = con.execute();
while (rs.next()) {
System.out.println(
"Friend: "+rs.getString("f.name")+" is "+rs.getInt("f.age"));
}
} catch (Exception e) { e.printStackTrace(); }
con.close();
}
}
I am unable to compile this as:
DriverManager cannot be resolved within the neo4j-jdbc-3.0,
Prepared stmt = con.prepareStatement(query); causes a type mismatch,
and con.execute() is undefined for type org.neo4j.jdbc.Connection
I'd greatly appreciate any advice and expertise on the matter, thanks.
By changing to:
<dependency>
<groupId>org.neo4j.driver</groupId>
<artifactId>neo4j-java-driver</artifactId>
<version>1.0.4</version>
</dependency>
I was able to successfully connect to the Neo4j 3.0 server using an example from Neo4j's site:
public static void main(String[] args) {
Driver driver = GraphDatabase.driver(
"bolt://localhost", AuthTokens.basic( "neo4j", "neo4j" ) );
Session session = driver.session();
session.run( "CREATE (a:Person {name:'Arthur', title:'King'})" );
StatementResult result = session.run(
"MATCH (a:Person)
WHERE a.name = 'Arthur'
RETURN a.name AS name, a.title AS title");
while ( result.hasNext() ) {
Record record = result.next();
System.out.println( record.get( "title" ).asString() +
" " + record.get("name").asString() );
}
session.close();
driver.close();
}
I thought I'd share as this worked instantly with no hassle.
Neo4j Language Guides
DriverManager, Connection, PreparedStatement and ResultSet are all classes or interfaces from the java.sql package, which is part of the JDK. I guess the documentation assumes you'll use an IDE which will find the correct import for you.
It's the point of using the JDBC driver: you use the JDBC API, not a proprietary one (i.e. in a vendor package).
Update
There was a typo in the neo4j-jdbc readme, it should have read
ResultSet rs = stmt.execute();
instead of
ResultSet rs = con.execute();
otherwise the PreparedStatement has not use (and the code doesn't compile because there's no no-arg overload of Connection.execute()).
Update 2
The documented dependency was also wrong, as neo4j-jdbc does not contain any driver.
You should depend on:
either the all-in-one module, which gives you the opportunity to use the Bolt or HTTP protocols:
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-driver</artifactId>
<version>3.0</version>
</dependency>
or the module for a specific protocol:
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-bolt</artifactId>
<version>3.0</version>
</dependency>
<!-- or -->
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-jdbc-http</artifactId>
<version>3.0</version>
</dependency>
Update 3
Both problems have now been fixed in the documentation of the project.

Servlet with JDBC [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 5 years ago.
I have a problem with my progect. Files of progect:
House.class
public class House implements Serializable {
//properties -------------------------------------------------------------
private String price;
private String square;
private String RoomNumbers;
//------------------------------------------------------------------------
//getters - settersm Object overriding.... -----------------------------
HouseDAO.class
public class HouseDAO {
Connection connection;
final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb2";
final String DB_USER = "root";
final String DB_PASSWORD = "root";
public HouseDAO(Connection connection) {
this.connection = connection;
}
public List<House> getList() {
List<House> houses = new ArrayList<>();
try {
connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection available");
PreparedStatement ps = connection.prepareStatement("SELECT Square, RoomNumbers, Price FROM houses WHERE District = 'Dnepr'");
ResultSet rs = ps.executeQuery();
while (rs.next()){
House house = new House();
house.setSquare(rs.getString("Square"));
house.setRoomNumbers(rs.getString("RoomNumbers"));
house.setPrice(rs.getString("Price"));
houses.add(house);
}
}catch (Exception ex){
System.out.println("SQL exceprion");
ex.printStackTrace();
}
return houses;
}
}
and Servlet:
HousesBaseServlet
#WebServlet("/post")
public class HosesBaseServlet extends HttpServlet {
Connection conn;
private HouseDAO houseDAO;
#Override
public void init(){
houseDAO = new HouseDAO(conn);
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
//choice from html form
// String choice = request.getParameter("district");
try {
List<House> houses = houseDAO.getList();
request.setAttribute("houses", houses);
request.getRequestDispatcher("/houses.jsp").forward(request,response);
}catch (Exception ex ) {
System.out.println("Fail to connect with base");
ex.printStackTrace();
}
}
}
I was read some solutiotuns, but it doesn't help. The problem in two exceptions:
SQL exceprion java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/mydb2
I try to add:
Class.forName("com.mysql.jdbc.Driver");
to my code, and add mysql connector jar to my project, but it throws exception:
SQL exception java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Second exception:
JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core
cannot be resolved in either web.xml or the jar files deployed with
this application Fail to connect with base
Here is my pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
,
JSP taglib:
%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %
and project structure:
[project structure][1]
Project structure - artifacts
In project structure -> libraries i have all jars.
Since you are using IntelliJ I believe you might need to add the libraries to the artifact because from my experience Intellij adds the maven dependencies to the Classpath but not to the artifact.
Make sure you go to File -> Project Structure -> Artifacts and then add all the libraries from the available side to the artifact.
But you need to register the driver before getting the connection otherwise it doesn't work either way :
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
Hope this helps.

Exception with com.mysql.jdbc.Driver

i'm trying run code
public static Connection getConnection() throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull [root on Default schema]");
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null,e.toString());
}
return cn;
}
but i get the exception:
with the dialog:
I have added the divier :mysql-connector-java-5.1.36-bin.jar in this project.
What am I doing wrong?
Add mysql connector jar to your project classpath.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

Getting error retrieving data from column family using cassandra-jdbc dreiver

when i am retrieving data from column family using Cssandra-JDBC driver. i got error
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.cassandra.thrift.Cassandra$Client.execute_cql3_query(Ljava/nio/ByteBuffer;Lorg/apache/cassandra/thrift/Compression;Lorg/apache/cassandra/thrift/ConsistencyLevel;)Lorg/apache/cassandra/thrift/CqlResult;
at org.apache.cassandra.cql.jdbc.CassandraConnection.execute(CassandraConnection.java:447)
at org.apache.cassandra.cql.jdbc.CassandraConnection.execute(CassandraConnection.java:472)
at org.apache.cassandra.cql.jdbc.CassandraStatement.doExecute(CassandraStatement.java:161)
at org.apache.cassandra.cql.jdbc.CassandraStatement.executeQuery(CassandraStatement.java:226)
at CassandraJDBCTest.main(CassandraJDBCTest.java:19)
Code is
public static void main (String args[]) throws SQLException{
try {
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://localhost:9160/TestExample");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Name,Age FROM Users WHERE keyname='001';");
rs.next();
System.out.println(rs.getString("Name"));
System.out.println(rs.getInt(2));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You have missing dependencies:
Exception in thread "main" java.lang.NoSuchMethodError
I have a feeling that the classpath is just not configured correctly (why the L's?):
Ljava/nio/ByteBuffer;
Lorg/apache/cassandra/thrift/Compression;
Lorg/apache/cassandra/thrift/ConsistencyLevel;
...
If you want to save yourself of dependency hell try using maven, the Datastax java driver has a maven central repo and you just need to include the dependency:
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>1.0.2</version>
</dependency>
EDIT
Sorry, didnt realise you are using JDBC. The cassandra jdbc driver has also got a maven repository:
<dependency>
<groupId>org.apache-extras.cassandra-jdbc</groupId>
<artifactId>cassandra-jdbc</artifactId>
<version>1.2.5</version>
</dependency>

Using MS-SQL With Maven2, Netbeans on a (Mac or Linux)

Looking for advice or a bit of help, to point me in the right direction.
I need to connect to a Microsoft SQL Server from a Java program, however, the drivers must be available in maven2 and work with NetBeans.
Any advice? (pointer to an example would be great) (Suicide is no longer an option)
Edit: I've found JTDS- is this a good solution?
Edit 2: Looks like it works... Here is how I have it configured...
Pom file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.steward.ccd</groupId>
<artifactId>amalgainterface</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>amalgainterface</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.ini4j</groupId>
<artifactId>ini4j</artifactId>
<version>0.5.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
</project>
Java File
import java.sql.*;
import org.ini4j.*;
import java.util.*;
import java.io.File;
public class AmalgaInterface {
public static void main(String[] args) {
// MS-SQL Parameters
String db_name = "xxxx";
String db_hostname = "xxxx";
String db_port = "1433";
String db_userid = "xxxx";
String db_password = "xxxx";
String db_timeout = "10";
// Check the Configuration file, and replace all service reference as required.
// Get configuration
String configFile = "/etc/test.conf";
// Load data from INI files
Ini ini = null;
try {
ini = new Ini(new File(configFile));
db_name = ini.get("database", "name");
db_hostname = ini.get("database", "host");
db_userid = ini.get("database", "user");
db_password = ini.get("database", "pass");
db_port = ini.get("database", "port");
db_timeout = ini.get("database", "dbtimeout");
} catch (Exception ex) {
System.out.println("Cannot load the configuration file");
}
// Create the connection string
String db_connect_string = "jdbc:jtds:sqlserver://" + db_hostname + ":" + db_port + "/" + db_name + ";socketTimeout=" + db_timeout;
// setup connection
Connection connection = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connection = DriverManager.getConnection(db_connect_string, db_userid, db_password);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
// clean up
if (connection != null) {
try {
connection.close();
} catch (Exception ex) {
}
}
}
}
Try JTDS
It's a type 4 jdbc driver and I believe it's available via maven repository.

Categories