Using JDBC to connect to MySQL from Java Program

By: Rajan Emailed: 1591 times Printed: 2037 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

This sample Java program connects to MySQL database using JDBC, executes a query and retrieves and prints the value of the database field.

This same sample code can be used to connect to any type of database, all you need to do is change the connection url (dbUrl in the sample). For this code to work properly, you will need to download the mysql driver for JDBC in other words Java Connectors from mysql.com site.

If after downloading the URL it still doesn't work then it is probably due to the classpath. You will have to add the driver jar file in the classpath.

import java.sql.*;
import javax.sql.*;

public class jdbcdemo{

public static void main(String args[]){
String dbtime;
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select * FROM users";

try {

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
dbtime = rs.getString(1);
System.out.println(dbtime);
} //end while

con.close();
} //end try

catch(ClassNotFoundException e) {
e.printStackTrace();
}

catch(SQLException e) {
e.printStackTrace();
}

}  //end main

}  //end class

JDBC Home | All JDBC Tutorials | Latest JDBC Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(33)


1. View Comment

Thanks! Can u explain how to use PreparedStatements with Parameters under MySQL?

View Tutorial          By: Shashank Araokar at 2007-05-07 07:41:54
2. View Comment

Can you explain when the user input through the above code; How can add using a variable parsing?

View Tutorial          By: mujmil at 2008-02-11 18:46:00
3. View Comment

this is i got error msg when i run a my program . how to overcome any one pls helpme. java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at cod.focusLost(cod.java:368)
at java.awt.AWTEventMulticaster.focusLost(AWTEventMulticaster.java:213)
at java.awt.Component.processFocusEvent(Component.java:6108)
at java.awt.Component.processEvent(Component.java:5972)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4583)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.ja
va:1848)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeybo
ardFocusManager.java:889)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFoc
usManager.java:562)
at java.awt.Component.dispatchEventImpl(Component.java:4455)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4413)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
ad.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)


View Tutorial          By: anbu at 2009-04-08 02:41:17
4. View Comment

can u explain about printStackTrace()method.what is the use of it?

View Tutorial          By: himabindu at 2009-06-10 20:03:14
5. View Comment

@ anub : This is because you need to add external jar file that is connector mysql-connector-java-5.1.8-bin.jar

View Tutorial          By: Sushil at 2009-09-09 12:24:23
6. View Comment

wen i run i get dis error

jdbc:mysql://localhost:3306/details,root,root
java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO
)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:910)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3923)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1273)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2031)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:718)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstruct
orAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingC
onstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java
:282)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)


View Tutorial          By: sandeep at 2009-11-24 08:24:20
7. View Comment

when i tried this code i couldnt run the program...

View Tutorial          By: kavitha at 2009-11-28 01:38:55
8. View Comment

It seems like your getConnection doesnt recognize the credentials you pass. Can you try like this?

String url = "jdbc:mysql://localhost:3306/details";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (url, "root", "root");


View Tutorial          By: Partha at 2009-11-28 11:32:53
9. View Comment

i have written above code but the values are not storing in the database but there is no errors

View Tutorial          By: varun at 2010-01-15 18:37:19
10. View Comment

The above code is not for storing values it returns resultset note that sql query is SELECT not INSERT

View Tutorial          By: vinoj at 2010-04-28 15:58:47
11. View Comment

i have run the program..bt there r so many exception comes

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:268)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:164)
at abc.db_con.main(db_con.java:18)


View Tutorial          By: ayan at 2010-05-26 10:37:51
12. View Comment

i can saved when i run the program...
but when I check the mysql,
there is no record..

how can I solved it?!


View Tutorial          By: kathleen ashley at 2010-08-02 05:22:46
13. View Comment

thank you....
I have a problem.
I my source code I have a Book as a class and BookEntryForm class
and InsertConnectivity class.
there is two more class Main and ConnectionManager..
Now every Class is compiled but I don't understand how I connect it with the database in Main class..
plz it is imp for my project....


