Create and View the Database Table in Java Swing


Download the database and jar file here download

      1.Create Java Project in Netbeans

      2.Create JFrame form

     3.Drag & Drop JTable


    4.Delete the predefined columns




   5.Then the jtable look like this


   6.Insert this getTable() method in your class 

public JTable getTable(int value)throws Exception{
String query=null;
query="select * from jsample where id='"+value+"'";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/path","root","root");
Statement s1=con.createStatement();
DefaultTableModel dm=new DefaultTableModel();
ResultSet rs=s1.executeQuery(query );
ResultSetMetaData rsmd=rs.getMetaData();
//Coding to get columns-
int cols=rsmd.getColumnCount();
String c[]=new String[cols];
for(int i=0;i<cols;i++){
c[i]=rsmd.getColumnName(i+1);
dm.addColumn(c[i]);
}
//get data from rows
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
jTable1.setModel(dm);     //change your table name here
con.close();
return jTable1;                 //change your table name here
  }

   7.Call your method from your Action 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
getTable(1);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}

  8.Output






Autocomplete using jquery and Mysql Database



Requirement:

Required javascript and css file Download Here

Required jsp files see below code

update.jsp

<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script src="jquery.autocomplete.js"></script>
<script language="javascript" type="text/javascript">

jQuery(function(){
$("#country").autocomplete("reg_update.jsp");
});
</script>
<title>Ganesh Rengarajan</title>
</head>
<body onLoad="show_clock()">
<table align="center" border="0" width=" 60%" cellspacing="6">
<tr>
<td >Select Name</td>
<td><input name="appno" id="country" name="country" size="20" ></td>
</tr>
</table>
</body>
</html>


reg_update.jsp

<%@page import="java.sql.*"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%

try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/path","root","root");
Statement s1=con.createStatement();
Statement st1=con.createStatement();
ResultSet rs=st1.executeQuery("select * from jsample");
String product="";
ArrayList aa=new ArrayList();
while(rs.next())
{
aa.add(rs.getString("name"));
}
int cnt=1;
String query = (String)request.getParameter("q");

for(int i=0;i<aa.size();i++)
{
String temp=(String) aa.get(i);

if(temp.toUpperCase().startsWith(query.toUpperCase()))
{
out.print(temp+"\n");
if(cnt>=10)
break;
cnt++;
}
}

}
catch(Exception ex)
{
System.out.println("error"+ex);
}

%>

how to create struts in netbeans

Sample table creation in PDF using Servlet



Required Jar:

Download Itext 1.3 jar 

Servlet Code:

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class PDFServlet extends HttpServlet
{

public PDFServlet()
{
super();
}


public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws javax.servlet.ServletException, java.io.IOException
{
DocumentException ex = null;

ByteArrayOutputStream baosPDF = null;

try
{
baosPDF = generatePDFDocumentBytes(req, this.getServletContext());

StringBuffer sbFilename = new StringBuffer();
sbFilename.append("filename_");
sbFilename.append(System.currentTimeMillis());
sbFilename.append(".pdf");

resp.setHeader("Cache-Control", "max-age=30");

resp.setContentType("application/pdf");

StringBuffer sbContentDispValue = new StringBuffer();
sbContentDispValue.append("inline");
sbContentDispValue.append("; filename=");
sbContentDispValue.append(sbFilename);

resp.setHeader(
"Content-disposition",
sbContentDispValue.toString());

resp.setContentLength(baosPDF.size());

ServletOutputStream sos;

sos = resp.getOutputStream();

baosPDF.writeTo(sos);

sos.flush();
}
catch (DocumentException dex)
{
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println(
this.getClass().getName()
+ " caught an exception: "
+ dex.getClass().getName()
+ "<br>");
writer.println("<pre>");
dex.printStackTrace(writer);
writer.println("</pre>");
}
finally
{
if (baosPDF != null)
{
baosPDF.reset();
}
}

 }
protected ByteArrayOutputStream generatePDFDocumentBytes(
final HttpServletRequest req,
final ServletContext ctx)
throws DocumentException

{
Document doc = new Document();

ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
PdfWriter docWriter = null;

try
{
docWriter = PdfWriter.getInstance(doc, baosPDF);

doc.addAuthor(this.getClass().getName());
doc.addCreationDate();
doc.addProducer();
doc.addCreator(this.getClass().getName());
doc.addTitle("This is a title.");
doc.addKeywords("pdf, itext, Java, open source, http");
doc.setPageSize(PageSize.LETTER);

HeaderFooter footer = new HeaderFooter(
new Phrase("Created by Ganesh Rengarajan."),
false);

doc.setFooter(footer);
doc.open();
doc.add(new Paragraph(
  "Sample table in PDF using Web Application(Servlet)"));
doc.add( makeGeneralRequestDetailsElement(req) );
}
catch (DocumentException dex)
{
baosPDF.reset();
throw dex;
}
finally
{
if (doc != null)
{
doc.close();
}
if (docWriter != null)
{
docWriter.close();
}
}

if (baosPDF.size() < 1)
{
throw new DocumentException(
"document has "
+ baosPDF.size()
+ " bytes");
}
return baosPDF;
}

protected Element makeGeneralRequestDetailsElement(
final HttpServletRequest req)

{

ArrayList l=new ArrayList();
l.add("Name");
l.add("ganesh");
l.add("Age");
l.add("23");
l.add("Gender");
l.add("Male");
l.add("Date");
l.add("23/02/12");
l.add("Seat No");
l.add("07");
l.add("From");
l.add("Mayiladuthurai");
l.add("To");
l.add("Chennai");
l.add("Ticket Fare");
l.add("240");

Table tab = null;

tab = makeTableFromMap(l);

return (Element) tab;
}

private static Table makeTableFromMap(

final java.util.ArrayList m)
{
Table tab = null;

try
{
tab = new Table(2 /* columns */);
}
catch (BadElementException ex)
{
throw new RuntimeException(ex);
}

tab.setBorderWidth(1.0f);
tab.setPadding(5);
tab.setSpacing(5);
tab.endHeaders();

if (m.size() == 0)
{
Cell c = new Cell("none");
c.setColspan(tab.columns());
tab.addCell(c);
}
else
{

Iterator i = m.iterator();
String strName=null;
while (i.hasNext())
{
strName=i.next().toString();
tab.addCell(new Cell(strName));
}

}

return tab;
}

}

