Take the 2-minute tour ×

I installed MySql on my own machine. I created database, create table, ... using MySql CommandLine Client. When working on a project in school, I connected to school's database using this syntax:

public static Statement connect() {
  try {
   Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
   conn = DriverManager.getConnection( "1", "2", "3" );
   stmt = conn.createStatement();
  catch( Exception e ) {
   System.out.println( "Connection Error:  " + e );
  return stmt;

In my local machine, I don't have to type in user name, all I did is just login with my password as root user:

Enter password: ****
Your MySQL connection id is 1
Server version: 5.1.53-community MySQL Community Server (GPL)



mysql> use chandb;
Database changed
mysql> show tables;
| Tables_in_chandb |
| another          |
| cars             |
| employees        |
3 rows in set (0.03 sec)

mysql> select * from Another;
| Id | GoldValue | Model    |
|  0 |       100 | Civic DX |
1 row in set (0.00 sec)


I would like to know how can I connect to my local machine's database? what should I put as parameters within method .getConnection

conn = DriverManager.getConnection( 
   "1", // ?
   "2", // ?
   "3"  ); // ?

Best regards,

share|improve this question
Dude, remove that username and password from your code snippet, ASAP! Remove the hostname too, while you're at it. Also you don't need to clutter the snippet with the mistyped show tables bit –  Todd Dec 14 '10 at 5:33
Thanks for reminding about security issue. Editted. –  Chan Dec 14 '10 at 6:00
add comment

2 Answers

up vote 1 down vote accepted

Simple Connection:

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

public class Main {
    String driverName = "org.gjt.mm.mysql.Driver";

    String serverName = "localhost";
    String mydatabase = "mydatabase";
    String url = "jdbc:mysql://" + serverName + "/" + mydatabase; 

    String username = "username";
    String password = "password";
    Connection connection = DriverManager.getConnection(url, username, password);
share|improve this answer
Thanks Mohamed, but it did not work. I got exception thrown in main. Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:mysql :// localhost/chandb at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at Program.main(Program.java:15) –  Chan Dec 14 '10 at 5:58
I got it worked ;) Thanks ;) –  Chan Dec 14 '10 at 6:05
There are spaces in the URL which makes it invalid. Remove it. –  BalusC Jan 23 '11 at 13:54
@BalusC thanks for correction –  Mohamed Saligh Jan 24 '11 at 2:44
add comment

It looks like you left your username and password in the source you posted.

I don't see why you can't just do

DriverManager.getConnection("jdbc:mysql://localhost/chandb", "user, "pass");
share|improve this answer
add comment

Your Answer


