Documente Academic
Documente Profesional
Documente Cultură
com
Source of IT knowledge
Site search:
Introduction
This tutorial show you how to use NetBeans to connect MySQL by using MySQL Connector/J, MySQL AB’s JDBC Driver for MySQL.
Requirements
MySQL Connector/J, licensed under the GPL or a commercial license
from MySQL AB.
NetBeans with JRE (Java Runtime Environment).
Step-by-Step guide
1. Installation
Install NetBeans.
Download MySQL Connector/J, name ‘mysql-connector-java-5.0.6.zip’. (The file name may differs depends on the version if
you’ve downloaded from the Official Site at here.)
Extract the zip file to a folder, you’ll see file ‘mysql-connector-java-5.0.6-bin.jar’ which is the library file that we want. Just
copy the file to the library folder, for example to “C:\Program Files\Java\jdk1.6.0_02\lib” directory.
2. Add JDBC Driver to the project on NetBeans (Add a library).
Next, I create a new Java project on NetBeans named ‘TestMySQL’ and add ‘mysql-connector-java-5.0.6-bin.jar’ that I’ve just
extracted from previous step to the project’s library.
1. Create New Project called TestSQL.
2. In Projects window, right click the project name and select Properties.
3. Project Properties window appears. The Categories on left side, select Libraries. And on right side in Compile tab, click Add
JAR/Folder.
4. New Window appears, browse to the file ‘mysql-connector-java-5.0.6-bin.jar’ and click Open.
5. You’ll see the .jar file was added to the project. Click OK to finish.
Note: You should keep mysql-connector-java-5.0.6-bin.jar in the directory that you won’t delete it (ex. not in temp folder).
May be in the same directory that keep common library files. If you delete the file without delete a link from the project, the
project will show error about missing library.
3. Connect to the database.
Now I’m going to write some code to connect to MySQL database. I have configured MySQL service on localhost.
1. I’m going to use Connection and DriverMapper Classes so I need to import libraries.
import java.sql.*;
2. I’ll connect to MySQL Server on local machine, the mysql database(a default database in MySQL). In main method, add the
following code.
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost/mysql?" +
"user=root&password=123456";
Connection con = DriverManager.getConnection(connectionUrl);
} catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
} catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
3. Compile and run the project. If no error occurs, it means that the connection has established successfully.
Next part, I’ll show to how to perform some basic SQL operations to MySQL.
Related post
Related posts:
1. Accessing SQL Server on NetBeans using JDBC, Part I: Create a connection Introduction This tutorial show you how to use NetBeans to
connect SQL Server (2000 and 2005) by using Microsoft SQL...
2. Accessing MS Access 2007 on NetBeans 6.5 using JDBC, Part 3: Create a Connection This article is one of the series of Accessing MS Access
2007 on NetBeans 6.5 using JDBC. You can see...
3. Accessing MySQL on NetBeans using JDBC, Part II: Perform SQL Operations From Part I, I have only established a connection with local
MySQL. Next I’ll show how to retrieve and modify...
4. Accessing SQL Server on NetBeans using JDBC, Part III: Troubleshooting This post is the last part which gathers common problems along
with solutions about accessing SQL Server using JDBC on...
5. Accessing MS Access 2007 on NetBeans 6.5 using JDBC, Part 1: Introduction Introduction Here comes again, a tutorial about accessing
database on NetBeans. In 2007, I wrote two tutorials which are accessing...
2. vanessa Says:
December 8th, 2007 at 4:37 am
no idea dear!!!!
4. Engineer Says:
December 31st, 2007 at 7:25 pm
The one who does not thank people, he does not thank the GOD
sorry i want the data to change on the scoreboard each time i change it from the control panel.. :):)
7. linglom Says:
January 7th, 2008 at 3:27 pm
I’m not sure that I understand your question correctly. If you have data displayed on more than 1 output, I suggest using Timer to
periodically update your data on each output.
9. Alan Says:
February 14th, 2008 at 12:50 am
Thanks for the example. For some reason I received the message: “SQL Exception: java.sql.SQLException: Access denied for user…”. I
then reformatted the getConnection to be in the form of 3 arguments like this:
String connectionUrl = “jdbc:mysql://localhost/”;
Connection con = DriverManager.getConnection(connectionUrl, “User”, “Password”);
where “User” and “Password” were registered in the MySQL server, and it connected fine. Also, I don’t have a db yet, so I left out the
db name.
Thanks again for taking the time to post your example.
To Alan,
Thank you for sharing.
Another way, you can use Windows Authentication method which authenticate by using the current user’s credential (user that execute
the application) so no need to specify username and password in application.
Reference: http://www.netbeans.org/kb/55/using-netbeans/project_setup.html
on Managing the Classpath in Free-form Projects -> Specifying the Classpath for Project Sources
Thanks.
cheers, sam
Thanks
DK
Why ? It almost 1 week i’m searching for solution, but I can’t get one.
thanks
34. T Says:
February 12th, 2009 at 8:28 pm
Best explanation I’ve read so far…thanx!
Netbeans 6.5 provides a very simple way for connecting to a database. Though I can’t seem to locate the connection object to execute
queries on :/
Have you tried it?
cheers for writing this tutorial. it’s very useful and it works just fine. if only i found this blog sooner, spent an entire weekend trying to
connect to my mysql database without success…
Using the snippet provided above I’m trying to retreive the contents of the Database table Person. I’ve already created the table using
mysql.
But as soon as I execute this I’m getting the following exception.
package testapp;
import java.sql.*;
try {
Class.forName(“com.mysql.jdbc.Driver”);
String connectionUrl = “jdbc:mysql://localhost/mysql?” + “user=root&password=pwdpwd”;
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost/Customer”,”root”,”pwd”);
String query=”Select *from Person”;
stmt=con.createStatement();
Results=stmt.executeQuery(query);
stmt.close();
boolean Records=Results.next();
if(!Records)
{
System.out.println(“No Data returned”);
return;
}
else
{
do{
FirstName=Results.getString(1);
Id=Results.getString(2);
printrow=FirstName+” “+Id;
System.out.println(printrow);
}while(Results.next());
}
} catch (SQLException e) {
System.out.println(“SQL Exception: “+ e.toString());
} catch (ClassNotFoundException cE) {
System.out.println(“Class Not Found Exception: “+ cE.toString());
}
Thanks in advance!
Thanks dude…..
It says Build is sccuessful but also says failure handshake. Can you please let me know if the connection is successful or not?
Thanks
Ankit
package my.test;
import java.sql.*;
import java.util.*;
public class NewClass
{
public static void main(String[] args)
{
int a = 5;
a= a^3;
System.out.println(Math.pow(2, 4));
DB db = new DB();
Connection conn=db.dbConnect(
“jdbc:mysql://localhost:3306/applet”, “root”, “password”);
try{
Statement query= conn.createStatement();
query.executeQuery(“select * from tabletest where ID=\’3\’”);
ResultSet rs = query.getResultSet();
System.out.println(rs.next());
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt (“ID”);
int recordX = rs.getInt (“RecordX”);
int recordY = rs.getInt (“RecordY”);
System.out.println (
“id = ” + idVal
+ “, name = ” + recordX
+ “, category = ” + recordY);
++count;
}
rs.close ();
query.close ();
System.out.println (count + ” rows were retrieved”);
List list = new LinkedList();
list.add(1);
list.add(3);
list.add(5);
System.out.println(list.size());
}
catch(Exception e)
{
}
}
class DB
{
public DB() {}
System.out.println(“connected”);
return conn;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
};
java.net.ConnectException
MESSAGE: Connection refused: connect
STACKTRACE:
For the second problem, try to change the hostname in the connection string to ip address, try both 127.0.0.1 and your network ip
address.
Hi, Nissy
I’m not have experience with mobile application. But I think the code for mobile application should be simialr with this example.
java.net.SocketException
MESSAGE: java.net.ConnectException: Connection refused: connect
STACKTRACE:
THanks a lot
run:
SQL Exception: java.sql.SQLException: Access denied for user ‘root’@'localhost’ (using password: YES)
BUILD SUCCESSFUL (total time: 0 seconds)
The error message stated that you had provided with the wrong password for user ‘root’. You need to change user name and password
to the correct one in the connection string.
I was terrible upset for I was not able connect to Oracle DB using netbean. Your lesson part one and two has given me breather and I am
so happy that I am able to connect to Oracle. Your style creating a class with a connection method, object creation to get connection is
excellent.
S.Kumar
Sir.
A good lesson.
Thnkx 4 ua concern
System.out.println(“pass class.forName”);
// Create a connection to the database
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println(“pass Connection”);
Error at :
DriverManager.getConnection(url, username, password);
org.gjt.mm.mysql.Driver
pass class.forName
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near ‘????????????????’ at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1051)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2562)
at com.mysql.jdbc.ConnectionImpl.configureClientCharacterSet(ConnectionImpl.java:1856)
at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3457)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2328)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2122)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:774)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:371)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:289)
at java.sql.DriverManager.getConnection(libgcj.so.90)
at java.sql.DriverManager.getConnection(libgcj.so.90)
at test.DBCommunication.ExecuteQuerry(DBCommunication.java:52)
at test.Main.main(Main.java:22)
SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right
syntax to use near ‘????????????????’ at line 1
SQLState: 42000
VendorError: 1064
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I solution friend
Class.forName(“com.mysql.jdbc.Driver”);
String connectionUrl = “jdbc:mysql://localhost:3306/balsdb”;
Connection con = DriverManager.getConnection(connectionUrl,”Admin”,”admin”);
Verify if that username and password is correct and it has sufficient privilege to access the selected database.
118. 6. Java for Web Development for PHP developer – a rant Says:
September 24th, 2010 at 1:26 am
[...] I was getting better error explanation in Eclipse. After searching on Google, I got the solution. Solution is to mention the file in
Library from the project's properties [...]
I need help in connecting a database (mysql) to a java web application. Please help by giving me an idea on how to go about it. I don’t
have an idea.
Thanks.
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
BUILD SUCCESSFUL (total time: 9 seconds)
do I still need to download mysql connector.? can’t configure it though… pls post or email me thanks
lordbyron_yumul@yahoo.com
Thanks
Have you add MySQL Connector/J library to your project and “import java.sql.*;” in your code?
Hi, Harshit