Databases Concepts
Databases Concepts
Figure: NetBeans project libs
Register the JDBC driver: Requires that you initialize a driver so you can open
a communication channel with the database.
To start, we use the forName method of the Class class to load the driver.
For MySQl:
Class.forName("com.mysql.jdbc.Driver");
Class.forName("org.apache.derby.jdbc.ClientDriver");
i.e
DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
For MySQl:
DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","username", "password");
Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
Extract data from result set: Requires that you use the
appropriateResultSet.getXXX() method to retrieve the data from the result set.
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
rs.close();
stmt.close();
conn.close();
EXAMPLE: Create a Frame for Contacts Table
In the following example, the default user name and password for mySql database.
The security for the database was enabled, you would need to supply a valid user
name and password for the database.
DBconn = DriverManager.getConnection(myDb,"root","");
jTextArea1.setText("Db connected");
statement =
DBconn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONC
UR_UPDATABLE);
save.setEnabled(false);
cancel.setEnabled(false);String user = "root";
try{
String query = "SELECT * FROM contacts";
results = statement.executeQuery(query);
rows= results.getRow();
num = results.getString(4);
email = results.getString(3);
System.out.println(email);
nameText.setText(name);
addressText.setText(address);
phoneTxt.setText(num);
emailTxt.setText(email);
}
}catch(Exception e){e.printStackTrace();}
How to return a result set
The result of a SQL query is available in Resultset object. Resultsets are of 3 types.
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
Concurrency of ResultSet
By default get one that is CONCUR_READ_ONLY.
Concurrency Description
Code examples
results.last();
name = results.getString(1);
address = results.getString(2);
System.out.println(name);
num = results.getString(3);
email = results.getString(4);
nameText.setText(name);
addressText.setText(address);
phoneTxt.setText(num);
emailTxt.setText(email);
String name="";
String address="";
String email="";
String num="";
try{
if(!results.isFirst()){
results.previous();
name = results.getString(1);
address = results.getString(2);
System.out.println(name);
num = results.getString(3);
email = results.getString(4);
nameText.setText(name);
addressText.setText(address);
phoneTxt.setText(num);
emailTxt.setText(email);
}} catch(SQLException e){e.printStackTrace();}
The first, previous, next, last, absolute, and relative methods all return a true value
if the new row exists and a false value if the new row doesn’t exist or the result
isn’t valid.
All of the methods in this figure throw an exception of the SQLException type.
ClearActionPerformed(evt);
save.setEnabled(false);
cancel.setEnabled(false);
name= nameText.getText();
address= addressText.getText();
num= phoneTxt.getText();
email= emailTxt.getText();
// updating data
results.updateString( "name", name );
results.updateString( "address", address );
results.updateString( "phone", num );
results.updateString( "email", email );
results.updateRow( );
JOptionPane.showMessageDialog(this, "Updated");
ClearActionPerformed(evt);
}catch(Exception e){e.printStackTrace();}
try{
int res= JOptionPane.showConfirmDialog(null,
"Press Yes to Delete", "Press Yes to Delete", JOptionPane.YES_NO_OPTION);
if(res==JOptionPane.YES_OPTION){ClearActionPerformed(evt);
results.deleteRow( );}
}catch(Exception e){e.printStackTrace();}
Extra methods
Code for Clear Button:
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// int res=JOptionPane.showConfirmDialog(this, " Do you Wanna Clear Data");
// if(res==JOptionPane.YES_OPTION){
nameText.setText("");
addressText.setText("");
phoneTxt.setText("");
emailTxt.setText("");//}
1) Obviously, Jasper Library needs to be added to our project and some sort of layout has to be
generated before we are able to start reporting from Java code.
2) Jasper's reporting layout design is nothing but an XML file with the extension
<filename>.jrxml.
3) This JRXML file is to be compiled to create <filename>.jasper. JRXML file can be compiled
on the fly, dynamically from our Java code or we can use iReport or JasperStudio to visually
design the JRXML file and then compile to create a Jasper file.
4) Once compiled and <filename>.jasper are created, we are done and can feed data into the
report from the Java code.
After downloading the plugin, follow the listed steps to install the plugin in NetBeans:
5. Select the plugin files. For iReport 5.5.0 the plugins are: iReport-
5.5.0.nbm, jasperreports-components-plugin-5.5.0.nbm, jasperreportsextensions-
plugin-5.5.0.nbm, and jasperserver-plugin-5.5.0.nbm. After opening the plugin files you
will see the following screen:
6. Check the Install checkbox of ireport-designer, and press the Install button at the
bottom of the window. The following screen will appear:
7. Press Next >, and accept the terms of the License Agreement.
8. If the Verify Certificate dialog box appears, click Continue.
9. Press Install, and wait for the installer to complete the installation.
10. After the installation is done, press Finish and close the Plugins dialog. If the IDE
requests for a restart, then do it. Now the IDE is ready for creating reports.
Creating reports
We have already learnt about creating various types of reports, such as reports without
parameters, reports with parameters, reports with variables, subreports, crosstab reports,
reports with charts and images, and so on. We have also attained knowledge associated
with these types of reports. Now, we will learn quickly how to create these reports using
NetBeans with the help of the installed iReport plugins.
1. Select the Services tab from the left side of the project window.
2. Select Databases.
3. Right-click on Databases, and press New Connection….
4. In the New Database Connection dialog, set the following under Basic setting, and
check theRemember password checkbox:
Option Value
Host localhost
Port 3306
Database inventory
Password packt
5. Press OK. Now the connection is created, and you can see this under the Services |
Databasessection, as shown in the following screenshot:
Creating a report data source
The NetBeans database JDBC connection created previously will be used by a report data
source that will be used by the report. Follow the listed steps to create the data source:
1. From the NetBeans toolbar, press the Report Datasources button. You will see the
following dialog box:
2. Press New.
3. Select NetBeans Database JDBC connection, and press Next >.
4. Enter inventory in the Name field, and from the Connection drop-down list,
selectjdbc:mysql://localhost:3306/inventory [root on Default schema].
5. Press Test, and if the connection is successful, press Save and close
the Connections / Datasourcesdialog box.
Creating a simple report
We are going to create a report, which shows the list of products. Just follow the listed steps:
3. Press Next >. Select the Simple Blue layout and press Next > again.
4. Enter ProductListNB.jrxml as File Name:, and Browse… to the reports folder.
9. Select all the fields, press >>, and then press Next >.
10. Press Next > again without selecting any group.
11. Press Finish. You will see the following output:
12. Click on the Preview button to see the output, as shown in the following screenshot:
13. You can design the report in the Designer section as per your design requirements.
Creating a parameterized report
We are going to create a report in NetBeans that shows the information of a particular user.
Follow the listed steps:
16. Change the Name to Name(i.e parameter name corresponding to the field name)
17. Change the Parameter Class to java.lang.String
18. Check the Use as a prompt checkbox.
19. Now, click on Report query (beside the Preview button),
20. Replace the query with the following one.(Note P must be in capital)
SELECT * FROM Contacts
WHERE name= $P{Name}
21. Press OK and Preview the report. Input the customerNo, and see the output.
Passing Parameter from JFrame to report
First we need to import the following file to our project.
To call the report you must have to include the following jars in classpath-
i.e add these jar file from lib folder of Jasper report project Zip file
1. commons-beanutils-1.9.0.jar
2. commons-collections-3.2.1.jar
3. commons-digester-2.1.jar
4. commons-logging-1.1.1.jar
5. groovy-all-2.0.1.jar
6. iText-2.1.7.jar
7. jasperreports-6.1.0.jar
We are going call report from NetBeans that shows the information of a particular user.
Follow the listed steps:
.
3. Run the program and provide parameter and Click the generate param button
4. Report for specific user is generated
2. Run the program and generate report without parameter by Clicking the generate
button