0

am getting an exception as java.sql.Connection.prepareStatement(String) because con is null, I don't know why as I have already added MySQL Connector jar file.

import java.sql.Connection;
import java.sql.PreparedStatement;

public class Studentdao {

public static boolean insertStudenttoDB(Student st) {

    boolean f=false;
try {
Connection con =CP.createc();
//jdbc code
String q="insert into students(sname,sphone scity)values(?,?,?)";
PreparedStatement pstmt=con.prepareStatement(q);
pstmt.setString(1,st.getStudentname());
pstmt.setString(2,st.getStudentcity());
pstmt.setLong(3,st.getStudentphone());

//execute
pstmt.executeUpdate();
f=true;

}
catch(Exception e) {
    e.printStackTrace();
}
return f;
}
}

This is my connection program

import java.sql.Connection;
import java.sql.DriverManager;

public class CP {


static Connection con;
//load driver
public static Connection createc() {
    try {
Class.forName("com.sql.jdbc.Driver");

//creating connection
String user="mysql";
String password="mysql";
String url="jdbc:mysql://localhost:3306/student_manage";
    con=DriverManager.getConnection(url,user,password);
     
}catch(Exception e) {
    e.printStackTrace();
}

 return con;        
}
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

2 Answers2

0

Incorrect class name

You appear to have an incorrect class name, if you are using the Connector/J product as your JDBC driver.

Section 3.6.1 of the Connector/J manual shows the use of "com.mysql.cj.jdbc.Driver" versus your use of "com.sql.jdbc.Driver". Here is their code example:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!
public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }
    }
}

DataSource

Note that your use of Class.forName is generally not needed in modern Java. The JDBC architecture was years ago revamped so that now drivers are automatically located and loaded using the Java Service Provider Interface (SPI) technology.

I do suggest you make a habit of using a DataSource to obtain connections rather than calling on the DriverManager. Using DataSource makes your code much more flexible. You will be able to switch JDBC drivers, add connection pooling, and externalize configuration info (server address, database name, user name, password, etc.) for deployment.

Usually your JDBC driver comes with a basic implementation of DataSource. Check the documentation for all the various options you can set, specific to your database (MySQL in this case).

For MySQL, I understand the implementation of DataSource currently provided in Connector/J is com.mysql.cj.jdbc.MysqlDataSource. Caveat: I make regular use of Postgres & H2, not MySQL, so I may not be up-to-date.

See my Answer to another Question for source code of a full example of connecting and working with MySQL. Here are the parts relating to DataSource and Connection.

    private DataSource configureDataSource ( )
    {
        System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );

        com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() );  // Implementation of `DataSource` bundled with H2.
        dataSource.setServerName( "db-mysql-sfo3-422-do-user-8982-1.x.db.ondigitalocean.com" );
        dataSource.setPortNumber( 24_090 );
        dataSource.setDatabaseName( "defaultdb" );
        dataSource.setUser( "scott" );
        dataSource.setPassword( "tiger" );
        return dataSource;
    }

Early in the lifecycle of your app, instantiate and retain the DataSource object returned from that method. Remember, a DataSource holds only the configuration details; it is not an open resource itself, and need not be closed.

DataSource dataSource = this.configureDataSource();

To open a connection, pass the DataSource to your method that wants to connect to the database.

private void dumpTable ( DataSource dataSource ) { … }

Here is a piece of that dumpTable method.

Notice the use of try-with-resources syntax to automatically close the open resources in the order in which they were declared, even in case of failure with exceptions being thrown.

        String sql = "SELECT * FROM event_ ;";
        try (
                Connection conn = dataSource.getConnection() ;  //  Use the passed `DataSource` object to ask for a `Connection` object.
                Statement stmt = conn.createStatement() ;
                ResultSet rs = stmt.executeQuery( sql ) ;
        )
        {
            …
        }
        catch ( SQLException e )
        {
            e.printStackTrace();
        }
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

here's the code I tried to connect java class with mysql. Make sure you have to add the required driver to your libraries.

import java.sql.Connection;
import java.sql.DriverManager;
public class Server {
public static Connection getConnection()
{
try
{
   Class.forName("com.mysql.jdbc.Driver");
   String urls = "127.0.0.1";//you can even replace this with localhost
   String username = "yourusername";
   String password = "1234";
   Connection conn = DriverManager.getConnection("jdbc:mysql://"+urls+":3306/yourdb?useUnicode=yes&characterEncoding=UTF-8", username, password);
   return conn;
}
catch(Exception e)
{
   e.printStackTrace();
}
return null;
}
Ask Warvin
  • 53
  • 3
  • 12