Sunday, July 29, 2007

Accessing Databases from Netbeans

Netbeans has very nice integration with JDBC databases. You can view data, and even run any SQL statement from within Netbeans. Assuming you already have a project open, here are the steps to do so:

Adding your JDBC Driver
  1. In the Runtime Window, expand the Databases node.
  2. Right-click on the Drivers node, and select New Driver...
  3. Click the Add button and browse to where your JDBC driver is located, and select your driver.
  4. In the Driver Class field, type in the string needed to load your driver. For example, this string is "com.mysql.jdbc.Driver" for the MySQL Connector/J driver.
  5. In the Name field, give a name for your driver. For example, "MySQL Connector/J".
  6. Press OK to close the New JDBC Driver window. You should see the driver now listed under the Drivers node.

Creating a New JDBC Connection
  1. Right-click on the Databases node, and select New Connection...
  2. In the Name drop-down, select the new driver you just added.
  3. In the Database URL field, type in the URL you use to connect to the database. For MySQL Connector/J, this is something like jdbc:mysql://theserver:3306/yourDB.
  4. In the User Name field, type in the username you use to connect to the database.
  5. In the Password field, type in the password you use to connect to the database.
  6. Press OK to close the New Database Connection window. You should now see your new connection defined under the Databases node.

Testing your Connection
  1. Right-click on your newly defined connection, and select Connect...
  2. In the Connect window, enter the database Username and Password, then press OK. Once connected, you should now see the Tables node under your connection.
  3. Expand the Tables node to view the tables in your database. You can right-click on one of your tables and select View Data...
  4. To run an SQL statement, you can right-click on the connection node, or any of the nodes under it, and select Execute command... This will open an SQL Command window.
  5. Type in your SQL statement in the SQL Command window, right-click on the window and select Run Statement. You should then see the results!

That's it! You may also want to view my other blog on how to Set up a Connection Pool with Tomcat. If you want to know more about Java and J2EE, please visit Active Learning where I conduct training courses.

No comments: