java.lang.ClassNotFoundException: com.mysql.jdbc.Driver Vertrigo server eclipse [duplicate] - java

This question already has answers here:
java.lang.ClassNotFoundException in spite of using CLASSPATH environment variable
(9 answers)
Closed 9 years ago.
I am trying to connect to mysql database (as part of the Vertrigo server) on my windows 7 pc, but it keeps throw me the "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver".
Following is my code :
import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;
public class ShippingCompany {
private Connection conn;
private Statement stmt;
private List<Journey> journeyList;
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://172.16.127.38:3306/testRestricted";
public ShippingCompany(String dbUser, String dbPassword) throws Exception {
journeyList = new ArrayList<Journey>();
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(DB_URL, dbUser, dbPassword);
stmt = conn.createStatement();
} catch (SQLException e) {
System.out.println("SQL Exception:" + e);
}
}
public List<String> readAllPorts() throws SQLException{
List<String> allPorts = new ArrayList<String>();
String command = "SELECT * FROM Ports";
ResultSet rs = stmt.executeQuery(command);
while (rs.next()) { // database name string is in first column of result set
allPorts.add(rs.getString(2));
//In command concole, print out all ports
System.out.println(rs.getString(2));
}
return allPorts;
}
public List<Journey> getAllJourneys(String startPort, String startDate, String endPort){
return new LinkedList<Journey>();
}
private void findPaths(Journey journey, String endPort){
}
public void Close(){
}
public static void main(String[] args) throws Exception{
//TODO : entry point of the program
ShippingCompany sc = new ShippingCompany("root", "vertrigo");
sc.readAllPorts();
}
}
should be

You need to have mysql connector jar in your classpath while running the program. If you are running it through the command line then you can do something like this:
java -cp <.;path to sql jar> ShippingCompany

Related

Cannot Script to file in h2 database in java application

When I tried to backup my database by org.h2.tools.Script.process(), I keep getting a wired problem, in which it did not mention the details :
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SCRIPT TO '' TEST[*].SQL "; SQL statement:
SCRIPT TO '' test.sql [42000-194]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.message.DbException.getSyntaxError(DbException.java:191)
at org.h2.command.Parser.getSyntaxError(Parser.java:532)
at org.h2.command.Parser.prepareCommand(Parser.java:259)
at org.h2.engine.Session.prepareLocal(Session.java:564)
at org.h2.engine.Session.prepareCommand(Session.java:505)
at org.h2.jdbc.JdbcConnection.prepareCommand(JdbcConnection.java:1204)
at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:170)
at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:158)
at org.h2.tools.Script.process(Script.java:139)
at com.h2.examples.Example.generatBackup(Example.java:57)
at com.h2.examples.Example.main(Example.java:40)
My sample code:
private static final String DB_DRIVER = "org.h2.Driver";
private static final String DB_CONNECTION = "jdbc:h2:~/test";
private static final String DB_USER = "";
private static final String DB_PASSWORD = "";
public static void main(String[] args) throws Exception {
Example example = new Example();
try {
Connection connection = getDBConnection();
example.generatBackup(connection, DB_USER, DB_PASSWORD, "test.sql");
} catch (SQLException e) {
e.printStackTrace();
}
}
private void generatBackup(Connection connection,
String user,
String password,
String fileName) throws SQLException {
Script.process(connection, user, password, fileName);
}
}
Environment:
Windows 10
Eclipse Neon.3 Release (4.6.3)
H2 1.4.194
I was using h2 1.4.197 and seems your usage of parameter order is incorrect. Please have a look at the following API Method for usage of the process API.
process(Connection conn,String fileName, String options1, String options2)

Why i can not connect to mysql db using java

