Connect Java to a MySQL databaseClassNotFoundException com.mysql.jdbc.Driverjava.lang.ClassNotFoundException:com.mysql.jdbc.DriverHow to connect Java to Mysql?ClassNotFoundException: com.mysql.jdbc.DriverCan't find jdbc driver?How to connect with MySQL DB running as container in docker?can anyone teach me how to install mysql connector in java…?inserting data into database using JSPDriverManager.getConnection returns nullCentos mysql connector java - JDBC DriverIs Java “pass-by-reference” or “pass-by-value”?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL serverCreating a memory leak with JavaCan't start Eclipse - Java was started but returned exit code=13No suitable driver found for jdbc:mysql/localhost:3306/worldHow to connect to mysql through jdbc

expl3-strategy to automatically update the title of a document, depending on its content

What happened to python's ~ when working with boolean?

How to make a Lich look like a human without magic in 5e?

How to slow yourself down (for playing nice with others)

Delta TSA-Precheck status removed

Is there any evidence to support the claim that the United States was "suckered into WW1" by Zionists, made by Benjamin Freedman in his 1961 speech?

Is there a need for better software for writers?

Composite Factor Soup

Why do Thanos's punches not kill Captain America or at least cause some mortal injuries?

What did Rocket give Hawkeye in "Avengers: Endgame"?

Thesis' "Future Work" section – is it acceptable to omit personal involvement in a mentioned project?

Can you book a one-way ticket to the UK on a visa?

Why use steam instead of just hot air?

How are one-time password generators like Google Authenticator different from having two passwords?

How does Howard Stark know this?

Why was this sacrifice sufficient?

Why does "decimal.TryParse()" always return 0 for the input string "-1" in the below code?

Looking for a simple way to manipulate one column of a matrix

Is a diamond sword feasible?

Remove everything except csv file Bash Script

Can 'sudo apt-get remove [write]' destroy my Ubuntu?

Was there a contingency plan in place if Little Boy failed to detonate?

Is "now" UTC time in Solidity?

stdout and stderr redirection to different files



Connect Java to a MySQL database


ClassNotFoundException com.mysql.jdbc.Driverjava.lang.ClassNotFoundException:com.mysql.jdbc.DriverHow to connect Java to Mysql?ClassNotFoundException: com.mysql.jdbc.DriverCan't find jdbc driver?How to connect with MySQL DB running as container in docker?can anyone teach me how to install mysql connector in java…?inserting data into database using JSPDriverManager.getConnection returns nullCentos mysql connector java - JDBC DriverIs Java “pass-by-reference” or “pass-by-value”?How do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL serverCreating a memory leak with JavaCan't start Eclipse - Java was started but returned exit code=13No suitable driver found for jdbc:mysql/localhost:3306/worldHow to connect to mysql through jdbc






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








291















How do you connect to a MySQL database in Java?



When I try, I get



java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)


Or



java.lang.ClassNotFoundException: com.mysql.jdbc.Driver


Or



java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver









share|improve this question
























  • Here's a short 3-minute video tutorial that demonstrates using MySQL from Java. Check it out here: Quick Tutorial: Connecting to MySQL database using Java

    – drorw
    Oct 10 '18 at 12:47


















291















How do you connect to a MySQL database in Java?



When I try, I get



java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)


Or



java.lang.ClassNotFoundException: com.mysql.jdbc.Driver


Or



java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver









share|improve this question
























  • Here's a short 3-minute video tutorial that demonstrates using MySQL from Java. Check it out here: Quick Tutorial: Connecting to MySQL database using Java

    – drorw
    Oct 10 '18 at 12:47














291












291








291


199






How do you connect to a MySQL database in Java?



When I try, I get



java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)


Or



java.lang.ClassNotFoundException: com.mysql.jdbc.Driver


Or



java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver









share|improve this question
















How do you connect to a MySQL database in Java?



When I try, I get



java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)


Or



java.lang.ClassNotFoundException: com.mysql.jdbc.Driver


Or



java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver






java mysql jdbc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 23 '18 at 7:23









Mark Rotteveel

62.7k1479124




62.7k1479124










asked May 15 '10 at 7:39









absonabson

3,882134463




3,882134463












  • Here's a short 3-minute video tutorial that demonstrates using MySQL from Java. Check it out here: Quick Tutorial: Connecting to MySQL database using Java

    – drorw
    Oct 10 '18 at 12:47


















  • Here's a short 3-minute video tutorial that demonstrates using MySQL from Java. Check it out here: Quick Tutorial: Connecting to MySQL database using Java

    – drorw
    Oct 10 '18 at 12:47

















Here's a short 3-minute video tutorial that demonstrates using MySQL from Java. Check it out here: Quick Tutorial: Connecting to MySQL database using Java

– drorw
Oct 10 '18 at 12:47






Here's a short 3-minute video tutorial that demonstrates using MySQL from Java. Check it out here: Quick Tutorial: Connecting to MySQL database using Java

– drorw
Oct 10 '18 at 12:47













13 Answers
13






active

oldest

votes


















193














DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:



Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");


or instantiating and configuring one from your database driver directly:



MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");


and then obtain connections from it, same as above:



Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();





share|improve this answer


















  • 1





    how come the other examples use com.mysql.jdbc.Driver? is this method better?

    – Jason S
    May 21 '10 at 3:21






  • 7





    I think this is the old-style Driver class that works with the old-style driver mechanism. MysqlDataSource implements javax.sql.DataSource which is the newer mechanism.

    – Sean Owen
    May 21 '10 at 9:00






  • 1





    Hi @SeanOwen I wonder that, why do we close rs and stmt? Why not just conn?

    – Kamuran Sönecek
    Apr 14 '16 at 6:37






  • 3





    Maybe you should add dataSource.setDatabaseName("database").

    – Myoch
    May 22 '16 at 11:14







  • 1





    It's good practice to close() things explicitly, though it is more code. Any good implementation would have to close the resources when the connection closes, yes. Consider other contexts where you want to reuse a statement or connection though. In Java 7's try-with-resources, you get this behavior for free anyway:

    – Sean Owen
    May 29 '16 at 13:22


















439














Here's a step by step explanation how to install MySQL and JDBC and how to use it:



  1. Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.



  2. Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).



    If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.



    If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.



    java -cp .;/path/to/mysql-connector.jar com.example.YourClass


    The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.




  3. Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.



    CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;



  4. Create an user for Java and grant it access. Simply because using root is a bad practice.



    CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
    GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';


    Yes, java is the username and password is the password here.




  5. Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:



    jdbc:mysql://hostname:port/databasename


    • hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.


    • port: The TCP/IP port where MySQL server listens on. This is by default 3306.


    • databasename: The name of the database you'd like to connect to. That's javabase.


    So the final URL should look like:



    jdbc:mysql://localhost:3306/javabase



  6. Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.



    String url = "jdbc:mysql://localhost:3306/javabase";
    String username = "java";
    String password = "password";

    System.out.println("Connecting database...");

    try (Connection connection = DriverManager.getConnection(url, username, password))
    System.out.println("Database connected!");
    catch (SQLException e)
    throw new IllegalStateException("Cannot connect the database!", e);



    If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:



    System.out.println("Loading driver...");

    try
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("Driver loaded!");
    catch (ClassNotFoundException e)
    throw new IllegalStateException("Cannot find the driver in the classpath!", e);



    Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.



    Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.



    If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
    Communications link failure
    , then it means that the DB isn't reachable at all. This can have one or more of the following causes:



    1. IP address or hostname in JDBC URL is wrong.

    2. Hostname in JDBC URL is not recognized by local DNS server.

    3. Port number is missing or wrong in JDBC URL.

    4. DB server is down.

    5. DB server doesn't accept TCP/IP connections.

    6. DB server has run out of connections.

    7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.



    To solve the one or the other, follow the following advices:



    1. Verify and test them with ping.

    2. Refresh DNS or use IP address in JDBC URL instead.

    3. Verify it based on my.cnf of MySQL DB.

    4. Start the DB.

    5. Verify if mysqld is started without the --skip-networking option.

    6. Restart the DB and fix your code accordingly that it closes connections in finally.

    7. Disable firewall and/or configure firewall/proxy to allow/forward the port.



    Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.



That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.




Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: http://stackoverflow.com/q/9428573/. This is a #1 starters mistake.