Oracle Database Connection for Java


PART 1

Oracle Download
Install Oracle database and do steps below in image




After select  Go To Database Home Page  a login page appear and then enter your username(what u give at installation time) and password (what u give at installation time)  following page appear




After select sql command  following page appear


Enter and Run your query here .

Table is created .

PART 2

In windows xp Start  --> Control Panel  --> Performance and Maintanenace --> Administratvie Tool --> Data Source(odbc)


  • ODBC Data Source Administrator dialog box appear
  • click Add Button
  • Create New Data Source dialog box appear




select Oracle in XE and Click Finish Button following dialog box appear



Fill information like above image and select ok button.After that your connectOracle created.


PART 3


Create Project and import ODBC jar into library  from your installation path


C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar


Java Coding

INSERT CODING:

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

public class InsertRecord {

public static void main(String[] args) {

String driver="sun.jdbc.odbc.JdbcOdbcDriver";
String cs="jdbc:odbc:connectoracle";
String user = "system";
String pwd = "admin";
 String sqlstmt="INSERT INTO GANESH2 VALUES(7,'ambross')";
 //String sqlstmt1="create table login(ID Number NOT NULL ,Name Varchar2(50),Password Varchar2(50),CONSTRAINT login_PK PRIMARY KEY (ID) ENABLE);";
Connection con = null;
Statement st = null;
try
{
Class.forName(driver);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Driver loaded");
try
{
con=DriverManager.getConnection(cs,user,pwd);
System.out.println("Connected to the Oracle Database");
st = con.createStatement();//creates a Statement object for sending SQL statements to the database.
//st.executeQuery(sqlstmt);
int updatecount=st.executeUpdate(sqlstmt);//return either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing
//System.out.println(updatecount+" row inserted");
}
catch(Exception e)
{
System.out.println(e);
}
try
{
st.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//main()
}//class()



VIEW CODING:


import java.sql.*;

public class oracle {

public static void main(String[] args) {
String driver="sun.jdbc.odbc.JdbcOdbcDriver"; //
String cs="jdbc:odbc:connectOracle"; //connectOracle is the data source name
String user = "system"; //username of oracle database
String pwd = "admin"; //password of oracle database
Connection con = null; //connection variable assigned to null
try
{
Class.forName(driver);// for loading the jdbc driver
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("JDBC Driver loaded");
try
{
  con=DriverManager.getConnection(cs,user,pwd);// for establishing connection with database
Statement s=con.createStatement();
  ResultSet r=s.executeQuery("select * from ganesh2");
while(r.next())
{
  System.out.println("ID:"+r.getInt("id")+" Password:"+r.getString("name"));
}
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Connected to the Oracle Database");
try
{
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//end of main()
}//end of class()






Java Swing Look and Feel

Download Link for Look and Feel Jar:
Download




  • Save NimRODThemeFile in your project source folder and set like below in your main class

            UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");



Simple WebApplication Using Spring

In Netbeans Go File --> New Project

select java webapplication like show below:



Click Next--->click Next-->and select framework in framework window like show below:
Click -->Next

Now its ready for coding part....

Create java class bean.java

--------------------------------------Coding Start-------------------------------------

public class bean {
public void myexample()
{
System.out.println("Hello my spring by ganesh");
}
}
 --------------------------------------Coding End------------------------------------- 

Create Main class main.java

--------------------------------------Coding Start-------------------------------------

public class main {
public static void main(String[] args) {
XmlBeanFactory xml=new XmlBeanFactory(new ClassPathResource("myxml.xml"));
bean b=(bean)xml.getBean("mybean");
b.myexample();
}

}

 --------------------------------------Coding End------------------------------------- 

Create Spring xml Configuration file  myxml.xml like show below:


myxml.xml
 --------------------------------------Coding Start-------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
">
<bean id="mybean" class="bean"/>
</beans>

 --------------------------------------Coding End------------------------------------- 

Run your main class

Ouput :
Hello my spring by ganesh.






 
java4practices © 2013 | Designed by Ganesh Rengarajan