I have used jdbc driver before.But for this piece of program i can't connect to the db.This doesn't throw any exception or anything. Just won't connect. I couldn't find a solution online either.Below is the code i tried to run :( Please help in solving this. Thank you in advance :)
public class HeapMySql<T extends Comparable<T>> implements HeapInterface {
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Heap";
static final String USERNAME = "root";
static final String PASSWORD = "";
private int size = 0 ;
String sql;
static Statement stmt = null;
static Connection conn = null;
static ResultSet rs = null;
public void HeapMySql(){
try
{
sql = "CREATE TABLE testHeap (index integer, value integer);";
stmt.executeUpdate(sql);
System.out.println("Done");
}catch(Exception e){
}
}
public static void main(String [] arg){
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected database successfully...");
System.out.println("Creating table in given database..."); //lets create a table in our database
stmt = conn.createStatement();
HeapMySql test1 = new HeapMySql<>();
}catch(ClassNotFoundException | SQLException ex){
}finally{
}
A constructor does not have a return type: docs
Remove void from public void HeapMySql() and it will do the work.
Also as said in comments, you should print the stacktrace in your catch blocks. This makes it easy to understand the exception and resolve the problem.

Blocked on connecting to Amazon RDS

I have recently deployed a DB Instance on Amazon RDS and I am trying to get the hang of it. After following the instructions on the documentation I tried connecting to that DB Instance but for some reason my simple program which shows the server's version hangs on the connection.
Here is my code:
import java.sql.*;
public class AWSTest {
public static void main(String[] args) {
System.out.println(getVersion());
}
public static String getVersion() {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("Driver Error: " + e.getMessage());
return VERSION_NOT_FOUND;
}
System.out.println(CONNECTING_MESSAGE);
try (Connection con = DriverManager.getConnection(DB_URL,
USER,
PASS);
Statement stmt = con.createStatement();) {
System.out.println("Getting server version...");
try (ResultSet rs = stmt.executeQuery(VERSION_QUERY);) {
rs.next();
return rs.getString(1);
}
} catch (SQLException se) {
System.out.println("SQL Error: " + se.getErrorCode() + " "
+ se.getMessage());
return VERSION_NOT_FOUND;
}
}
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://**************.*******."
+ "*******.rds.amazonaws.com:3306";
private static final String VERSION_QUERY = "Select VERSION()";
static final String USER = "*******";
static final String PASS = "*******";
private static final String VERSION_NOT_FOUND = "Version was not found";
public static final String GETTING_DRIVER_MESSAGE = "Getting driver...";
public static final String CONNECTING_MESSAGE = "Connecting to server...";
}
My program hangs at the line Connection con = DriverManager.getConnection(DB_URL, USER, PASS); and my main problem is that it does not even throw an exception, it just stays there.
USER, PASS and DB_URL are definitely correct.
It sounds like your ip/port is getting blocked/dropped. That's typically the case when a connection does nothing (as opposed to getting refused or failed login). Make sure your Security Group is set up properly. http://aws.amazon.com/rds/faqs/#31

JDBC No suitable driver found

I'm trying to make a custom MySQL class in Java but I'm getting a few exceptions, here's my code:
MySQL.java:
package evo.common;
import java.sql.*;
public class MySQL {
private static String hostname;
private static String username;
private static String password;
private static String database;
public MySQL(String host, String user, String pass, String db)
{
hostname = host;
username = user;
password = pass;
database = db;
}
public static void Error(Exception ex)
{
System.out.println("Fatal Error: "+ex.getMessage());
}
public static void SQLError(SQLException ex)
{
System.out.println("Fatal SQL Error: "+ex.getMessage());
}
private static Connection connect()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch(Exception e){
Error(e);
}
String url = "jdbc:mysql://"+hostname+":3306/"+database;
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch(SQLException ex){
SQLError(ex);
}
return conn;
}
public static ResultSet result(String query)
{
Connection conn = connect();
PreparedStatement pst = null;
ResultSet rs = null;
try
{
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
} catch(SQLException ex){
SQLError(ex);
}
return rs;
}
public static void main(String args[]){}
}
Test.java:
package evo.common;
import java.sql.*;
public class Test {
public static void main(String args[])
{
MySQL mysql = new MySQL("localhost", "root", "******", "souljaz");
ResultSet res = mysql.result("SELECT * FROM users");
}
}
When I run Test I get these error messages in the console:
Fatal Error: com.mysql.jdbc.Driver
Fatal SQL Error: No suitable driver found for jdbc:mysql://localhost:3306/souljaz
Exception in thread "main" java.lang.NullPointerException
at evo.common.MySQL.result(MySQL.java:58)
at evo.common.Test.main(Test.java:8)
I'm quite new to Java so help appreciated. thanks.
Download the lastest version of Connector/J and included it in your Classpath. If you are using an IDE this is only a matter of including the jar in your referenced libraries. If you are doing everything by hand, refer to this official guide:
java -cp "bin;lib/mysql-connector-java-5.1.30-bin" evo.common.Test
Update:
In Eclipse: Right click your project in Package Explorer, then:
Properties -> Java Build Path -> Add JARS... (if lib is in the project)
or Add External JARS... (if it is external)

why can't java see my mysql driver

I'm having trouble working out why java can't see my mysql driver:
I've downloaded the driver .jar from the mysql website
I've added the jar to my runtime classpath
I can confirm the jar is on the classpath, by printing out the relevant system property
But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?
class example:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
My main class simply passes the query into the DB class:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}
You've a typo in the driver class name.
private String driverClassName = "com.myqsl.jdbc.Driver";
it should be
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?

Categories