share|improve this answer
































    32














    Initialize database constants



    Create constant properties database username, password, URL and drivers, polling limit etc.



    // init database constants
    private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";
    private static final String MAX_POOL = "250"; // set your own limit


    Initialize Connection and Properties



    Once the connection is established, it is better to store for reuse purpose.



    // init connection object
    private Connection connection;
    // init properties object
    private Properties properties;


    Create Properties



    The properties object hold the connection information, check if it is already set.



    // create properties
    private Properties getProperties()
    if (properties == null)
    properties = new Properties();
    properties.setProperty("user", USERNAME);
    properties.setProperty("password", PASSWORD);
    properties.setProperty("MaxPooledStatements", MAX_POOL);

    return properties;



    Connect the Database



    Now connect to database using the constants and properties initialized.



    // connect database
    public Connection connect()
    if (connection == null)
    try
    Class.forName(DATABASE_DRIVER);
    connection = DriverManager.getConnection(DATABASE_URL, getProperties());
    catch (ClassNotFoundException
    return connection;



    Disconnect the database



    Once you are done with database operations, just close the connection.



    // disconnect database
    public void disconnect()
    if (connection != null)
    try
    connection.close();
    connection = null;
    catch (SQLException e)
    e.printStackTrace();





    Everything together



    Use this class MysqlConnect directly after changing database_name, username and password etc.



    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Properties;

    public class MysqlConnect
    // init database constants
    private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";
    private static final String MAX_POOL = "250";

    // init connection object
    private Connection connection;
    // init properties object
    private Properties properties;

    // create properties
    private Properties getProperties()
    if (properties == null)
    properties = new Properties();
    properties.setProperty("user", USERNAME);
    properties.setProperty("password", PASSWORD);
    properties.setProperty("MaxPooledStatements", MAX_POOL);

    return properties;


    // connect database
    public Connection connect()
    if (connection == null)
    try
    Class.forName(DATABASE_DRIVER);
    connection = DriverManager.getConnection(DATABASE_URL, getProperties());
    catch (ClassNotFoundException
    return connection;


    // disconnect database
    public void disconnect()
    if (connection != null)
    try
    connection.close();
    connection = null;
    catch (SQLException e)
    e.printStackTrace();






    How to Use?



    Initialize the database class.



    // !_ note _! this is just init
    // it will not create a connection
    MysqlConnect mysqlConnect = new MysqlConnect();


    Somewhere else in your code ...



    String sql = "SELECT * FROM `stackoverflow`";
    try
    PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
    ... go on ...
    ... go on ...
    ... DONE ....
    catch (SQLException e)
    e.printStackTrace();
    finally
    mysqlConnect.disconnect();



    This is all :) If anything to improve edit it! Hope this is helpful.






    share|improve this answer

























    • Mark, does each class need to maintain it's own separate MysqlConnect instance open at all times - assuming they need to interact wit the data? I'm just wondering how this setup works between classes.

      – Michael Sims
      Nov 19 '17 at 16:42











    • in place of com.mysql.jdbc.Driver this jdbc:mysql://localhost:3306/stocks should be used as the former is deprecated.

      – Chaudhry Waqas
      Oct 23 '18 at 12:20


















    23














    String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
    String user = "username";
    String password = "password";

    // Load the Connector/J driver
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    // Establish connection to MySQL
    Connection conn = DriverManager.getConnection(url, user, password);





    share|improve this answer























    • what is yourdatabase in here? database name?

      – Koray Tugay
      Mar 24 '13 at 0:04











    • newInstance() is not necessary. Is it?

      – Mohamed Ennahdi El Idrissi
      Dec 12 '16 at 16:28


















    13














    Here's the very minimum you need to get data out of a MySQL database:



    Class.forName("com.mysql.jdbc.Driver").newInstance();
    Connection conn = DriverManager.getConnection
    ("jdbc:mysql://localhost:3306/foo", "root", "password");

    Statement stmt = conn.createStatement();
    stmt.execute("SELECT * FROM `FOO.BAR`");
    stmt.close();
    conn.close();


    Add exception handling, configuration etc. to taste.






    share|improve this answer


















    • 2





      why do you need Class.forName(...).newInstance()?

      – Don Cheadle
      Apr 21 '15 at 21:21






    • 2





      @mmcrae You don't, since 2007.

      – user207421
      Feb 13 '17 at 5:39


















    4














    MySQL JDBC Connection with useSSL.



    private String db_server = BaseMethods.getSystemData("db_server");
    private String db_user = BaseMethods.getSystemData("db_user");
    private String db_password = BaseMethods.getSystemData("db_password");

    private String connectToDb() throws Exception
    String jdbcDriver = "com.mysql.jdbc.Driver";
    String dbUrl = "jdbc:mysql://" + db_server +
    "?verifyServerCertificate=false" +
    "&useSSL=true" +
    "&requireSSL=true";
    System.setProperty(jdbcDriver, "");
    Class.forName(jdbcDriver).newInstance();

    Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
    Statement statement = conn.createStatement();
    String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + """ + letterID + """;
    ResultSet resultSet = statement.executeQuery(query);
    resultSet.next();
    return resultSet.getString(1);






    share|improve this answer
































      3














      you need to have mysql connector jar in your classpath.



      in Java JDBC API makes everything with databases. using JDBC we can write Java applications to

      1. Send queries or update SQL to DB(any relational Database)
      2. Retrieve and process the results from DB



      with below three steps we can able to retrieve data from any Database



      Connection con = DriverManager.getConnection(
      "jdbc:myDriver:DatabaseName",
      dBuserName,
      dBuserPassword);

      Statement stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

      while (rs.next())
      int x = rs.getInt("a");
      String s = rs.getString("b");
      float f = rs.getFloat("c");






      share|improve this answer






























        3














        Short and Sweet code.



        try

        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver Loaded");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
        //Database Name - testDB, Username - "root", Password - ""
        System.out.println("Connected...");

        catch(Exception e)

        e.printStackTrace();



        For SQL server 2012



        try

        String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
        //KHILAN is Host and 1433 is port number
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        System.out.println("Driver Loaded");
        conn = DriverManager.getConnection(url);
        System.out.println("Connected...");

        catch(Exception e)

        e.printStackTrace();






        share|improve this answer
































          3














          You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.



          Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA






          share|improve this answer
































            2














            Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly



            Connection con = DriverManager.getConnection(
            "jdbc:myDriver:DatabaseName",
            dBuserName,
            dBuserPassword);
            if (con != null)
            //..handle your code there



            Or something like in that way :)



            Probably there's some case, while getConnection can return null :)






            share|improve this answer






























              0














              MySql JDBC Connection:



              Class.forName("com.mysql.jdbc.Driver"); 

              Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
              Statement stmt=con.createStatement();
              stmt = con.createStatement();
              ResultSet rs=stmt.executeQuery("Select * from Table");





              share|improve this answer






























                0














                Short Code



                public class DB 

                public static Connection c;

                public static Connection getConnection() throws Exception
                if (c == null)
                Class.forName("com.mysql.jdbc.Driver");
                c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");

                return c;


                // Send data TO Database
                public static void setData(String sql) throws Exception
                DB.getConnection().createStatement().executeUpdate(sql);


                // Get Data From Database
                public static ResultSet getData(String sql) throws Exception
                ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
                return rs;







                share|improve this answer
































                  0














                  HOW

                  • To set up the Driver to run a quick sample

                  1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J

                  2. Remember to set the classpath to include the path of the connector jar file.
                  If we don't set it correctly, below errors can occur:

                  No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development

                  java.lang.ClassNotFoundException: com.mysql.jdbc:Driver


                  • To set up the CLASSPATH

                  Method 1: set the CLASSPATH variable.



                  export CLASSPATH=".:mysql-connector-java-VERSION.jar"
                  java MyClassFile


                  In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
                  And it found the Drive class => BOOM errors was gone.



                  Method 2:



                  java -cp .:mysql-connector-java-VERSION.jar MyClassFile


                  Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.



                  Hope this can help someone!






                  share|improve this answer























                    protected by Sean Owen May 23 '12 at 22:07



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?














                    13 Answers
                    13






                    active

                    oldest

                    votes








                    13 Answers
                    13






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    193














                    DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:



                    Context context = new InitialContext();
                    DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");


                    or instantiating and configuring one from your database driver directly:



                    MysqlDataSource dataSource = new MysqlDataSource();
                    dataSource.setUser("scott");
                    dataSource.setPassword("tiger");
                    dataSource.setServerName("myDBHost.example.org");


                    and then obtain connections from it, same as above:



                    Connection conn = dataSource.getConnection();
                    Statement stmt = conn.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
                    ...
                    rs.close();
                    stmt.close();
                    conn.close();





                    share|improve this answer


















                    • 1





                      how come the other examples use com.mysql.jdbc.Driver? is this method better?

                      – Jason S
                      May 21 '10 at 3:21






                    • 7





                      I think this is the old-style Driver class that works with the old-style driver mechanism. MysqlDataSource implements javax.sql.DataSource which is the newer mechanism.

                      – Sean Owen
                      May 21 '10 at 9:00






                    • 1





                      Hi @SeanOwen I wonder that, why do we close rs and stmt? Why not just conn?

                      – Kamuran Sönecek
                      Apr 14 '16 at 6:37






                    • 3





                      Maybe you should add dataSource.setDatabaseName("database").

                      – Myoch
                      May 22 '16 at 11:14







                    • 1





                      It's good practice to close() things explicitly, though it is more code. Any good implementation would have to close the resources when the connection closes, yes. Consider other contexts where you want to reuse a statement or connection though. In Java 7's try-with-resources, you get this behavior for free anyway:

                      – Sean Owen
                      May 29 '16 at 13:22















                    193














                    DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:



                    Context context = new InitialContext();
                    DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");


                    or instantiating and configuring one from your database driver directly:



                    MysqlDataSource dataSource = new MysqlDataSource();
                    dataSource.setUser("scott");
                    dataSource.setPassword("tiger");
                    dataSource.setServerName("myDBHost.example.org");


                    and then obtain connections from it, same as above:



                    Connection conn = dataSource.getConnection();
                    Statement stmt = conn.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
                    ...
                    rs.close();
                    stmt.close();
                    conn.close();





                    share|improve this answer


















                    • 1





                      how come the other examples use com.mysql.jdbc.Driver? is this method better?

                      – Jason S
                      May 21 '10 at 3:21






                    • 7





                      I think this is the old-style Driver class that works with the old-style driver mechanism. MysqlDataSource implements javax.sql.DataSource which is the newer mechanism.

                      – Sean Owen
                      May 21 '10 at 9:00






                    • 1





                      Hi @SeanOwen I wonder that, why do we close rs and stmt? Why not just conn?

                      – Kamuran Sönecek
                      Apr 14 '16 at 6:37






                    • 3





                      Maybe you should add dataSource.setDatabaseName("database").

                      – Myoch
                      May 22 '16 at 11:14







                    • 1





                      It's good practice to close() things explicitly, though it is more code. Any good implementation would have to close the resources when the connection closes, yes. Consider other contexts where you want to reuse a statement or connection though. In Java 7's try-with-resources, you get this behavior for free anyway:

                      – Sean Owen
                      May 29 '16 at 13:22













                    193












                    193








                    193







                    DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:



                    Context context = new InitialContext();
                    DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");


                    or instantiating and configuring one from your database driver directly:



                    MysqlDataSource dataSource = new MysqlDataSource();
                    dataSource.setUser("scott");
                    dataSource.setPassword("tiger");
                    dataSource.setServerName("myDBHost.example.org");


                    and then obtain connections from it, same as above:



                    Connection conn = dataSource.getConnection();
                    Statement stmt = conn.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
                    ...
                    rs.close();
                    stmt.close();
                    conn.close();





                    share|improve this answer













                    DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:



                    Context context = new InitialContext();
                    DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");


                    or instantiating and configuring one from your database driver directly:



                    MysqlDataSource dataSource = new MysqlDataSource();
                    dataSource.setUser("scott");
                    dataSource.setPassword("tiger");
                    dataSource.setServerName("myDBHost.example.org");


                    and then obtain connections from it, same as above:



                    Connection conn = dataSource.getConnection();
                    Statement stmt = conn.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
                    ...
                    rs.close();
                    stmt.close();
                    conn.close();






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered May 15 '10 at 9:10









                    Sean OwenSean Owen

                    58.7k18125159




                    58.7k18125159







                    • 1





                      how come the other examples use com.mysql.jdbc.Driver? is this method better?

                      – Jason S
                      May 21 '10 at 3:21






                    • 7





                      I think this is the old-style Driver class that works with the old-style driver mechanism. MysqlDataSource implements javax.sql.DataSource which is the newer mechanism.

                      – Sean Owen
                      May 21 '10 at 9:00






                    • 1





                      Hi @SeanOwen I wonder that, why do we close rs and stmt? Why not just conn?

                      – Kamuran Sönecek
                      Apr 14 '16 at 6:37






                    • 3





                      Maybe you should add dataSource.setDatabaseName("database").

                      – Myoch
                      May 22 '16 at 11:14







                    • 1





                      It's good practice to close() things explicitly, though it is more code. Any good implementation would have to close the resources when the connection closes, yes. Consider other contexts where you want to reuse a statement or connection though. In Java 7's try-with-resources, you get this behavior for free anyway:

                      – Sean Owen
                      May 29 '16 at 13:22












                    • 1





                      how come the other examples use com.mysql.jdbc.Driver? is this method better?

                      – Jason S
                      May 21 '10 at 3:21






                    • 7





                      I think this is the old-style Driver class that works with the old-style driver mechanism. MysqlDataSource implements javax.sql.DataSource which is the newer mechanism.

                      – Sean Owen
                      May 21 '10 at 9:00






                    • 1





                      Hi @SeanOwen I wonder that, why do we close rs and stmt? Why not just conn?

                      – Kamuran Sönecek
                      Apr 14 '16 at 6:37






                    • 3





                      Maybe you should add dataSource.setDatabaseName("database").

                      – Myoch
                      May 22 '16 at 11:14







                    • 1





                      It's good practice to close() things explicitly, though it is more code. Any good implementation would have to close the resources when the connection closes, yes. Consider other contexts where you want to reuse a statement or connection though. In Java 7's try-with-resources, you get this behavior for free anyway:

                      – Sean Owen
                      May 29 '16 at 13:22







                    1




                    1





                    how come the other examples use com.mysql.jdbc.Driver? is this method better?

                    – Jason S
                    May 21 '10 at 3:21





                    how come the other examples use com.mysql.jdbc.Driver? is this method better?

                    – Jason S
                    May 21 '10 at 3:21




                    7




                    7





                    I think this is the old-style Driver class that works with the old-style driver mechanism. MysqlDataSource implements javax.sql.DataSource which is the newer mechanism.

                    – Sean Owen
                    May 21 '10 at 9:00





                    I think this is the old-style Driver class that works with the old-style driver mechanism. MysqlDataSource implements javax.sql.DataSource which is the newer mechanism.

                    – Sean Owen
                    May 21 '10 at 9:00




                    1




                    1





                    Hi @SeanOwen I wonder that, why do we close rs and stmt? Why not just conn?

                    – Kamuran Sönecek
                    Apr 14 '16 at 6:37





                    Hi @SeanOwen I wonder that, why do we close rs and stmt? Why not just conn?

                    – Kamuran Sönecek
                    Apr 14 '16 at 6:37




                    3




                    3





                    Maybe you should add dataSource.setDatabaseName("database").

                    – Myoch
                    May 22 '16 at 11:14






                    Maybe you should add dataSource.setDatabaseName("database").

                    – Myoch
                    May 22 '16 at 11:14





                    1




                    1





                    It's good practice to close() things explicitly, though it is more code. Any good implementation would have to close the resources when the connection closes, yes. Consider other contexts where you want to reuse a statement or connection though. In Java 7's try-with-resources, you get this behavior for free anyway:

                    – Sean Owen
                    May 29 '16 at 13:22





                    It's good practice to close() things explicitly, though it is more code. Any good implementation would have to close the resources when the connection closes, yes. Consider other contexts where you want to reuse a statement or connection though. In Java 7's try-with-resources, you get this behavior for free anyway:

                    – Sean Owen
                    May 29 '16 at 13:22













                    439














                    Here's a step by step explanation how to install MySQL and JDBC and how to use it:



                    1. Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.



                    2. Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).



                      If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.



                      If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.



                      java -cp .;/path/to/mysql-connector.jar com.example.YourClass


                      The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.




                    3. Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.



                      CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;



                    4. Create an user for Java and grant it access. Simply because using root is a bad practice.



                      CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
                      GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';


                      Yes, java is the username and password is the password here.




                    5. Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:



                      jdbc:mysql://hostname:port/databasename


                      • hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.


                      • port: The TCP/IP port where MySQL server listens on. This is by default 3306.


                      • databasename: The name of the database you'd like to connect to. That's javabase.


                      So the final URL should look like:



                      jdbc:mysql://localhost:3306/javabase



                    6. Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.



                      String url = "jdbc:mysql://localhost:3306/javabase";
                      String username = "java";
                      String password = "password";

                      System.out.println("Connecting database...");

                      try (Connection connection = DriverManager.getConnection(url, username, password))
                      System.out.println("Database connected!");
                      catch (SQLException e)
                      throw new IllegalStateException("Cannot connect the database!", e);



                      If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:



                      System.out.println("Loading driver...");

                      try
                      Class.forName("com.mysql.jdbc.Driver");
                      System.out.println("Driver loaded!");
                      catch (ClassNotFoundException e)
                      throw new IllegalStateException("Cannot find the driver in the classpath!", e);



                      Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.



                      Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.



                      If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
                      Communications link failure
                      , then it means that the DB isn't reachable at all. This can have one or more of the following causes:



                      1. IP address or hostname in JDBC URL is wrong.

                      2. Hostname in JDBC URL is not recognized by local DNS server.

                      3. Port number is missing or wrong in JDBC URL.

                      4. DB server is down.

                      5. DB server doesn't accept TCP/IP connections.

                      6. DB server has run out of connections.

                      7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.



                      To solve the one or the other, follow the following advices:



                      1. Verify and test them with ping.

                      2. Refresh DNS or use IP address in JDBC URL instead.

                      3. Verify it based on my.cnf of MySQL DB.

                      4. Start the DB.

                      5. Verify if mysqld is started without the --skip-networking option.

                      6. Restart the DB and fix your code accordingly that it closes connections in finally.

                      7. Disable firewall and/or configure firewall/proxy to allow/forward the port.



                      Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.



                    That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.




                    Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: http://stackoverflow.com/q/9428573/. This is a #1 starters mistake.






                    share|improve this answer





























                      439














                      Here's a step by step explanation how to install MySQL and JDBC and how to use it:



                      1. Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.



                      2. Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).



                        If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.



                        If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.



                        java -cp .;/path/to/mysql-connector.jar com.example.YourClass


                        The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.




                      3. Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.



                        CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;



                      4. Create an user for Java and grant it access. Simply because using root is a bad practice.



                        CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
                        GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';


                        Yes, java is the username and password is the password here.




                      5. Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:



                        jdbc:mysql://hostname:port/databasename


                        • hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.


                        • port: The TCP/IP port where MySQL server listens on. This is by default 3306.


                        • databasename: The name of the database you'd like to connect to. That's javabase.


                        So the final URL should look like:



                        jdbc:mysql://localhost:3306/javabase



                      6. Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.



                        String url = "jdbc:mysql://localhost:3306/javabase";
                        String username = "java";
                        String password = "password";

                        System.out.println("Connecting database...");

                        try (Connection connection = DriverManager.getConnection(url, username, password))
                        System.out.println("Database connected!");
                        catch (SQLException e)
                        throw new IllegalStateException("Cannot connect the database!", e);



                        If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:



                        System.out.println("Loading driver...");

                        try
                        Class.forName("com.mysql.jdbc.Driver");
                        System.out.println("Driver loaded!");
                        catch (ClassNotFoundException e)
                        throw new IllegalStateException("Cannot find the driver in the classpath!", e);



                        Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.



                        Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.



                        If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
                        Communications link failure
                        , then it means that the DB isn't reachable at all. This can have one or more of the following causes:



                        1. IP address or hostname in JDBC URL is wrong.

                        2. Hostname in JDBC URL is not recognized by local DNS server.

                        3. Port number is missing or wrong in JDBC URL.

                        4. DB server is down.

                        5. DB server doesn't accept TCP/IP connections.

                        6. DB server has run out of connections.

                        7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.



                        To solve the one or the other, follow the following advices:



                        1. Verify and test them with ping.

                        2. Refresh DNS or use IP address in JDBC URL instead.

                        3. Verify it based on my.cnf of MySQL DB.

                        4. Start the DB.

                        5. Verify if mysqld is started without the --skip-networking option.

                        6. Restart the DB and fix your code accordingly that it closes connections in finally.

                        7. Disable firewall and/or configure firewall/proxy to allow/forward the port.



                        Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.



                      That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.




                      Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: http://stackoverflow.com/q/9428573/. This is a #1 starters mistake.






                      share|improve this answer



























                        439












                        439








                        439







                        Here's a step by step explanation how to install MySQL and JDBC and how to use it:



                        1. Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.



                        2. Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).



                          If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.



                          If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.



                          java -cp .;/path/to/mysql-connector.jar com.example.YourClass


                          The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.




                        3. Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.



                          CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;



                        4. Create an user for Java and grant it access. Simply because using root is a bad practice.



                          CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
                          GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';


                          Yes, java is the username and password is the password here.




                        5. Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:



                          jdbc:mysql://hostname:port/databasename


                          • hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.


                          • port: The TCP/IP port where MySQL server listens on. This is by default 3306.


                          • databasename: The name of the database you'd like to connect to. That's javabase.


                          So the final URL should look like:



                          jdbc:mysql://localhost:3306/javabase



                        6. Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.



                          String url = "jdbc:mysql://localhost:3306/javabase";
                          String username = "java";
                          String password = "password";

                          System.out.println("Connecting database...");

                          try (Connection connection = DriverManager.getConnection(url, username, password))
                          System.out.println("Database connected!");
                          catch (SQLException e)
                          throw new IllegalStateException("Cannot connect the database!", e);



                          If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:



                          System.out.println("Loading driver...");

                          try
                          Class.forName("com.mysql.jdbc.Driver");
                          System.out.println("Driver loaded!");
                          catch (ClassNotFoundException e)
                          throw new IllegalStateException("Cannot find the driver in the classpath!", e);



                          Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.



                          Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.



                          If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
                          Communications link failure
                          , then it means that the DB isn't reachable at all. This can have one or more of the following causes:



                          1. IP address or hostname in JDBC URL is wrong.

                          2. Hostname in JDBC URL is not recognized by local DNS server.

                          3. Port number is missing or wrong in JDBC URL.

                          4. DB server is down.

                          5. DB server doesn't accept TCP/IP connections.

                          6. DB server has run out of connections.

                          7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.



                          To solve the one or the other, follow the following advices:



                          1. Verify and test them with ping.

                          2. Refresh DNS or use IP address in JDBC URL instead.

                          3. Verify it based on my.cnf of MySQL DB.

                          4. Start the DB.

                          5. Verify if mysqld is started without the --skip-networking option.

                          6. Restart the DB and fix your code accordingly that it closes connections in finally.

                          7. Disable firewall and/or configure firewall/proxy to allow/forward the port.



                          Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.



                        That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.




                        Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: http://stackoverflow.com/q/9428573/. This is a #1 starters mistake.






                        share|improve this answer















                        Here's a step by step explanation how to install MySQL and JDBC and how to use it:



                        1. Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.



                        2. Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).



                          If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.



                          If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.



                          java -cp .;/path/to/mysql-connector.jar com.example.YourClass


                          The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.




                        3. Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.



                          CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;



                        4. Create an user for Java and grant it access. Simply because using root is a bad practice.



                          CREATE USER 'java'@'localhost' IDENTIFIED BY 'password';
                          GRANT ALL ON javabase.* TO 'java'@'localhost' IDENTIFIED BY 'password';


                          Yes, java is the username and password is the password here.




                        5. Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:



                          jdbc:mysql://hostname:port/databasename


                          • hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.


                          • port: The TCP/IP port where MySQL server listens on. This is by default 3306.


                          • databasename: The name of the database you'd like to connect to. That's javabase.


                          So the final URL should look like:



                          jdbc:mysql://localhost:3306/javabase



                        6. Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.



                          String url = "jdbc:mysql://localhost:3306/javabase";
                          String username = "java";
                          String password = "password";

                          System.out.println("Connecting database...");

                          try (Connection connection = DriverManager.getConnection(url, username, password))
                          System.out.println("Database connected!");
                          catch (SQLException e)
                          throw new IllegalStateException("Cannot connect the database!", e);



                          If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:



                          System.out.println("Loading driver...");

                          try
                          Class.forName("com.mysql.jdbc.Driver");
                          System.out.println("Driver loaded!");
                          catch (ClassNotFoundException e)
                          throw new IllegalStateException("Cannot find the driver in the classpath!", e);



                          Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.



                          Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.



                          If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
                          Communications link failure
                          , then it means that the DB isn't reachable at all. This can have one or more of the following causes:



                          1. IP address or hostname in JDBC URL is wrong.

                          2. Hostname in JDBC URL is not recognized by local DNS server.

                          3. Port number is missing or wrong in JDBC URL.

                          4. DB server is down.

                          5. DB server doesn't accept TCP/IP connections.

                          6. DB server has run out of connections.

                          7. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.



                          To solve the one or the other, follow the following advices:



                          1. Verify and test them with ping.

                          2. Refresh DNS or use IP address in JDBC URL instead.

                          3. Verify it based on my.cnf of MySQL DB.

                          4. Start the DB.

                          5. Verify if mysqld is started without the --skip-networking option.

                          6. Restart the DB and fix your code accordingly that it closes connections in finally.

                          7. Disable firewall and/or configure firewall/proxy to allow/forward the port.



                          Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.



                        That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.




                        Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: http://stackoverflow.com/q/9428573/. This is a #1 starters mistake.







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jun 29 '17 at 0:45









                        Aaron Hall

                        188k53312265




                        188k53312265










                        answered May 15 '10 at 13:55









                        BalusCBalusC

                        865k30631983251




                        865k30631983251





















                            32














                            Initialize database constants



                            Create constant properties database username, password, URL and drivers, polling limit etc.



                            // init database constants
                            private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
                            private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
                            private static final String USERNAME = "root";
                            private static final String PASSWORD = "";
                            private static final String MAX_POOL = "250"; // set your own limit


                            Initialize Connection and Properties



                            Once the connection is established, it is better to store for reuse purpose.



                            // init connection object
                            private Connection connection;
                            // init properties object
                            private Properties properties;


                            Create Properties



                            The properties object hold the connection information, check if it is already set.



                            // create properties
                            private Properties getProperties()
                            if (properties == null)
                            properties = new Properties();
                            properties.setProperty("user", USERNAME);
                            properties.setProperty("password", PASSWORD);
                            properties.setProperty("MaxPooledStatements", MAX_POOL);

                            return properties;



                            Connect the Database



                            Now connect to database using the constants and properties initialized.



                            // connect database
                            public Connection connect()
                            if (connection == null)
                            try
                            Class.forName(DATABASE_DRIVER);
                            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                            catch (ClassNotFoundException
                            return connection;



                            Disconnect the database



                            Once you are done with database operations, just close the connection.



                            // disconnect database
                            public void disconnect()
                            if (connection != null)
                            try
                            connection.close();
                            connection = null;
                            catch (SQLException e)
                            e.printStackTrace();





                            Everything together



                            Use this class MysqlConnect directly after changing database_name, username and password etc.



                            import java.sql.Connection;
                            import java.sql.DriverManager;
                            import java.sql.SQLException;
                            import java.util.Properties;

                            public class MysqlConnect
                            // init database constants
                            private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
                            private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
                            private static final String USERNAME = "root";
                            private static final String PASSWORD = "";
                            private static final String MAX_POOL = "250";

                            // init connection object
                            private Connection connection;
                            // init properties object
                            private Properties properties;

                            // create properties
                            private Properties getProperties()
                            if (properties == null)
                            properties = new Properties();
                            properties.setProperty("user", USERNAME);
                            properties.setProperty("password", PASSWORD);
                            properties.setProperty("MaxPooledStatements", MAX_POOL);

                            return properties;


                            // connect database
                            public Connection connect()
                            if (connection == null)
                            try
                            Class.forName(DATABASE_DRIVER);
                            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                            catch (ClassNotFoundException
                            return connection;


                            // disconnect database
                            public void disconnect()
                            if (connection != null)
                            try
                            connection.close();
                            connection = null;
                            catch (SQLException e)
                            e.printStackTrace();






                            How to Use?



                            Initialize the database class.



                            // !_ note _! this is just init
                            // it will not create a connection
                            MysqlConnect mysqlConnect = new MysqlConnect();


                            Somewhere else in your code ...



                            String sql = "SELECT * FROM `stackoverflow`";
                            try
                            PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
                            ... go on ...
                            ... go on ...
                            ... DONE ....
                            catch (SQLException e)
                            e.printStackTrace();
                            finally
                            mysqlConnect.disconnect();



                            This is all :) If anything to improve edit it! Hope this is helpful.






                            share|improve this answer

























                            • Mark, does each class need to maintain it's own separate MysqlConnect instance open at all times - assuming they need to interact wit the data? I'm just wondering how this setup works between classes.

                              – Michael Sims
                              Nov 19 '17 at 16:42











                            • in place of com.mysql.jdbc.Driver this jdbc:mysql://localhost:3306/stocks should be used as the former is deprecated.

                              – Chaudhry Waqas
                              Oct 23 '18 at 12:20















                            32














                            Initialize database constants



                            Create constant properties database username, password, URL and drivers, polling limit etc.



                            // init database constants
                            private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
                            private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
                            private static final String USERNAME = "root";
                            private static final String PASSWORD = "";
                            private static final String MAX_POOL = "250"; // set your own limit


                            Initialize Connection and Properties



                            Once the connection is established, it is better to store for reuse purpose.



                            // init connection object
                            private Connection connection;
                            // init properties object
                            private Properties properties;


                            Create Properties



                            The properties object hold the connection information, check if it is already set.



                            // create properties
                            private Properties getProperties()
                            if (properties == null)
                            properties = new Properties();
                            properties.setProperty("user", USERNAME);
                            properties.setProperty("password", PASSWORD);
                            properties.setProperty("MaxPooledStatements", MAX_POOL);

                            return properties;



                            Connect the Database



                            Now connect to database using the constants and properties initialized.



                            // connect database
                            public Connection connect()
                            if (connection == null)
                            try
                            Class.forName(DATABASE_DRIVER);
                            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                            catch (ClassNotFoundException
                            return connection;



                            Disconnect the database



                            Once you are done with database operations, just close the connection.



                            // disconnect database
                            public void disconnect()
                            if (connection != null)
                            try
                            connection.close();
                            connection = null;
                            catch (SQLException e)
                            e.printStackTrace();





                            Everything together



                            Use this class MysqlConnect directly after changing database_name, username and password etc.



                            import java.sql.Connection;
                            import java.sql.DriverManager;
                            import java.sql.SQLException;
                            import java.util.Properties;

                            public class MysqlConnect
                            // init database constants
                            private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
                            private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
                            private static final String USERNAME = "root";
                            private static final String PASSWORD = "";
                            private static final String MAX_POOL = "250";

                            // init connection object
                            private Connection connection;
                            // init properties object
                            private Properties properties;

                            // create properties
                            private Properties getProperties()
                            if (properties == null)
                            properties = new Properties();
                            properties.setProperty("user", USERNAME);
                            properties.setProperty("password", PASSWORD);
                            properties.setProperty("MaxPooledStatements", MAX_POOL);

                            return properties;


                            // connect database
                            public Connection connect()
                            if (connection == null)
                            try
                            Class.forName(DATABASE_DRIVER);
                            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                            catch (ClassNotFoundException
                            return connection;


                            // disconnect database
                            public void disconnect()
                            if (connection != null)
                            try
                            connection.close();
                            connection = null;
                            catch (SQLException e)
                            e.printStackTrace();






                            How to Use?



                            Initialize the database class.



                            // !_ note _! this is just init
                            // it will not create a connection
                            MysqlConnect mysqlConnect = new MysqlConnect();


                            Somewhere else in your code ...



                            String sql = "SELECT * FROM `stackoverflow`";
                            try
                            PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
                            ... go on ...
                            ... go on ...
                            ... DONE ....
                            catch (SQLException e)
                            e.printStackTrace();
                            finally
                            mysqlConnect.disconnect();



                            This is all :) If anything to improve edit it! Hope this is helpful.






                            share|improve this answer

























                            • Mark, does each class need to maintain it's own separate MysqlConnect instance open at all times - assuming they need to interact wit the data? I'm just wondering how this setup works between classes.

                              – Michael Sims
                              Nov 19 '17 at 16:42











                            • in place of com.mysql.jdbc.Driver this jdbc:mysql://localhost:3306/stocks should be used as the former is deprecated.

                              – Chaudhry Waqas
                              Oct 23 '18 at 12:20













                            32












                            32








                            32







                            Initialize database constants



                            Create constant properties database username, password, URL and drivers, polling limit etc.



                            // init database constants
                            private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
                            private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
                            private static final String USERNAME = "root";
                            private static final String PASSWORD = "";
                            private static final String MAX_POOL = "250"; // set your own limit


                            Initialize Connection and Properties



                            Once the connection is established, it is better to store for reuse purpose.



                            // init connection object
                            private Connection connection;
                            // init properties object
                            private Properties properties;


                            Create Properties



                            The properties object hold the connection information, check if it is already set.



                            // create properties
                            private Properties getProperties()
                            if (properties == null)
                            properties = new Properties();
                            properties.setProperty("user", USERNAME);
                            properties.setProperty("password", PASSWORD);
                            properties.setProperty("MaxPooledStatements", MAX_POOL);

                            return properties;



                            Connect the Database



                            Now connect to database using the constants and properties initialized.



                            // connect database
                            public Connection connect()
                            if (connection == null)
                            try
                            Class.forName(DATABASE_DRIVER);
                            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                            catch (ClassNotFoundException
                            return connection;



                            Disconnect the database



                            Once you are done with database operations, just close the connection.



                            // disconnect database
                            public void disconnect()
                            if (connection != null)
                            try
                            connection.close();
                            connection = null;
                            catch (SQLException e)
                            e.printStackTrace();





                            Everything together



                            Use this class MysqlConnect directly after changing database_name, username and password etc.



                            import java.sql.Connection;
                            import java.sql.DriverManager;
                            import java.sql.SQLException;
                            import java.util.Properties;

                            public class MysqlConnect
                            // init database constants
                            private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
                            private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
                            private static final String USERNAME = "root";
                            private static final String PASSWORD = "";
                            private static final String MAX_POOL = "250";

                            // init connection object
                            private Connection connection;
                            // init properties object
                            private Properties properties;

                            // create properties
                            private Properties getProperties()
                            if (properties == null)
                            properties = new Properties();
                            properties.setProperty("user", USERNAME);
                            properties.setProperty("password", PASSWORD);
                            properties.setProperty("MaxPooledStatements", MAX_POOL);

                            return properties;


                            // connect database
                            public Connection connect()
                            if (connection == null)
                            try
                            Class.forName(DATABASE_DRIVER);
                            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                            catch (ClassNotFoundException
                            return connection;


                            // disconnect database
                            public void disconnect()
                            if (connection != null)
                            try
                            connection.close();
                            connection = null;
                            catch (SQLException e)
                            e.printStackTrace();






                            How to Use?



                            Initialize the database class.



                            // !_ note _! this is just init
                            // it will not create a connection
                            MysqlConnect mysqlConnect = new MysqlConnect();


                            Somewhere else in your code ...



                            String sql = "SELECT * FROM `stackoverflow`";
                            try
                            PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
                            ... go on ...
                            ... go on ...
                            ... DONE ....
                            catch (SQLException e)
                            e.printStackTrace();
                            finally
                            mysqlConnect.disconnect();



                            This is all :) If anything to improve edit it! Hope this is helpful.






                            share|improve this answer















                            Initialize database constants



                            Create constant properties database username, password, URL and drivers, polling limit etc.



                            // init database constants
                            private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
                            private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
                            private static final String USERNAME = "root";
                            private static final String PASSWORD = "";
                            private static final String MAX_POOL = "250"; // set your own limit


                            Initialize Connection and Properties



                            Once the connection is established, it is better to store for reuse purpose.



                            // init connection object
                            private Connection connection;
                            // init properties object
                            private Properties properties;


                            Create Properties



                            The properties object hold the connection information, check if it is already set.



                            // create properties
                            private Properties getProperties()
                            if (properties == null)
                            properties = new Properties();
                            properties.setProperty("user", USERNAME);
                            properties.setProperty("password", PASSWORD);
                            properties.setProperty("MaxPooledStatements", MAX_POOL);

                            return properties;



                            Connect the Database



                            Now connect to database using the constants and properties initialized.



                            // connect database
                            public Connection connect()
                            if (connection == null)
                            try
                            Class.forName(DATABASE_DRIVER);
                            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                            catch (ClassNotFoundException
                            return connection;



                            Disconnect the database



                            Once you are done with database operations, just close the connection.



                            // disconnect database
                            public void disconnect()
                            if (connection != null)
                            try
                            connection.close();
                            connection = null;
                            catch (SQLException e)
                            e.printStackTrace();





                            Everything together



                            Use this class MysqlConnect directly after changing database_name, username and password etc.



                            import java.sql.Connection;
                            import java.sql.DriverManager;
                            import java.sql.SQLException;
                            import java.util.Properties;

                            public class MysqlConnect
                            // init database constants
                            private static final String DATABASE_DRIVER = "com.mysql.jdbc.Driver";
                            private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
                            private static final String USERNAME = "root";
                            private static final String PASSWORD = "";
                            private static final String MAX_POOL = "250";

                            // init connection object
                            private Connection connection;
                            // init properties object
                            private Properties properties;

                            // create properties
                            private Properties getProperties()
                            if (properties == null)
                            properties = new Properties();
                            properties.setProperty("user", USERNAME);
                            properties.setProperty("password", PASSWORD);
                            properties.setProperty("MaxPooledStatements", MAX_POOL);

                            return properties;


                            // connect database
                            public Connection connect()
                            if (connection == null)
                            try
                            Class.forName(DATABASE_DRIVER);
                            connection = DriverManager.getConnection(DATABASE_URL, getProperties());
                            catch (ClassNotFoundException
                            return connection;


                            // disconnect database
                            public void disconnect()
                            if (connection != null)
                            try
                            connection.close();
                            connection = null;
                            catch (SQLException e)
                            e.printStackTrace();






                            How to Use?



                            Initialize the database class.



                            // !_ note _! this is just init
                            // it will not create a connection
                            MysqlConnect mysqlConnect = new MysqlConnect();


                            Somewhere else in your code ...



                            String sql = "SELECT * FROM `stackoverflow`";
                            try
                            PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
                            ... go on ...
                            ... go on ...
                            ... DONE ....
                            catch (SQLException e)
                            e.printStackTrace();
                            finally
                            mysqlConnect.disconnect();



                            This is all :) If anything to improve edit it! Hope this is helpful.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Sep 23 '18 at 7:25









                            Mark Rotteveel

                            62.7k1479124




                            62.7k1479124










                            answered Jun 14 '15 at 5:15









                            Madan SapkotaMadan Sapkota

                            16.9k784100




                            16.9k784100












                            • Mark, does each class need to maintain it's own separate MysqlConnect instance open at all times - assuming they need to interact wit the data? I'm just wondering how this setup works between classes.

                              – Michael Sims
                              Nov 19 '17 at 16:42











                            • in place of com.mysql.jdbc.Driver this jdbc:mysql://localhost:3306/stocks should be used as the former is deprecated.

                              – Chaudhry Waqas
                              Oct 23 '18 at 12:20

















                            • Mark, does each class need to maintain it's own separate MysqlConnect instance open at all times - assuming they need to interact wit the data? I'm just wondering how this setup works between classes.

                              – Michael Sims
                              Nov 19 '17 at 16:42











                            • in place of com.mysql.jdbc.Driver this jdbc:mysql://localhost:3306/stocks should be used as the former is deprecated.

                              – Chaudhry Waqas
                              Oct 23 '18 at 12:20
















                            Mark, does each class need to maintain it's own separate MysqlConnect instance open at all times - assuming they need to interact wit the data? I'm just wondering how this setup works between classes.

                            – Michael Sims
                            Nov 19 '17 at 16:42





                            Mark, does each class need to maintain it's own separate MysqlConnect instance open at all times - assuming they need to interact wit the data? I'm just wondering how this setup works between classes.

                            – Michael Sims
                            Nov 19 '17 at 16:42













                            in place of com.mysql.jdbc.Driver this jdbc:mysql://localhost:3306/stocks should be used as the former is deprecated.

                            – Chaudhry Waqas
                            Oct 23 '18 at 12:20





                            in place of com.mysql.jdbc.Driver this jdbc:mysql://localhost:3306/stocks should be used as the former is deprecated.

                            – Chaudhry Waqas
                            Oct 23 '18 at 12:20











                            23














                            String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
                            String user = "username";
                            String password = "password";

                            // Load the Connector/J driver
                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            // Establish connection to MySQL
                            Connection conn = DriverManager.getConnection(url, user, password);





                            share|improve this answer























                            • what is yourdatabase in here? database name?

                              – Koray Tugay
                              Mar 24 '13 at 0:04











                            • newInstance() is not necessary. Is it?

                              – Mohamed Ennahdi El Idrissi
                              Dec 12 '16 at 16:28















                            23














                            String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
                            String user = "username";
                            String password = "password";

                            // Load the Connector/J driver
                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            // Establish connection to MySQL
                            Connection conn = DriverManager.getConnection(url, user, password);





                            share|improve this answer























                            • what is yourdatabase in here? database name?

                              – Koray Tugay
                              Mar 24 '13 at 0:04











                            • newInstance() is not necessary. Is it?

                              – Mohamed Ennahdi El Idrissi
                              Dec 12 '16 at 16:28













                            23












                            23








                            23







                            String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
                            String user = "username";
                            String password = "password";

                            // Load the Connector/J driver
                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            // Establish connection to MySQL
                            Connection conn = DriverManager.getConnection(url, user, password);





                            share|improve this answer













                            String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
                            String user = "username";
                            String password = "password";

                            // Load the Connector/J driver
                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            // Establish connection to MySQL
                            Connection conn = DriverManager.getConnection(url, user, password);






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 15 '10 at 7:43









                            heffaklumpheffaklump

                            82031126




                            82031126












                            • what is yourdatabase in here? database name?

                              – Koray Tugay
                              Mar 24 '13 at 0:04











                            • newInstance() is not necessary. Is it?

                              – Mohamed Ennahdi El Idrissi
                              Dec 12 '16 at 16:28

















                            • what is yourdatabase in here? database name?

                              – Koray Tugay
                              Mar 24 '13 at 0:04











                            • newInstance() is not necessary. Is it?

                              – Mohamed Ennahdi El Idrissi
                              Dec 12 '16 at 16:28
















                            what is yourdatabase in here? database name?

                            – Koray Tugay
                            Mar 24 '13 at 0:04





                            what is yourdatabase in here? database name?

                            – Koray Tugay
                            Mar 24 '13 at 0:04













                            newInstance() is not necessary. Is it?

                            – Mohamed Ennahdi El Idrissi
                            Dec 12 '16 at 16:28





                            newInstance() is not necessary. Is it?

                            – Mohamed Ennahdi El Idrissi
                            Dec 12 '16 at 16:28











                            13














                            Here's the very minimum you need to get data out of a MySQL database:



                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            Connection conn = DriverManager.getConnection
                            ("jdbc:mysql://localhost:3306/foo", "root", "password");

                            Statement stmt = conn.createStatement();
                            stmt.execute("SELECT * FROM `FOO.BAR`");
                            stmt.close();
                            conn.close();


                            Add exception handling, configuration etc. to taste.






                            share|improve this answer


















                            • 2





                              why do you need Class.forName(...).newInstance()?

                              – Don Cheadle
                              Apr 21 '15 at 21:21






                            • 2





                              @mmcrae You don't, since 2007.

                              – user207421
                              Feb 13 '17 at 5:39















                            13














                            Here's the very minimum you need to get data out of a MySQL database:



                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            Connection conn = DriverManager.getConnection
                            ("jdbc:mysql://localhost:3306/foo", "root", "password");

                            Statement stmt = conn.createStatement();
                            stmt.execute("SELECT * FROM `FOO.BAR`");
                            stmt.close();
                            conn.close();


                            Add exception handling, configuration etc. to taste.






                            share|improve this answer


















                            • 2





                              why do you need Class.forName(...).newInstance()?

                              – Don Cheadle
                              Apr 21 '15 at 21:21






                            • 2





                              @mmcrae You don't, since 2007.

                              – user207421
                              Feb 13 '17 at 5:39













                            13












                            13








                            13







                            Here's the very minimum you need to get data out of a MySQL database:



                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            Connection conn = DriverManager.getConnection
                            ("jdbc:mysql://localhost:3306/foo", "root", "password");

                            Statement stmt = conn.createStatement();
                            stmt.execute("SELECT * FROM `FOO.BAR`");
                            stmt.close();
                            conn.close();


                            Add exception handling, configuration etc. to taste.






                            share|improve this answer













                            Here's the very minimum you need to get data out of a MySQL database:



                            Class.forName("com.mysql.jdbc.Driver").newInstance();
                            Connection conn = DriverManager.getConnection
                            ("jdbc:mysql://localhost:3306/foo", "root", "password");

                            Statement stmt = conn.createStatement();
                            stmt.execute("SELECT * FROM `FOO.BAR`");
                            stmt.close();
                            conn.close();


                            Add exception handling, configuration etc. to taste.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 15 '10 at 7:48









                            Kilian FothKilian Foth

                            12k32947




                            12k32947







                            • 2





                              why do you need Class.forName(...).newInstance()?

                              – Don Cheadle
                              Apr 21 '15 at 21:21






                            • 2





                              @mmcrae You don't, since 2007.

                              – user207421
                              Feb 13 '17 at 5:39












                            • 2





                              why do you need Class.forName(...).newInstance()?

                              – Don Cheadle
                              Apr 21 '15 at 21:21






                            • 2





                              @mmcrae You don't, since 2007.

                              – user207421
                              Feb 13 '17 at 5:39







                            2




                            2





                            why do you need Class.forName(...).newInstance()?

                            – Don Cheadle
                            Apr 21 '15 at 21:21





                            why do you need Class.forName(...).newInstance()?

                            – Don Cheadle
                            Apr 21 '15 at 21:21




                            2




                            2





                            @mmcrae You don't, since 2007.

                            – user207421
                            Feb 13 '17 at 5:39





                            @mmcrae You don't, since 2007.

                            – user207421
                            Feb 13 '17 at 5:39











                            4














                            MySQL JDBC Connection with useSSL.



                            private String db_server = BaseMethods.getSystemData("db_server");
                            private String db_user = BaseMethods.getSystemData("db_user");
                            private String db_password = BaseMethods.getSystemData("db_password");

                            private String connectToDb() throws Exception
                            String jdbcDriver = "com.mysql.jdbc.Driver";
                            String dbUrl = "jdbc:mysql://" + db_server +
                            "?verifyServerCertificate=false" +
                            "&useSSL=true" +
                            "&requireSSL=true";
                            System.setProperty(jdbcDriver, "");
                            Class.forName(jdbcDriver).newInstance();

                            Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
                            Statement statement = conn.createStatement();
                            String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + """ + letterID + """;
                            ResultSet resultSet = statement.executeQuery(query);
                            resultSet.next();
                            return resultSet.getString(1);






                            share|improve this answer





























                              4














                              MySQL JDBC Connection with useSSL.



                              private String db_server = BaseMethods.getSystemData("db_server");
                              private String db_user = BaseMethods.getSystemData("db_user");
                              private String db_password = BaseMethods.getSystemData("db_password");

                              private String connectToDb() throws Exception
                              String jdbcDriver = "com.mysql.jdbc.Driver";
                              String dbUrl = "jdbc:mysql://" + db_server +
                              "?verifyServerCertificate=false" +
                              "&useSSL=true" +
                              "&requireSSL=true";
                              System.setProperty(jdbcDriver, "");
                              Class.forName(jdbcDriver).newInstance();

                              Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
                              Statement statement = conn.createStatement();
                              String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + """ + letterID + """;
                              ResultSet resultSet = statement.executeQuery(query);
                              resultSet.next();
                              return resultSet.getString(1);






                              share|improve this answer



























                                4












                                4








                                4







                                MySQL JDBC Connection with useSSL.



                                private String db_server = BaseMethods.getSystemData("db_server");
                                private String db_user = BaseMethods.getSystemData("db_user");
                                private String db_password = BaseMethods.getSystemData("db_password");

                                private String connectToDb() throws Exception
                                String jdbcDriver = "com.mysql.jdbc.Driver";
                                String dbUrl = "jdbc:mysql://" + db_server +
                                "?verifyServerCertificate=false" +
                                "&useSSL=true" +
                                "&requireSSL=true";
                                System.setProperty(jdbcDriver, "");
                                Class.forName(jdbcDriver).newInstance();

                                Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
                                Statement statement = conn.createStatement();
                                String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + """ + letterID + """;
                                ResultSet resultSet = statement.executeQuery(query);
                                resultSet.next();
                                return resultSet.getString(1);






                                share|improve this answer















                                MySQL JDBC Connection with useSSL.



                                private String db_server = BaseMethods.getSystemData("db_server");
                                private String db_user = BaseMethods.getSystemData("db_user");
                                private String db_password = BaseMethods.getSystemData("db_password");

                                private String connectToDb() throws Exception
                                String jdbcDriver = "com.mysql.jdbc.Driver";
                                String dbUrl = "jdbc:mysql://" + db_server +
                                "?verifyServerCertificate=false" +
                                "&useSSL=true" +
                                "&requireSSL=true";
                                System.setProperty(jdbcDriver, "");
                                Class.forName(jdbcDriver).newInstance();

                                Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
                                Statement statement = conn.createStatement();
                                String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + """ + letterID + """;
                                ResultSet resultSet = statement.executeQuery(query);
                                resultSet.next();
                                return resultSet.getString(1);







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Sep 18 '17 at 15:02

























                                answered Mar 31 '17 at 21:33









                                AJCAJC

                                486413




                                486413





















                                    3














                                    you need to have mysql connector jar in your classpath.



                                    in Java JDBC API makes everything with databases. using JDBC we can write Java applications to

                                    1. Send queries or update SQL to DB(any relational Database)
                                    2. Retrieve and process the results from DB



                                    with below three steps we can able to retrieve data from any Database



                                    Connection con = DriverManager.getConnection(
                                    "jdbc:myDriver:DatabaseName",
                                    dBuserName,
                                    dBuserPassword);

                                    Statement stmt = con.createStatement();
                                    ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

                                    while (rs.next())
                                    int x = rs.getInt("a");
                                    String s = rs.getString("b");
                                    float f = rs.getFloat("c");






                                    share|improve this answer



























                                      3














                                      you need to have mysql connector jar in your classpath.



                                      in Java JDBC API makes everything with databases. using JDBC we can write Java applications to

                                      1. Send queries or update SQL to DB(any relational Database)
                                      2. Retrieve and process the results from DB



                                      with below three steps we can able to retrieve data from any Database



                                      Connection con = DriverManager.getConnection(
                                      "jdbc:myDriver:DatabaseName",
                                      dBuserName,
                                      dBuserPassword);

                                      Statement stmt = con.createStatement();
                                      ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

                                      while (rs.next())
                                      int x = rs.getInt("a");
                                      String s = rs.getString("b");
                                      float f = rs.getFloat("c");






                                      share|improve this answer

























                                        3












                                        3








                                        3







                                        you need to have mysql connector jar in your classpath.



                                        in Java JDBC API makes everything with databases. using JDBC we can write Java applications to

                                        1. Send queries or update SQL to DB(any relational Database)
                                        2. Retrieve and process the results from DB



                                        with below three steps we can able to retrieve data from any Database



                                        Connection con = DriverManager.getConnection(
                                        "jdbc:myDriver:DatabaseName",
                                        dBuserName,
                                        dBuserPassword);

                                        Statement stmt = con.createStatement();
                                        ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

                                        while (rs.next())
                                        int x = rs.getInt("a");
                                        String s = rs.getString("b");
                                        float f = rs.getFloat("c");






                                        share|improve this answer













                                        you need to have mysql connector jar in your classpath.



                                        in Java JDBC API makes everything with databases. using JDBC we can write Java applications to

                                        1. Send queries or update SQL to DB(any relational Database)
                                        2. Retrieve and process the results from DB



                                        with below three steps we can able to retrieve data from any Database



                                        Connection con = DriverManager.getConnection(
                                        "jdbc:myDriver:DatabaseName",
                                        dBuserName,
                                        dBuserPassword);

                                        Statement stmt = con.createStatement();
                                        ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");

                                        while (rs.next())
                                        int x = rs.getInt("a");
                                        String s = rs.getString("b");
                                        float f = rs.getFloat("c");







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Aug 15 '13 at 13:56









                                        kapil daskapil das

                                        1,6132328




                                        1,6132328





















                                            3














                                            Short and Sweet code.



                                            try

                                            Class.forName("com.mysql.jdbc.Driver");
                                            System.out.println("Driver Loaded");
                                            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
                                            //Database Name - testDB, Username - "root", Password - ""
                                            System.out.println("Connected...");

                                            catch(Exception e)

                                            e.printStackTrace();



                                            For SQL server 2012



                                            try

                                            String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
                                            //KHILAN is Host and 1433 is port number
                                            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                                            System.out.println("Driver Loaded");
                                            conn = DriverManager.getConnection(url);
                                            System.out.println("Connected...");

                                            catch(Exception e)

                                            e.printStackTrace();






                                            share|improve this answer





























                                              3














                                              Short and Sweet code.



                                              try

                                              Class.forName("com.mysql.jdbc.Driver");
                                              System.out.println("Driver Loaded");
                                              conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
                                              //Database Name - testDB, Username - "root", Password - ""
                                              System.out.println("Connected...");

                                              catch(Exception e)

                                              e.printStackTrace();



                                              For SQL server 2012



                                              try

                                              String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
                                              //KHILAN is Host and 1433 is port number
                                              Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                                              System.out.println("Driver Loaded");
                                              conn = DriverManager.getConnection(url);
                                              System.out.println("Connected...");

                                              catch(Exception e)

                                              e.printStackTrace();






                                              share|improve this answer



























                                                3












                                                3








                                                3







                                                Short and Sweet code.



                                                try

                                                Class.forName("com.mysql.jdbc.Driver");
                                                System.out.println("Driver Loaded");
                                                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
                                                //Database Name - testDB, Username - "root", Password - ""
                                                System.out.println("Connected...");

                                                catch(Exception e)

                                                e.printStackTrace();



                                                For SQL server 2012



                                                try

                                                String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
                                                //KHILAN is Host and 1433 is port number
                                                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                                                System.out.println("Driver Loaded");
                                                conn = DriverManager.getConnection(url);
                                                System.out.println("Connected...");

                                                catch(Exception e)

                                                e.printStackTrace();






                                                share|improve this answer















                                                Short and Sweet code.



                                                try

                                                Class.forName("com.mysql.jdbc.Driver");
                                                System.out.println("Driver Loaded");
                                                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
                                                //Database Name - testDB, Username - "root", Password - ""
                                                System.out.println("Connected...");

                                                catch(Exception e)

                                                e.printStackTrace();



                                                For SQL server 2012



                                                try

                                                String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
                                                //KHILAN is Host and 1433 is port number
                                                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                                                System.out.println("Driver Loaded");
                                                conn = DriverManager.getConnection(url);
                                                System.out.println("Connected...");

                                                catch(Exception e)

                                                e.printStackTrace();







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Oct 6 '15 at 20:19

























                                                answered Oct 6 '15 at 13:08









                                                KhiLan PaTeLKhiLan PaTeL

                                                1074




                                                1074





















                                                    3














                                                    You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.



                                                    Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA






                                                    share|improve this answer





























                                                      3














                                                      You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.



                                                      Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA






                                                      share|improve this answer



























                                                        3












                                                        3








                                                        3







                                                        You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.



                                                        Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA






                                                        share|improve this answer















                                                        You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.



                                                        Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA







                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Feb 13 '17 at 6:15









                                                        xlm

                                                        3,24493441




                                                        3,24493441










                                                        answered Jan 21 '12 at 6:24









                                                        JwalantJwalant

                                                        391




                                                        391





















                                                            2














                                                            Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly



                                                            Connection con = DriverManager.getConnection(
                                                            "jdbc:myDriver:DatabaseName",
                                                            dBuserName,
                                                            dBuserPassword);
                                                            if (con != null)
                                                            //..handle your code there



                                                            Or something like in that way :)



                                                            Probably there's some case, while getConnection can return null :)






                                                            share|improve this answer



























                                                              2














                                                              Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly



                                                              Connection con = DriverManager.getConnection(
                                                              "jdbc:myDriver:DatabaseName",
                                                              dBuserName,
                                                              dBuserPassword);
                                                              if (con != null)
                                                              //..handle your code there



                                                              Or something like in that way :)



                                                              Probably there's some case, while getConnection can return null :)






                                                              share|improve this answer

























                                                                2












                                                                2








                                                                2







                                                                Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly



                                                                Connection con = DriverManager.getConnection(
                                                                "jdbc:myDriver:DatabaseName",
                                                                dBuserName,
                                                                dBuserPassword);
                                                                if (con != null)
                                                                //..handle your code there



                                                                Or something like in that way :)



                                                                Probably there's some case, while getConnection can return null :)






                                                                share|improve this answer













                                                                Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly



                                                                Connection con = DriverManager.getConnection(
                                                                "jdbc:myDriver:DatabaseName",
                                                                dBuserName,
                                                                dBuserPassword);
                                                                if (con != null)
                                                                //..handle your code there



                                                                Or something like in that way :)



                                                                Probably there's some case, while getConnection can return null :)







                                                                share|improve this answer












                                                                share|improve this answer



                                                                share|improve this answer










                                                                answered May 28 '15 at 9:50









                                                                xxxvodnikxxxxxxvodnikxxx

                                                                97121228




                                                                97121228





















                                                                    0














                                                                    MySql JDBC Connection:



                                                                    Class.forName("com.mysql.jdbc.Driver"); 

                                                                    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
                                                                    Statement stmt=con.createStatement();
                                                                    stmt = con.createStatement();
                                                                    ResultSet rs=stmt.executeQuery("Select * from Table");





                                                                    share|improve this answer



























                                                                      0














                                                                      MySql JDBC Connection:



                                                                      Class.forName("com.mysql.jdbc.Driver"); 

                                                                      Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
                                                                      Statement stmt=con.createStatement();
                                                                      stmt = con.createStatement();
                                                                      ResultSet rs=stmt.executeQuery("Select * from Table");





                                                                      share|improve this answer

























                                                                        0












                                                                        0








                                                                        0







                                                                        MySql JDBC Connection:



                                                                        Class.forName("com.mysql.jdbc.Driver"); 

                                                                        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
                                                                        Statement stmt=con.createStatement();
                                                                        stmt = con.createStatement();
                                                                        ResultSet rs=stmt.executeQuery("Select * from Table");





                                                                        share|improve this answer













                                                                        MySql JDBC Connection:



                                                                        Class.forName("com.mysql.jdbc.Driver"); 

                                                                        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
                                                                        Statement stmt=con.createStatement();
                                                                        stmt = con.createStatement();
                                                                        ResultSet rs=stmt.executeQuery("Select * from Table");






                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Jan 9 '17 at 17:13









                                                                        Sarat ChandraSarat Chandra

                                                                        2,3281421




                                                                        2,3281421





















                                                                            0














                                                                            Short Code



                                                                            public class DB 

                                                                            public static Connection c;

                                                                            public static Connection getConnection() throws Exception
                                                                            if (c == null)
                                                                            Class.forName("com.mysql.jdbc.Driver");
                                                                            c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");

                                                                            return c;


                                                                            // Send data TO Database
                                                                            public static void setData(String sql) throws Exception
                                                                            DB.getConnection().createStatement().executeUpdate(sql);


                                                                            // Get Data From Database
                                                                            public static ResultSet getData(String sql) throws Exception
                                                                            ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
                                                                            return rs;







                                                                            share|improve this answer





























                                                                              0














                                                                              Short Code



                                                                              public class DB 

                                                                              public static Connection c;

                                                                              public static Connection getConnection() throws Exception
                                                                              if (c == null)
                                                                              Class.forName("com.mysql.jdbc.Driver");
                                                                              c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");

                                                                              return c;


                                                                              // Send data TO Database
                                                                              public static void setData(String sql) throws Exception
                                                                              DB.getConnection().createStatement().executeUpdate(sql);


                                                                              // Get Data From Database
                                                                              public static ResultSet getData(String sql) throws Exception
                                                                              ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
                                                                              return rs;







                                                                              share|improve this answer



























                                                                                0












                                                                                0








                                                                                0







                                                                                Short Code



                                                                                public class DB 

                                                                                public static Connection c;

                                                                                public static Connection getConnection() throws Exception
                                                                                if (c == null)
                                                                                Class.forName("com.mysql.jdbc.Driver");
                                                                                c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");

                                                                                return c;


                                                                                // Send data TO Database
                                                                                public static void setData(String sql) throws Exception
                                                                                DB.getConnection().createStatement().executeUpdate(sql);


                                                                                // Get Data From Database
                                                                                public static ResultSet getData(String sql) throws Exception
                                                                                ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
                                                                                return rs;







                                                                                share|improve this answer















                                                                                Short Code



                                                                                public class DB 

                                                                                public static Connection c;

                                                                                public static Connection getConnection() throws Exception
                                                                                if (c == null)
                                                                                Class.forName("com.mysql.jdbc.Driver");
                                                                                c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");

                                                                                return c;


                                                                                // Send data TO Database
                                                                                public static void setData(String sql) throws Exception
                                                                                DB.getConnection().createStatement().executeUpdate(sql);


                                                                                // Get Data From Database
                                                                                public static ResultSet getData(String sql) throws Exception
                                                                                ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
                                                                                return rs;








                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited Sep 17 '17 at 11:21









                                                                                YakovL

                                                                                3,203102845




                                                                                3,203102845










                                                                                answered Sep 17 '17 at 10:01









                                                                                Corrupted_S.KCorrupted_S.K

                                                                                817




                                                                                817





















                                                                                    0














                                                                                    HOW

                                                                                    • To set up the Driver to run a quick sample

                                                                                    1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J

                                                                                    2. Remember to set the classpath to include the path of the connector jar file.
                                                                                    If we don't set it correctly, below errors can occur:

                                                                                    No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development

                                                                                    java.lang.ClassNotFoundException: com.mysql.jdbc:Driver


                                                                                    • To set up the CLASSPATH

                                                                                    Method 1: set the CLASSPATH variable.



                                                                                    export CLASSPATH=".:mysql-connector-java-VERSION.jar"
                                                                                    java MyClassFile


                                                                                    In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
                                                                                    And it found the Drive class => BOOM errors was gone.



                                                                                    Method 2:



                                                                                    java -cp .:mysql-connector-java-VERSION.jar MyClassFile


                                                                                    Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.



                                                                                    Hope this can help someone!






                                                                                    share|improve this answer





























                                                                                      0














                                                                                      HOW

                                                                                      • To set up the Driver to run a quick sample

                                                                                      1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J

                                                                                      2. Remember to set the classpath to include the path of the connector jar file.
                                                                                      If we don't set it correctly, below errors can occur:

                                                                                      No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development

                                                                                      java.lang.ClassNotFoundException: com.mysql.jdbc:Driver


                                                                                      • To set up the CLASSPATH

                                                                                      Method 1: set the CLASSPATH variable.



                                                                                      export CLASSPATH=".:mysql-connector-java-VERSION.jar"
                                                                                      java MyClassFile


                                                                                      In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
                                                                                      And it found the Drive class => BOOM errors was gone.



                                                                                      Method 2:



                                                                                      java -cp .:mysql-connector-java-VERSION.jar MyClassFile


                                                                                      Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.



                                                                                      Hope this can help someone!






                                                                                      share|improve this answer



























                                                                                        0












                                                                                        0








                                                                                        0







                                                                                        HOW

                                                                                        • To set up the Driver to run a quick sample

                                                                                        1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J

                                                                                        2. Remember to set the classpath to include the path of the connector jar file.
                                                                                        If we don't set it correctly, below errors can occur:

                                                                                        No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development

                                                                                        java.lang.ClassNotFoundException: com.mysql.jdbc:Driver


                                                                                        • To set up the CLASSPATH

                                                                                        Method 1: set the CLASSPATH variable.



                                                                                        export CLASSPATH=".:mysql-connector-java-VERSION.jar"
                                                                                        java MyClassFile


                                                                                        In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
                                                                                        And it found the Drive class => BOOM errors was gone.



                                                                                        Method 2:



                                                                                        java -cp .:mysql-connector-java-VERSION.jar MyClassFile


                                                                                        Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.



                                                                                        Hope this can help someone!






                                                                                        share|improve this answer















                                                                                        HOW

                                                                                        • To set up the Driver to run a quick sample

                                                                                        1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J

                                                                                        2. Remember to set the classpath to include the path of the connector jar file.
                                                                                        If we don't set it correctly, below errors can occur:

                                                                                        No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development

                                                                                        java.lang.ClassNotFoundException: com.mysql.jdbc:Driver


                                                                                        • To set up the CLASSPATH

                                                                                        Method 1: set the CLASSPATH variable.



                                                                                        export CLASSPATH=".:mysql-connector-java-VERSION.jar"
                                                                                        java MyClassFile


                                                                                        In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
                                                                                        And it found the Drive class => BOOM errors was gone.



                                                                                        Method 2:



                                                                                        java -cp .:mysql-connector-java-VERSION.jar MyClassFile


                                                                                        Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.



                                                                                        Hope this can help someone!







                                                                                        share|improve this answer














                                                                                        share|improve this answer



                                                                                        share|improve this answer








                                                                                        edited Apr 24 at 13:12

























                                                                                        answered Apr 24 at 13:05









                                                                                        Nhat DinhNhat Dinh

                                                                                        2,71422639




                                                                                        2,71422639















                                                                                            protected by Sean Owen May 23 '12 at 22:07



                                                                                            Thank you for your interest in this question.
                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                            Popular posts from this blog

                                                                                            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                                                                            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                                                                                            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해