class.forname() giving the "driverclass" as exception [duplicate] - java

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 8 years ago.
I used the following code segment for connecting my java application to mySQL DB, but its giving an error which I can't figure out why.
try {
con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "ass1";
String driver = "com.mysql.jdbc.Driver";
String user = "";
String pass = "";
System.out.println("OK 1"); //Checkpoint 1
Class.forName(driver).newInstance();
System.out.println("OK 2"); //Checkpoint 2
con = DriverManager.getConnection(url + db, user, pass);
System.out.println("OK 3"); //Checkpoint 3
}
catch (Exception e) {
System.out.println(e.getMessage());
}
Exception(Output):
run:
OK 1
com.mysql.jdbc.Driver
null
BUILD SUCCESSFUL(total time: 13 seconds)
So the exception is driver itself. It's the first time that I'm encountering this.
P.S.: Please ignore the checkpoints.

No Need to call newInstance() method .
Class.forName(driver);
is enough. Check that the required jar is available in your build path or not ?
Another Suggestion
Always try to use printStackTrace() instaed of getMessage()

You do not need to instantiate the driver, just call it's static initialization (e.g., by calling Class.forName) so it gets registered in the DriverManager:
System.out.println("OK 1"); //Checkpoint 1
Class.forName(driver); // no .newInstance() !
System.out.println("OK 2"); //Checkpoint 2
con = DriverManager.getConnection(url + db, user, pass);

Related

Java MySQL connection not working: No suitable driver found [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 2 years ago.
So I am trying to make a connection with JDBC using XAMPP, but it doesn't work, What am I doing wrong here?
public static void main(String args[]) {
try {
Connection myConn = DriverManager.getConnection(
"http://localhost/phpmyadmin/sql.php?db=a3_eindopdracht_2&table=namen&pos=0", "", "");
Statement myStm = myConn.createStatement();
ResultSet myRs = myStm.executeQuery("SELECT * FROM namen");
while (myRs.next()) {
System.out.println(myRs.getString("voornaam") + " " + myRs.getString("achternaam"));
}
} catch (Exception exc) {
exc.printStackTrace();
}
Firstly, you don't find Driver. You have to load them, by calling the Drive class like that :
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// Cannot find driver for MySQL
}
Then, you are trying to connect to your databse with HTTP protocol. But, DB have they own (with port 3306 by default), so you have to use address like that:
jdbc:mysql://myserver.com/schema
Finally: don't forget to add username and password on last 2 fields of getConnection method

JDBC doesn’t connect to Database [duplicate]

This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 3 years ago.
The code below is exactly the same from a YouTube video, but it does not work for me. The expected output is to printout "connected" to the system, which means that JDBC is successfully connected to the database. But I get this error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Here is my code:
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Controller {
private static final String username = "root";
private static final String password = "";
private static final String connection = "jdbc:mysql://localhost/hello";
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection(connection, username, password);
System.out.println("Connected");
}
catch (SQLException se) {
System.err.println(se);
}
}
}
I've added the JDBC successfully as a library, exactly like the video showed but it doesn't work. I saw similar questions on Stack Overflow but none of them solved my problem. Any help will be appreciated, thanks!
JDBC version: mysql-connector-java-5.1.47-bin.jar
Link failure means DB is not reachable, Kindly confirm your DB host,
port, username and password. If everything is correct, kindly confirm
DB server is running and has yet to hit max connection limit.
and you are using JDBC jar file, this may be corrupted. so check it and I suggest you, import JDBC using Maven
and you did not register JDBC driver. first, register it
by using Class.forName("com.mysql.jdbc.Driver"); this
here is one example for your help,
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
I assumed you put the appropriate JDBC dependency in your maven file
and use com.mysql.cj.jdbc.Driver as class for newer versions of MySQL-connector
The name of the class that implements java.sql.Driver in MySQL
Connector/J has changed from com.mysql.jdbc.Driver to
com.mysql.cj.jdbc.Driver. The old class name has been deprecated.

App crash when try to connect to DB with JDBC [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to get some values from my database, but when I click button (void ButtonClick) my app crashes.
That's my code:
public void ButtonClick() throws Exception {
getConnection();
}
public Connection getConnection() throws Exception {
try {
String username = "*******";
String password = "*******";
String url = "jdbc:mysql://http://**.***.***.***:3306/UserDB";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = (Connection) DriverManager.getConnection(url,username,password);
Statement statement = (Statement) conn.createStatement();
String query = "SELECT * FROM TABLE 'UserDB'";
ResultSet result = statement.executeQuery(query);
while (result.next()) {
String name = result.getString("Username");
int id = result.getInt("ID");
int points = result.getInt("Points");
Toast.makeText(this, name + " " + id + " " + points, Toast.LENGTH_SHORT).show();
}
return conn;
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
return null;
}
(I don't know what's the error because my AVD don't work)
Thanks for help!
Starting with Java 7, there is no need to use forName() method. You are creating a new instance in this way and in the same time you are trying to create a connection using DriverManager.getConnection().
So in order to solve this, just remove the instantiation of the driver using forName() method.
Seeing the screen-shot, please note that you can't access a MySQL database from Android natively. Actually you may be able to use JDBC, but it is not recommended. Please see this post
Hope it helps.

How do I connect to access database using java at runtime? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Accessing Access over JDBC (using ODBC?)
I have to do this since we have an unknown amount of access databases the user can select using our program so as to process data from them.
Here is connection code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=ACCESS_FILE_PATH/FILE_NAME.mdb";
connection = DriverManager.getConnection( database ,"username","password");
I did it as the following:
first , create a db DB1.MDB which contain a table named "table1";
second, config ODBC , create DatabaseSource named "Access2000"。
import java.sql.*;
class database {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url="jdbc:odbc:Access2000";
Connection connection=DriverManager.getConnection(url);
Statement statement = connection.createStatement();
String sql="SELECT * FROM table1";
ResultSet rs = statement.executeQuery(sql);
String tt;
while (rs.next()) {
System.out.print("name:" + rs.getString("Name"));
System.out.println("age:" + rs.getString("Age"));
}
rs.close();
connection.close();
}
catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
}

Connecting Java to MySQl database

Is there a standard way to connect a Java program to a MySQL database, and which is the easiest one?
JDBC is the standard way also the easiest.
In addition to answer posted above, JPA (Hibernate) is even easier one once you cross the initial barrier called learning curve (and before you are hit by next one called, Performance Optimization). On the serious note, Yes JPA is also a standard way to connect and query pretty much any database the same way.
JDBC is the standard way. Below is the sample java code to connect MySQL database:
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String db = "testdb";
String dbUser = "root";
String dbPasswd = "mysql123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "DELETE FROM user WHERE email = 'riponalwasim#gmail.com'";
int delete = st.executeUpdate(sql);
if(delete >= 1){
System.out.println("Row is deleted.");
}
else{
System.out.println("Row is not deleted.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
Maybe object-relational mapping with Hibernate is a useful way for you.

Categories

Resources