JDBC No suitable driver found - java

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)

Related

database result are not showing in java

I typed this code but no record is coming from database...I have attached Ms Access database
Need help please...
the output only says "build successful".
import java.sql.*;
public class Db {
Connection con;
Statement st;
ResultSet rs;
//constructor
public Db(){
connect();
}
//connect funtion
public void connect(){
try {
String driver;
driver = "sun.jdbc.odbc.JbdcObdcDriver";
Class.forName(driver);
String db;
db="jbdc:obdc:db2";
//connectin to db
con=DriverManager.getConnection(db);
String sql;
sql="Select * from Table1";
rs=st.executeQuery(sql);
while (rs.next()){
String fname=rs.getString("FirstName");
String lname=rs.getString("LastName");
String age=rs.getString("age");
System.out.println(fname+" "+lname+" "+age);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
// TODO code application logic here
}
Db d=new Db();

java with ms access not showing database result

I'm trying to connect with MS-Access using java but When I Compile this code it gives me no error and compile fine but it doesn't show any result while the database has records in it, table name and field name are also correct, anyone can please help me that what I'm doing wrong in it.
import java.sql.*;
public class database{
Connection dbCon;
Statement statement;
ResultSet result;
public database(){
connect();
}
public void connect(){
try{
String Driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(Driver);
String Sdb = "jdbc:odbc:students";
dbCon = DriverManager.getConnection(Sdb);
statement = dbCon.createStatement();
String sqlQuery = "SELECT * FROM StudentInfo";
result = statement.executeQuery(sqlQuery);
while(result.next()) {
//String name = result.getString("Studentname");
System.out.println(result.getString("Studentname"));
}
}catch(Exception ex){
}
}
public static void main(String[] args) {
System.out.println("**ACCESS DB CONNECTION**");
new database();
}
}
You are not getting error during execution of program because you are eating exception here:
catch(Exception ex){
}
You should try to print the exception trace to know what is going wrong.
catch(Exception ex){
ex.printStackTrace();
}

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

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

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

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