HOW TO CONNECT JAVA TO MYSQL DATABASE?

  1. DOWNLOAD AND INSTALL MYSQL SERVER
  2. DOWNLOAD THE JDBC Driver extract the ZIP file and put the containing JAR file in the classpath or in current directory of your code.
  3. MAKE SURE YOU HAVE YOUR MYSQL USERS TABLE IN YOUR [DATABASE] WITH USERNAME COLUMN

4. CREATE A FILENAME MySQLConnectExample.java

5. PUT THIS CODE INSIDE THE FILE. (TAKENOTE: CASE SENSITIVE)

import java.sql.*;
import java.util.Properties;

public class MySQLConnectExample
{
public static void main(String[] args)
{

Connection conn = null;
Statement stmt = null;
try {
String url1 = “jdbc:mysql://localhost:3306/dbname”; //your database name
String user = “root”; //login user
String password = “password”; //user db password

conn = DriverManager.getConnection(url1, user, password);
if (conn != null)
System.out.println(“Connected to the database test1”);

System.out.println(“Creating a statement..”);
stmt = conn.createStatement();
String sql;
sql = “SELECT username FROM users;”;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String value1 = rs.getString(“username”);
System.out.println(“users: ” + value1);
}

} catch (SQLException ex) {
System.out.println(“An error occurred. Maybe user/password is invalid”);
ex.printStackTrace();
}
}
}

SEE THE IMAGE BELOW TO THE FOLDER CONTENTS ON HOW TO COMPILE AND RUN THE PROGRAM.

6. COMPILE: javac MySQLConnectionExample.java

7. RUN: java -cp mysql-connector-java-5.1.37-bin.jar;. MySQLConnectExample
connect_java_to_mysql

Advertisements
This entry was posted in JAVA. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s