[SOLVED] Error in using statement in connecting mysql in my java project

Issue

screenshot of the codeI want to use statement in connecting mysql and java database, but the code is giving me errors, I want to know where did I go wrong and how I should do it without getting errore

try{
           Class.forName("com.mysql.jdbc.Driver");
                Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/sms","root","");
                 Statement st= (Statement)conn.createStatement();
                 String sql= "select * from user_login";
       }
           catch(Exception e){
               
           }![this is the screenshot of the code](https://i.stack.imgur.com/lo8Yo.png)

this is the declaration of the program

I tried using thisdeclaration

Solution

Alright, so to do JDBC with MySql you need 4 things

  1. Driver Class
  2. Connection URL
  3. Username
  4. Password

Assuming you have already created the database, with name database_name and table data that has 3 columns as id, first_name & last_name

Connection and showing the data in as follows:

import java.sql.*;
import java.util.*;
class ConnectionToDatabase{
  public static void main(String args[]){
    try{
      Class.forName("com.mysql.jdbc.Driver");
      Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","username","Pa$$word");
      Statement statement = connnection.createStatement();
      ResultSet resultSet = statement.executeQuery("select * from data");
      while(resultSet.next()){
        System.out.println(resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
        connection.close();  
      }  
    }catch(Exception e) { System.out.println(e); }
  }
}

And of course, you can use Spring Boot, where a file named application.properties exists inside java.resources, you can specify the connection as – (Copied from Spring docs)

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=databaseusername
spring.datasource.password=databasepassword

Answered By – Sandeep Roy

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.