Connecting to MySql on Mac: No suitable driver error - java

I am getting the error: java.sql.SQLException: No suitable driver
I have imported the .jar file that is available here http://dev.mysql.com/downloads/mirror.php?id=13598
I am using Eclipse.
I am connecting to the DB with this code:
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBCon {
private static final String host = "jdbc:mysql://localhost";
private static final String port = "3306";
private static final String db = "mydb";
// private static final String user = "root";
// private static final String pwd = "";
private static final String user = "myusername";
private static final String pwd = "mypwd";
public Connection getCon() {
Connection con = null;
try {
String url = host + ":" + port + "/" + db;
con = DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
I then query the DB with this code:
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.sql.Connection;
import model.ClassPojo;
public class ARCSDao {
public ArrayList<ClassPojo> viewClasses() throws SQLException{
ArrayList<ClassPojo> classList = new ArrayList<ClassPojo>();
DBCon db = new DBCon();
Connection con = db.getCon();
Statement stmt;
ResultSet rs;
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM classes");
while(rs.next()){
ClassPojo aClass = new ClassPojo();
rs.getString("class_name");
rs.getString("class_uri");
classList.add(aClass);
}
return classList;
}
}

Add
Class.forName("com.mysql.jdbc.Driver").newInstance();
before
con = DriverManager.getConnection(url, user, pwd);
if this doesn't work double check that the jdbc driver (jar file) is included in your classpath

Related

Can`t make insert in Oracle database from JSF Java web app

I have a JSF webapp and I encountered one problem. I want to take data that is from one table and is inserted in a datatable and insert it into a log table in the database.
I did the connection with the database but it doesn't show any errors and it doesn't insert anything.
I went in with the debugger from netbeans and the variables that I want to insert have values. I do not know where the problem is.
Here is the code:
package com.spv.raport;
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.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleDataSource;
#Named(value = "dateBean")
#RequestScoped
public class DateBean {
private List<Date> dateList = new ArrayList<>();
public DateBean() throws ClassNotFoundException, SQLException {
String host = "jdbc:oracle:thin:#xxx:1521:xxx";
String user = "xxx";
String pass = "xxx";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(host, user, pass);
Statement stmt = con.createStatement();
String sql = "select utilizator, tip_cerere, parametri, stare from
cereri where tip_cerere='D394' and utilizator='44192556' ";
ResultSet rs = stmt.executeQuery(sql);
String u = null;
String t = null;
String p = null;
String s = null;
String d = null;
while(rs.next()) {
u = rs.getString("utilizator");
t = rs.getString("tip_cerere");
p = rs.getString("parametri");
s = rs.getString("stare");
// d = rs.getString("creation_date");
dateList.add(new Date(u,t,p,s));
}
String host2 = "jdbc:oracle:thin:#xxx:xxx";
String user2 = "xxx";
String pass2 = "xxx";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con2 = DriverManager.getConnection(host2, user2, pass2);
Statement stmt2 = con2.createStatement();
String sql2 = "insert into SPV_RAPORT_LOG values ('serban', '123',
'parametru_test')";
stmt2.executeUpdate(sql);
} catch(SQLException se) {System.out.println(se);}
catch(Exception e) {System.out.println(e);}
}
public List<Date> getDateList() {
return dateList;
}
}
The database host and name and user and passwords are put intentionally with xxx to hide them.
I am a beginner and I do not have any idea why it doesn`t insert the test statement into the database table

Netbeans MySQL Connection - not to do with jbdc

I have a login app that needs to connect to a server to check the username and password. I am using netbeans and the jbdc is installed and working in the services tab(thanks stack overflow!). By the jbdc is work I mean that i can execute SQL script through it.
I have set this up with MS Server 16 and MySQL so I am convied it is the code:
Connection method:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
private static final String USERNAME = "root";
private static final String PASSWORD = "mess";
private static final String SQCONN = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection()throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(SQCONN, USERNAME, PASSWORD);
}catch (ClassNotFoundException e) {
}
return null;
}
}
loginmodel:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
Connection connection;
public LogInModel() {
try{
this.connection = dbConnection.getConnection();
}catch(SQLException e){
}
if(this.connection == null){
System.out.println("here");
// System.exit(1);
}
}
public boolean isDatabaseConnected(){
return this.connection != null;
}
public boolean isLogin(String username, String password) throws Exception{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
try{
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
boolean bool1;
if(rs.next()){
return true;
}
return false;
}
catch(SQLException ex){
return false;
}
finally {
{
pr.close();
rs.close();
}
}
}
}
I believe the issue is the return null; from the dbConnection file. The if(this.connection==Null) comes back true and the system is exiting.
Thank you in advance.
Your dbConnection class is a bad idea. Why hard wire those values when you can pass them in?
Your application will only have one Connection if you code it this way. A more practical solution will use a connection pool.
Learn Java coding standards. Your code doesn't follow them; it makes it harder to read and understand.
Here's a couple of recommendations:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "root";
public static final String PASSWORD = "mess";
public static final String URL = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
I might write that LogInModel this way:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
private static final String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
private Connection connection;
public LogInModel(Connection connection) {
this.connection = connection;
}
public boolean isLogin(String username, String password) {
boolean isValidUser = false;
PreparedStatement pr = null;
ResultSet rs = null;
try {
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
while (rs.hasNext()) {
isValidUser = true;
}
} catch (SQLException ex) {
e.printStackTrace();
isValidUser = false;
} finally {
dbUtils.close(rs);
dbUtils.close(pr);
}
return isValidUser;
}
}
Here's my guess as to why your code fails: You don't have the MySQL JDBC driver JAR in your runtime CLASSPATH. There's an exception thrown when it can't find the driver class, but you didn't know it because you swallowed the exception.