View Tutorial          By: AbhiRules at 2010-08-05 20:55:27
14. View Comment

i fixed it already...

how can I get the data from the mysql?!
the record that I saved?!

kindly give me any idea....

thanks


View Tutorial          By: kathleen ashley at 2010-08-08 04:51:26
15. View Comment

Hi guys, What is the best way to connect to mysql from java? May I connect to mysql in java from another pc I mean a remote pc withought using socket? Is there any risk?

View Tutorial          By: veron at 2010-09-11 16:13:25
16. View Comment

someone explain how to use PreparedStatements with Parameters under MySQL?

View Tutorial          By: Manikprabhu at 2011-03-26 00:04:54
17. View Comment

how to connect the database in servelet use to statements
and how to use servlete in ecclips


View Tutorial          By: sudhir singh tomar at 2011-04-28 03:10:34
18. View Comment

Thank you very much for your help,
this code is perfect! this has been a great help to me a few tweaks had to be made according to my tests but everything else is fantastically done.
Thank once again,
AA


View Tutorial          By: AA at 2011-09-09 14:24:45
19. View Comment

hi friends,
can i write the same jdbc code to access the db s/w that is installed in remote computer or i need any other extra setup to do it


View Tutorial          By: mahesh at 2012-01-05 05:09:38
20. View Comment

@mahesh yes you can use this to connect to any db server. Just get the ip address of the db server and replace the below line
String dbUrl = "jdbc:mysql://your.database.domain/yourDBname";

To
String dbUrl = "jdbc:mysql://ip/yourDBname";


View Tutorial          By: Rita sen at 2012-01-05 05:18:13
21. View Comment

How to connect a webpage(which I have created for my project) to the database(database may be mysql or oracle).
i.e., I have a web page, in which i have registration. Then when I enter the values in the form and those values should be stored in mysql database or oracle database


View Tutorial          By: sam at 2012-01-24 10:10:52
22. View Comment

hola

no funciona este
String userName = "userxxxx";
String password = "pasxxxx";
String url = "jdbc:mysql://free.hostingjava.it/dbase";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);

me da este


Cannot connect to database server : Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.


View Tutorial          By: ahmed at 2012-05-11 14:18:46
23. View Comment

Perfectly working, and able to connect database.
But is it the most efficient way to connect database or any other ? As I have seen so many others implementataion also and with faster result.


View Tutorial          By: satyajit at 2012-06-01 20:16:53
24. View Comment

i got an error msg at runtime of jdbc program with mysql...
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Demo.main(Demo.java:11)
plz tel me how can i solve this problem.........?


View Tutorial          By: madhu sudan at 2012-06-17 02:52:53
25. View Comment

I successfully connect to mysql server using:
"jdbc:mysql://localhost:3306/mysql";
But the problem I face at the end is compilation/execution of Query. I get the following error:
Error: java.lang.ClassNotFoundException: Select * from subject
BUILD SUCCESSFUL (total time: 0 seconds)
------------------ Please Suggest What should I do with this error
Thanks


View Tutorial          By: Arsalan at 2012-07-09 16:38:49
26. View Comment

MySQL Connector/J supports only TCP/IP connections
Java does not support Unix domain sockets connectivity

If the MYSQL is started with skip-networking flag or if the MySQL is running behind the firewall, then TCP/IP option is disabled. So that Java cannot communicate with MySQL.


View Tutorial          By: Java Training Institute In Chennai at 2012-09-13 12:37:44
27. View Comment

this what i get on the servlet web page plz some one guide me .....-->com.mysql.jdbc.Driver

View Tutorial          By: boney dsilva at 2012-09-19 15:37:09
28. View Comment

