PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 2, 2022

[FIXED] How to connect to database connection in Java

 July 02, 2022     database, java, jdbc, xampp     No comments   

Issue

I would like to know how to connect to database in which is hosted in Xampp MySQL.

This is what I have so far in my java code to connect but I'm unsure what I'm doing.

public static void main(String[] args) {
    try {
        Connection con = DriverManager.getConnection( host, username, password );
        String host = "jdbc:derby://localhost:1527/Employees";
        String uName = "root";
        String uPass= "password";
    }
    catch ( SQLException err ) {
    System.out.println( err.getMessage( ) );
    }

}
  1. What would the host URL be?
  2. Do i need a JDBC Jar file to connect to the DB?

I have setup a database and table via phpMyAdmin already. Just don't know how to proceed.

I am using Netbeans to write my Java code to connect to a local database which was created via Xampp PHPMyAdmin.

In the end, I want to create a database connection in Java and call out tables within the IDE. Would appreciate some help.


Solution

This is the project structure

Project Structure

Try with this

Update

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your MySQL JDBC Driver?");
        e.printStackTrace();
        return;
    }

    System.out.println("MySQL JDBC Driver Registered!");
    Connection connection = null;

    try {
        connection = DriverManager
        .getConnection("jdbc:mysql://localhost:3306/testspring","root", "password");

    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;
    }

    if (connection != null) {
        System.out.println("You made it, take control your database now!");
    } else {
        System.out.println("Failed to make connection!");
    }
}

It is working for me

I downloaded jar from Java2s.com

Refer



Answered By - Suganthan Madhavan Pillai
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing