issues with mysql connection in java: No suitable Driver [duplicate] - java

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 8 years ago.
I'm making a small program in Java that uses a Mysql connection but im getting some problems with the jdbc drivers. I installed Java EE and Java SE but i still get the message that there are no suitable driver for jdbc:mysql://localhost:3307/test. Can someone explain to me what i am doing wrong.
Code:
public class Mysql_Connection_2 {
/**
* #param args the command line arguments
*/
static String query = "select count(*) from stock";
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
Logger.getLogger(MysqlConnection.class.getName()).log(Level.SEVERE, null, ex);
}
MysqlConnection.dbConnection(query);
}
}
Extern Connection class:
public class MysqlConnection {
private static final String dbURL = "jdbc:mysql://localhost:3307/test";
private static final String dbuname = "root";
private static final String dbpass = "usbw";
static Connection dbcon = null;
static Statement stmt = null;
static ResultSet rs = null;
public static void dbConnection (String query){
try{
//getting database connection to MySQL server
dbcon = DriverManager.getConnection(dbURL, dbuname, dbpass);
//getting PreparedStatment to execute query
stmt = dbcon.prepareStatement(query);
//Resultset returned by query
rs = stmt.executeQuery(query);
while(rs.next()) {
int count = rs.getInt(1);
System.out.println("count of stock : " + count);
}
}
catch(SQLException ex){
System.out.println(ex.getMessage());
}
}
}

First You need to correct your driver
Class.forName("com.mysql.jdbc.Driver");
Then Check You added mysql connector jar file
after that you need to make sure that jar file is added to your class path or not.
Correct the First one and go to second and then third

1) As pointed out in above answers, for MySql you should use
Class.forName("com.mysql.jdbc.Driver");
2) Make sure you have jar in classpath.
You can download jar from mvnrepo MVNREPO
3) Port is 3306 for MySql?
And a quick google for JAVA + MYSQL gives me this tutorial

If you are trying to use mysql then the class should be com.mysql.jdbc.Driver and you should have mysql jdbc connectivity jar file in class path.
Initialize the driver using
Class.forName("com.mysql.jdbc.Driver").newInstance();

you are trying to access mysql database through oracle driver so you are getting error
try to use
Class.forName("com.mysql.jdbc.Driver");

try this
try {
Class.forName("com.mysql.jdbc.Driver");
}
and
private static final String dbURL = "jdbc:mysql://localhost:3306/test";

I can see one problem here. You are using Oracle driver to perform operation on the MySQL database.
try {
Class.forName("com.mysql.jdbc.Driver");
}
Try this.
You need not specify the port number if you are using the default port.jdbc:mysql://localhost/dbName should do

Related

How to instance 1 connection class for multiple requests?

