Monday, 17 October 2016

Java File handling


package multispeed;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class myclsmultispeed {

      public static void main(String[] args) throws IOException  {
              BufferedWriter bufferedWriter = null;
              String strContent = "This "+"\t"+"example"+"\n"+" how to write string content to a file";
                  File myFile = new File("C:/MyTestFile.doc");
                  // check if file exist, otherwise create the file before writing
                  if (!myFile.exists()) {
                      myFile.createNewFile();
                  }
                  Writer writer = new FileWriter(myFile);
                  bufferedWriter = new BufferedWriter(writer);
                  bufferedWriter.write(strContent);
                  if(bufferedWriter != null)
                  {
                      bufferedWriter.close();
                  }
          
      }

}




..........................................................................
output:textfile created in c drive and written content in it
..............................................................................
note: public static void main(String[] args) throws IOException
It should be written else there will be error like

Unhandled exception type IOException

Saturday, 8 October 2016

insert data in mysql via Jbutton and JtextField

right click JtextField1 property to change Name of JtextField to txtFname


/*
 * form2.java
 *
 * Created on October 8, 2016, 12:33 PM
 */

package myproject123;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


/**
 *
 * @author  Administrator
 */
public class form2 extends javax.swing.JFrame {
    
    /** Creates new form form2 */
    public form2() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                          
    private void initComponents() {
        txtFname = new javax.swing.JTextField();
        txtLname = new javax.swing.JTextField();
        txtAddress = new javax.swing.JTextField();
        txtSalary = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txtLname.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtLnameFocusLost(evt);
            }
        });

        jButton1.setText("save insert");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(121, 121, 121)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(txtFname, javax.swing.GroupLayout.DEFAULT_SIZE, 129, Short.MAX_VALUE)
                        .addComponent(txtLname)
                        .addComponent(txtAddress)
                        .addComponent(txtSalary)))
                .addContainerGap(150, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addComponent(txtFname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(15, 15, 15)
                .addComponent(txtLname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(20, 20, 20)
                .addComponent(txtAddress, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19)
                .addComponent(txtSalary, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(67, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>                        

    private void txtLnameFocusLost(java.awt.event.FocusEvent evt) {                                   
// TODO add your handling code here:
         try
{
//database without DSN ms access
//String database="D:/mydatabasefolder/employee.mdb";//Here database exists in the current directory
// String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + database + ";DriverID=22;READONLY=true";

 // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  //con=DriverManager.getConnection(url);
  //
  
//database mysql
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dblogin","root","vp");

String sql = "select * from emp";
Statement statement = con.createStatement();
//rs=statement.execute(sql);
                      ResultSet rs = statement.executeQuery(sql);
                       // JOptionPane.showMessageDialog(null, "saved successfully");
//createMessageBox("Inserted Successfully");
                       txtFname.setText(rs.getString("fName"));
txtLname.setText(rs.getString("lName"));
txtAddress.setText(rs.getString("Address"));
txtSalary.setText(rs.getString("Salary"));
}
catch(Exception e)
{
//createMessageBox(e.getMessage());
}

    }                                  

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
// TODO add your handling code here:
        try {
            //database without DSN ms access
            //String database="D:/mydatabasefolder/employee.mdb";//Here database exists in the current directory
            
            // String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + database + ";DriverID=22;READONLY=true";
            
            // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            //con=DriverManager.getConnection(url);
            //
            
            //database mysql
            
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dblogin","root","vp");
            
            
            
            String sql = "Insert Into Emp (FName,LName,Address,Salary) " +
                    "Values ('"+txtFname.getText()+"','"+txtLname.getText()
                    +"','"+txtAddress.getText()+"','"+txtSalary.getText()+"')";
            Statement statement = con.createStatement();
            statement.execute(sql);
            JOptionPane.showMessageDialog(null, "saved successfully");
            //createMessageBox("Inserted Successfully");
            
        } catch(Exception e) {
            //createMessageBox(e.getMessage());
        }
    }                                     
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new form2().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField txtAddress;
    private javax.swing.JTextField txtFname;
    private javax.swing.JTextField txtLname;
    private javax.swing.JTextField txtSalary;
    // End of variables declaration                   
    
}


Find records and fill in JtextFields

/*
 * form11.java
 *
 * Created on October 8, 2016, 1:28 PM
 */

package myproject123;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


/**
 *
 * @author  Administrator
 */
public class form11 extends javax.swing.JFrame {
    
    /** Creates new form form11 */
    public form11() {
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jTextField1.setText("jTextField1");
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextField1FocusLost(evt);
            }
        });

        jTextField2.setText("jTextField2");

        jTextField3.setText("jTextField3");

        jTextField4.setText("jTextField4");

        jButton1.setText("find");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(102, 102, 102)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jTextField4, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE)))
                .addContainerGap(153, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(14, 14, 14)
                .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(14, 14, 14)
                .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(19, 19, 19)
                .addComponent(jButton1)
                .addContainerGap(107, Short.MAX_VALUE))
        );
        pack();
    }// </editor-fold>

    private void jTextField1FocusLost(java.awt.event.FocusEvent evt) {                                      
// TODO add your handling code here:
         try
{
//database without DSN ms access
//String database="D:/mydatabasefolder/employee.mdb";//Here database exists in the current directory
// String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + database + ";DriverID=22;READONLY=true";

 // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  //con=DriverManager.getConnection(url);
  //
  
//database mysql
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dblogin","root","vp");

String sql = "select Fname,Lname,Address,Salary from emp";
Statement statement = con.createStatement();
//rs=statement.execute(sql);
                      ResultSet rs = statement.executeQuery(sql);
                      while (rs.next())
      {
        
        String vfirstName = rs.getString("Fname");
        String vlastName = rs.getString("Lname");
        String vAddress = rs.getString("Address");
        int vSalary = rs.getInt("Salary");

       // Date dateCreated = rs.getDate("date_created");
       // boolean isAdmin = rs.getBoolean("is_admin");
        //int numPoints = rs.getInt("num_points");
        //int id = rs.getInt("id");
        
        // print the results
        //System.out.format("%s, %s, %s, %s, %s, %s\n", id, firstName, lastName, dateCreated, isAdmin, numPoints);

        jTextField1.setText(vfirstName);
        jTextField2.setText(vlastName);
        jTextField3.setText(vAddress);
        jTextField4.setText(vAddress);
      }
                      
        }
                      
catch(Exception e)
{
//createMessageBox(e.getMessage());
}

    }                                     

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
// TODO add your handling code here:
        try
{
//database without DSN ms access
//String database="D:/mydatabasefolder/employee.mdb";//Here database exists in the current directory
// String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + database + ";DriverID=22;READONLY=true";

 // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  //con=DriverManager.getConnection(url);
  //
  
//database mysql
Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dblogin","root","vp");

String sql = "select Fname,Lname,Address,Salary from emp";
Statement statement = con.createStatement();
//rs=statement.execute(sql);
                      ResultSet rs = statement.executeQuery(sql);
                      while (rs.next())
      {
        
        String vfirstName = rs.getString("Fname");
        String vlastName = rs.getString("Lname");
        String vAddress = rs.getString("Address");
        int vSalary = rs.getInt("Salary");
       // Date dateCreated = rs.getDate("date_created");
       // boolean isAdmin = rs.getBoolean("is_admin");
        //int numPoints = rs.getInt("num_points");
        //int id = rs.getInt("id");
        
        // print the results
        //System.out.format("%s, %s, %s, %s, %s, %s\n", id, firstName, lastName, dateCreated, isAdmin, numPoints);
        jTextField1.setText(vfirstName);
        jTextField2.setText(vlastName);
        jTextField3.setText(vAddress);
        jTextField4.setText(vAddress);
      }
                      
        }
                      