java ResultSet and statement issue

i don't understand why my variable state cannot be resolved.
i'm in a java Mysql project.
Here is the Commands class code:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Commands {
public Commands() throws SQLException{
Connection conn = DbConn.getInstance();
Statement state = conn.createStatement();
}
public String getList(){
System.out.println("Here is a List of our Products:");
// Get list from db
ResultSet result = state.executeQuery("SELECT * FROM products");
ResultSetMetaData resultMeta = result.getMetaData();
// Display the List
System.out.println("List displayed");
return null;
}
}
Here is the DbConn class code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConn {
private static String url = "jdbc:mysql://localhost:3306/myDB";
private static String user = "root";
private static String passwd = "";
private static Connection connect;
// create new instance if not exists
public static Connection getInstance(){
if(connect == null){
try {
connect = DriverManager.getConnection(url, user, passwd);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connect;
}
}
My code is not finished yet, but the message come on this line:
ResultSet result = state.executeQuery("SELECT * FROM products");
My Eclipse editor says this message state cannot be resolved
Any idea?
That is a matter of scope. You define the variable here
public Commands() throws SQLException{
Connection conn = DbConn.getInstance();
Statement state = conn.createStatement();
}
And that is the only place the variable is visible - in the constructor. Define it in the class and initialize it in the constructor:
private Connection conn = null;
private Statement state = null;
public Commands() throws SQLException{
conn = DbConn.getInstance();
state = conn.createStatement();
}
Declare "State" outside of that constructor.
Connection conn = null;
Statement state = null;
public Commands() throws SQLException{
conn = DbConn.getInstance();
state = conn.createStatement();
}

While calling the below function control is going to the first line inside try block i.e to Class.forName then to catch block

package com.java.bean;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Dao {
// static Connection con = null;
static ResultSet rs = null;
static String url ="jdbc:mysql://localhost:3306/first";
static String user = "root";
static String passsword = "password";
public static Ex1 login(Ex1 ex){
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.driver");
Connection con = DriverManager.getConnection(url,user,passsword);
String userName = ex.getUserName();
String password = ex.getPassword();
Statement st = con.createStatement();
rs = st.executeQuery("Select * from employee where username = " +userName +"and password =" +password );
boolean more = rs.next();
if(!more)
{
System.out.println("you are not a registered user!");
ex.setValid(false);
}
else if(more)
{
System.out.println("welcome MR.HImanshu you are Great");
ex.setValid(true);
}
}
catch(Exception tex)
{
System.out.println("hey there is an exception " +ex);
}
return ex;
}
}
Is
Class.forName("com.mysql.jdbc.Driver");
not
Class.forName("com.mysql.jdbc.driver");
"Driver" with an uppercase "D".

java.sql.SQLException: No suitable driver found

I am trying to execute simple query using below DbQuery.java class which uses DbConnector to get a Connection from DriverManager.
note:
I have already included "mysql-connector-java-5.1.25-bin.jar" on my
classpath via: export
CLASSPATH=$CLASSPATH:/home/me/ocpjp/chapter-10/mysql-connector-java-5.1.25/mysql-connector-java-5.1.25-bin.jar
I am able to connect to mysql with "mysql -uroot -ptcial
addressBook", if it matters.
have also tried running with '-cp'
argument with no avail.
I am able to get my #3 DbConnect.java class to say "Database connection established".
Also #4 DbQueryWorking.java has no issues and provides expected output .
Can you please help me understand what is the issue here ?
1) DbConnector.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnector{
public static Connection connectToDb() throws SQLException{
String url = "jdbc:mysql//localhost:3306/";
String db = "addressBook";
String username = "root";
String password = "tcial";
return DriverManager.getConnection(url+db, username, password);
}
}
2) DbQuery.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import com.me.ocpjp.chapter10.DbConnector;
public class DbQuery{
public static void main(String[] args){
try(Connection connection = DbConnector.connectToDb();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
3) DbConnect.java
package com.me.ocpjp.chapter10;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbConnect{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url+database, userName, password)){
System.out.println("Database connection established");
}catch(Exception e){
System.out.println("Database connectioni NOT established");
e.printStackTrace();
}
}
}
4) DbQueryWorking.java
package com.me.ocpjp.chapter10;
import java.sql.Connection ;
import java.sql.Statement ;
import java.sql.ResultSet ;
import java.sql.SQLException ;
import java.sql.DriverManager;
public class DbQuery{
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306/";
String database = "addressBook";
String userName = "root";
String password = "tcial";
try(Connection connection = DriverManager.getConnection(url + database, userName, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from contact")){
System.out.println("ID \tfName \tlName \temail \t\tphoneNo");
while(resultSet.next()){
System.out.println(resultSet.getInt("id") + "\t"
+ resultSet.getString("firstName") + "\t"
+ resultSet.getString("lastName") + "\t"
+ resultSet.getString("email") + "\t"
+ resultSet.getString("phoneNo") );
}
}catch(SQLException sqle){
sqle.printStackTrace();
System.exit(-1);
}
}
}
it looks like that the URL in DbConnector.java is wrong. A colon is missing. The url must be:
jdbc:mysql://localhost:3306/
and not
jdbc:mysql//localhost:3306/
your URL is wrong, you're missing a colon in it, it should be:
String url = "jdbc:mysql://localhost:3306/";

Categories