package com.anand;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MySqlProjMain {


MySqlProjMain () {
init();
}

private void init() {
String dbUrl = "jdbc:mysql://localhost:3306/world";
String dbDriverClass = "com.mysql.jdbc.Driver";
String sql = "Select * from country";
String userName = "root", password = "password";
try {
Class.forName(dbDriverClass);
Connection conn = DriverManager.getConnection(dbUrl, userName, password);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
System.out.println( rs.getString("name") );
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MySqlProjMain main = new MySqlProjMain();
System.out.println("hello world");


}


}


View Tutorial          By: Anand at 2012-11-12 00:00:07
29. View Comment

"Invalid Password at the jsp bcos RuntimeException" How do i solve this error?

View Tutorial          By: Ogah I. G at 2013-01-08 16:44:54
30. View Comment

i connect my program to my sql and create table. and data are loded , but connection not stabliush!!!!
what m'i do i dont know ,i appley all method but i loss so plz help me...........


View Tutorial          By: Santosh Agrawal at 2013-04-08 13:00:56
31. View Comment

unzip jquery-ui-1.10.3.custom

and copy mysql-connector-java-5.1.25-bin.jar to your home folder and run this command

export CLASSPATH=mysql-connector-java-5.1.25-bin.jar:$CLASSPATH


View Tutorial          By: ajmal at 2013-06-06 10:44:55
32. View Comment

I have writtent this code in my jdbc program,

String url = "jdbc:mysql://localhost:3306/DBName";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (url, "root", "root");
This will connect with my localhost xampp server but i want to access my domain database with my JDBC program..please help me.


View Tutorial          By: yeshdeep kumar at 2014-11-12 07:46:46
33. View Comment

i want the database connectivity for telephone billing system project can you help me please

View Tutorial          By: rohan at 2015-04-05 05:01:46

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Rajan
WebWork 2 is now Apache Struts 2
Using JDBC to connect to MySQL from Java Program
Execute system commands in a Java Program
Cookies using JSP or Java Bean
Sample Java Script that displays a movable clock
Java Chat Client Sample Applet

More Tutorials in JDBC
TEXT datatype SPLIT in MSSQL - to solve the 8000 limit set by varchar
Import TEXT to TABLE in MSSQL
What is Referential Integrity in databases?
Handling CSV in Stored Procedures
setSavepoint and releaseSavepoint Example in Java
Calling a Stored Procedure from JDBC in Java
java.lang.NoClassDefFoundError and java.lang.NoSuchMethodError
Creating Database Connection Pool in Tomcat 5.0 and Tomcat 5.5 for MySQL and Java
JDBC Basics and JDBC Components
SELECT Statements
WHERE Clauses in SQL
Joins example in SQL
Common SQL Commands
Result Sets, Cursors and Transactions in SQL
Stored Procedures example in SQL

More Latest News
Most Viewed Articles (in JDBC )
A simple JDBC application sample code
How connection pooling works in Java and JDBC
JDBC Components
Using JDBC to extract data from a database and output to an XML document
Using the DriverManager Class vs Using a DataSource Object for a connection
PreparedStatement Example in Java
Using JDBC to connect to MySQL from Java Program
The Structure of JDBC
WHERE Clauses in SQL
JDBC Architecture
What is the ACID principal?
JDBC Basics and JDBC Components
Calling a Stored Procedure from JDBC in Java
Data Access Technologies in Java
Creating Database Connection Pool in Tomcat 5.0 and Tomcat 5.5 for MySQL and Java
Most Emailed Articles (in JDBC)
The Structure of JDBC
A simple JDBC application sample code
JDBC Components
What is the ACID principal?
Using Transactions in JDBC
How connection pooling works in Java and JDBC
Using JDBC to extract data from a database and output to an XML document
Using JDBC to connect to MySQL from Java Program
JDBC and Tomcat context settings
PreparedStatement Example in Java
Result Sets, Cursors and Transactions in SQL
Data Access Technologies in Java
WHERE Clauses in SQL
Joins example in SQL
Common SQL Commands