catch(Exception e)
{
//createMessageBox(e.getMessage());
}

    }                                     
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new form11().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration
    
}


Saturday, 24 September 2016

mysql connectivity with Java in Swing

mysql connectivity with Java

create database,use,create table in mysql


here mysql username is root and password is vp
You need mysql connectivity .jar driver so Download it from mysql website
mysql-connector-java-3.1.14-bin.jar
Add this .jar file in projects properties by Right click and Java Build path
Add External jars
here add mysql connector java 3.1.14-bin.jar by file browsing in Eclipse
look like this

if u use Netbeans 
,do following 1.Open Netbeans IDE 2.Right-click your Project. 3.Select Properties. 4.On the left-hand side click Libraries. 5.Under "Compile" tab - click Add Jar/Folder button. 6.Select Downloaded "mysql-connector-java-5.1.25-bin.jar" file (Download Connector/J from dev.mysql.com) 7.Click OK Run Again... Its work.

This 2 lines are essential of mysql connectivity

Class.forName("com.mysql.jdbc.Driver");
 

                  Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dblogin","root","vp");

here mysql username is root and password is vp and dblogin is the name of Database and 3306 is port.


how to find user in mysql
just write query in mysql
mysql> select user();
+----------------+
| user() |
+----------------+
| root@localhost |
+----------------+

1 row in set (0.41 sec)

How to find port in Mysql
just write select @port;
or
mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port | 3306 |
+---------------+-------+

1 row in set (0.00 sec)


set startup jframe1 or form1 as start in main method











Jframe frame = new Jframe();
frame.setVisible(true);


or
if you rename Jframe control as form1 then code will be as

 public static void main(String[] args) {
        // TODO code application logic here
        form1 frm=new form1();
        frm.setVisible(true);
    }

------------------------------------------------------------------------
here main will be like this
/*
 * Main.java
 *
 * Created on 
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package cal;

/**
 *
 * @author Administrator
 */
public class Main {
    
    /** Creates a new instance of Main */
    public Main() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        form1 frm=new form1();
        frm.setVisible(true);
    }
    

}