So I'm currently working on a project that will be using a database but its my first time trying fiddling with it on java.
But I'm already seeing my first problem is how would i make one single file that handles connection while other files handles GET/ADD/UPDATE/DELETE (one for each table) what would properly be the best way on doing this ?
To not having to place connection values in each file and do the connection
I though about extending the connection class with the other classes but idk if its a great idea.
import java.sql.*;
public class DatabaseConnection {
public static void main(String[] args) {
final String url = "jdbc:postgresql://localhost:5432/Database";
final String user = "dbuser";
final String password = "dbpass";
try(Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connection successful!");
} catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}
What would be the best approach?
Maybe i'm wrong, but i think you need connection pool.
Try to find instruction here https://www.baeldung.com/java-connection-pooling
You could move the database connection related code to a utility class, and use the PreparedStatement class to precompile the SQL Query
public class doSomething {
Connection conn = null;
PreparedStatement pst = null;
public static void main(String [] args){
conn = DatabaseConnection.connect()
String qry = "Select * from table_name";
pst = (PreparedStatement) conn.prepareStatement(qry);
}
}

Java Class Not Found Exception When Trying to Connect Into Database

Im trying to insert data into SQL SERVER 2008 database through java class. Here is my code:
public class DB_Sample
{
public static void main (String[] args)
{
try
{
String dbUrl = "jdbc:microsoft:sqlserver://ZAFRAN-PC:1433;databaseName=presentasi;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();;
Connection con = DriverManager.getConnection(dbUrl);
Statement st = con.createStatement();
st.executeUpdate("Insert into barang(nama_barang, jumlah_stok, merk, harga_barang) values('HANDUK','30','ADIDAS','25000')");
con.commit();
ResultSet rs = st.executeQuery("select * from barang");
String i1="";
while(rs.next())
{
i1 = rs.getString(1);
System.out.println("Nama barang: " +i1+ " Berhasil Diinputkan");
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Also i add sqljdbc4.jar in CLASSPATH.
.;C:\Program Files\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu\sqljdbc4.jar;
But when i run my java class throug CMD i got an error message like this:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
So whats the problem i have ? and how i can fix this problem ?

connecting Java to MySQL

I'm doing my dissertation on software engineering and im building a small application that makes use of a SQL DB, in this case MySQL. I'm also using the application controller pattern. So the code I have working for retrieving data from the db is;
public static void main(String[] args)
{
try
{
String url = "jdbc:mysql://localhost:3306/tm470_returns_stock_management_system";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"root","root");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM test_table");
while (res.next())
{
int id = res.getInt("test_id");
String msg = res.getString("test_info");
System.out.println(id + "\t" + msg);
}
con.close();
}
catch(Exception e)
{
System.out.println("DB connection unsuccesful");
}
}
I now want to transfer this out of my Main class/string and into my Application Controller Class (which is called Facility).
Now my question is, for every method in my Facility Class that needs to access the DB, do i have to do the full code each time? Or can i create a method within the Facility class that each application method can just call whenever it needs to access the DB. If i can condense all this into a method, can you advise me how to go about it please?
Be gentle with me guys, I am a learner :)
How about adding a utility class like ConnectionUtil and using the static method to access the connection.
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionUtil{
static final String url = "jdbc:mysql://localhost:3306/";
static final String dbName = "test";
static final String driver = "com.mysql.jdbc.Driver";
static final String userName = "userparatest";
static final String password = "userparatest";
Connection con = null;
static Connection getConnection() throws Exception {
if(con == null)
{ Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + dbName, userName,password);
}
return con;
}
}
this can be further improved but just providing a start..
just call below whenever you want a statement..
Statement st = ConnectionUtil.getConnection().createStatement();
I would map it as a own class, which is used by your application other classes. When you define it as a singleton you will only need one instance in your complete application
Yes , you can write a method for accessing db and you can reuse it across all the applications.
Keep the following in a method and reuse it.
String url = "jdbc:mysql://localhost:3306/tm470_returns_stock_management_system";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"root","root");
Statement st = con.createStatement();
int productID = 6;
String skuCode = "ABC123";
ResultSet res = st.executeQuery("SELECT * FROM test_table");
while (res.next())
{
int id = res.getInt("test_id");
String msg = res.getString("test_info");
System.out.println(id + "\t" + msg);
}

I can't connect to my sql and my driver is not found [duplicate]

This question already has answers here:
How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools? [duplicate]
(21 answers)
Closed 8 years ago.
I have this code in my Database controller
package nypHeritage.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBController {
//Declaration of attributes
private Connection con;
/********************************************************
* Method Name : testDriver
* Input Parameter : nil
* Purpose : To test if the driver is properly installed
* Return :nil
*******************************************************/
public void testDriver() throws Exception {
System.out.println("Initializing Server... ");
try {
Class.forName("org.gjt.mm.mysql.Driver");
System.out.println(" Driver Found.");
}
catch (ClassNotFoundException e) {
System.out.println(" Driver Not Found, exiting..");
throw (e);
}
}
public void getConnection(){
String url = "";
try {
url = "jdbc:mysql://localhost/nyp_heritage";
con = DriverManager.getConnection(url, "IT1639User", "user");
System.out.println("Successfully connected to " + url+ ".");
}
catch (java.sql.SQLException e) {
System.out.println("Connection failed ->"+ url);
System.out.println(e);
}
}
/************************************************************
* Method Name : readRequest
* Input Parameter : String (database query)
* Purpose : Obtain the result set from the db query
* Return : resultSet (records from the query)
************************************************************/
public ResultSet readRequest(String dbQuery) {
ResultSet rs = null;
System.out.println("DB Query: " + dbQuery);
try {
// create a statement object
Statement stmt = con.createStatement();
// execute an SQL query and get the result
rs = stmt.executeQuery(dbQuery);
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
/***********************************************************
* Method Name : updateRequest
* Input Parameter : String (database query)
* Purpose : Execute update using the db query
* Return : int (count is 1 if successful)
***********************************************************/
public int updateRequest(String dbQuery) {
int count = 0;
System.out.println("DB Query: " + dbQuery);
try {
// create a statement object
Statement stmt = con.createStatement();
// execute an SQL query and get the result
count = stmt.executeUpdate(dbQuery);
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
/***********************************************************
* Method Name : terminate
* Input Parameter : nil
* Purpose : Close db conection
* Return :nil
**********************************************************/
public void terminate() {
// close connection
try {
con.close();
System.out.println("Connection is closed");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] arg)throws Exception{
DBController db = new DBController();
db.testDriver();
}
}
It was perfectly working last 2 months but now when I reopened it, it showed me this error
Connection failed ->jdbc:mysql://localhost/nyp_heritage
java.lang.NullPointerException
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/nyp_heritage
DB Query: INSERT INTO PARTICIPANT(name, mobile, monthOfEvent, eventName, dateBirth, address, email, gender) VALUES ('Samantha Jones','+6590287645', 'december', 'Heritage Centres Tour', '19/05/1990', 'Woodlands', 'jones#gmail.com', 'Female')
It says, my connection is failed and that no suitable driver was found for my localhost. HELP PLS! I'm not sure how to fix this problem...
First, make sure you have an appropriate connector for mysql on your classpath. With JDBC 4.0 and up you don't need
Class.forName("org.gjt.mm.mysql.Driver"); // which should be "com.mysql.jdbc.Driver"
// since the one you appear to be trying
// is truly ancient.
From the DriverManager javadoc,
Applications no longer need to explictly load JDBC drivers using Class.forName().
change
Class.forName("org.gjt.mm.mysql.Driver");
to
Class.forName("com.mysql.jdbc.Driver");
Based on what I have found the
First,
org.gjt.mm.mysql.Driver is out dated.
so you should use this instead in Class.forName section
com.mysql.jdbc.Driver
Resource:
What is the jdbc driver "org.gjt.mm.mysql.Driver" for?
Second,
you should check whether you have appropriate J connector jar file added in your project
you can check this in here http://dev.mysql.com/downloads/connector/j/
Third,
you can use try catch block with resources to be sure that whatever you have opened is closed if it is close-able
For example
public void update(String name, String tel, String id) throws SQLException {
System.out.println("in update part tel is " + tel);
String sql = "UPDATE APP.DBNAME "
+ "SET NAME=? , TEL=? WHERE NAME=?";
try (PreparedStatement ps = getConn().prepareCall(sql)) {
ps.setString(1, name);
ps.setString(2, tel);
ps.setString(3, id);
ps.executeUpdate();
}
}
Fourth,
JDBC 4.0 Features
Thanks to the Java SE Service Provider mechanism included in Mustang,
Java developers no longer need to explicitly load JDBC drivers using
code like Class.forName() to register a JDBC driver. The DriverManager
class takes care of this by automatically locating a suitable driver
when the DriverManager.getConnection() method is called. This feature
is backward-compatible, so no changes are needed to the existing JDBC
code.
the resource:
http://www.onjava.com/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html

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