Home Answers Viewqa JDBC java with mysql

 
 


Subrat Patnaik
java with mysql
0 Answer(s)      2 years and 7 months ago
Posted in : JDBC

Hi, Here is my code:

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;

public class civil_fst extends JFrame implements ItemListener, ActionListener{

    static Connection con;
    static Statement stmt;
    static ResultSet rs;
    static ResultSetMetaData rsMeta;

    String query;
    String ref="",rollno="";
    String[] heads;
    int[] stChange;
    String[][] cubeData;
    int rows, cols, coo;

    /** Creates new form civil_fst */
    public civil_fst() {
        initComponents();

        con  = null;
        stmt = null;
        rs = null;
        rsMeta=null;

        query="SELECT *  FROM  civilfattnd order by Regd_No";
        rows=0;
        cols=0;
        coo=0;

        try
            {
                Class.forName("com.mysql.jdbc.Driver");
                con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
                con.setAutoCommit(true);
                stmt=con.createStatement();

                rs=stmt.executeQuery(query); //execute the query and get resultset(rs)
                rsMeta=rs.getMetaData(); //get rs metadata
                cols=rsMeta.getColumnCount(); // get number of columns
                coo=cols-1;

                while(rs.next()) {              // get rows in resultset
                  ++rows;
               }
                heads = new String[cols];           // initialize col heads

                for (int i = 0; i < cols; i++) {        // getting colums  heading in heads[]
                    int colindex=i+1;               // column indexes start from 1
                    heads[i] = rsMeta.getColumnName(colindex);
                }
                stChange = new int[rows];           //to save value when status changed


                rs=stmt.executeQuery(query);        // execure query and get resultset (rs)
                cubeData = new String[rows][cols];          // initialize table data

                int j=0; int k=0;               // function to get resultset data
                while(rs.next())
                {
                    if(j<=rows)
                    {
                        int h=1;
                        if(k<=cols)
                        {
                            for(int cc=0;cc<cols; cc++)
                            {
                                cubeData[j][k]=rs.getString(h);
                                h++;
                                k++;
                            }
                        }
                        k=0;h=0;
                        j++;
                    }
                }
        }
        catch(Exception ex)
         { System.err.println(ex.getMessage());
           ex.printStackTrace(System.err);
         }

        cp.setLayout(new GridLayout(rows+2,cols)); // 1 additional Row of Col heading, 1 for save btn


        //---------------- Adding heading in CP---------------------------------------

    for (int i = 0; i < cols; i++) {
        JLabel jl = new JLabel(" [ "+heads[i]+" ] ");
        jl.setOpaque(true);
        jl.setBackground(Color.gray);
        jl.setForeground(Color.white);
        cp.add(jl);

    }

    //---------------- Adding data ---------------------------------------


    for(int j=0; j<rows; j++){
        for(int k=0; k<cols; k++)
            {
             if(k==(cols-1))
                {    ref="-"+j+"."+k;
                    String status=cubeData[j][k]+ref;
                    stChange[j]=Integer.parseInt(rollno); // save previously selected status of each                                               // row(student) + array address
                    Choice jc = new Choice();

                        jc.add("Present"+ref);
                        jc.add("Leave"+ref);
                        jc.add("Absent"+ref);


                        jc.select(status);

                            jc.addItemListener(this);
                        cp.add(jc);

                }
             else
              cp.add(new JLabel(cubeData[j][k]));
              rollno=cubeData[j][k];
            }
        }
    addSaveButton();
    }
//------------------------SAVE BUTTON-----------------------------------------

    public void addSaveButton(){
        JButton saveBtn = new JButton(" ::::  Save  :::: ");
        saveBtn.addActionListener(this);
        cp.add(saveBtn);
    }




    //------------------------Item Listener -----------------------------------------
  public void itemStateChanged(ItemEvent ie) {
    String s = (String)ie.getItem();

    String ro = s.substring(s.indexOf("-")+1,s.indexOf("."));
    String co = s.substring(s.indexOf(".")+1,s.length());

    String stats = s.substring(0,s.indexOf("-"));

    int roo = Integer.parseInt(ro);
    coo = Integer.parseInt(co);

    cubeData[roo][coo]=stats;
  }

    //------------------------Action Listener-----------------------------------------
  public void actionPerformed(ActionEvent ae) {

    try{
        String create="CREATE TABLE civ_fourth (`Name` VARCHAR(50), `Regd_No` INT, `Status` VARCHAR(20) NOT NULL)";
                con=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
                stmt.executeUpdate(create);
                //con.close();
            }
            catch(Exception ex)
             { System.err.println(ex.getMessage());
             ex.printStackTrace(System.err);
             }

             try{
                for(int j=0; j<rows; j++)
        {
            //String updt = "update civilfattnd set Status= '"+cubeData[j][coo]+"' where Regd_No="+stChange[j];
                        String ins="INSERT INTO civ_fourth (`Regd_No`, `Status`) VALUES('"+stChange[j]+","+cubeData[j][coo]+")";

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

            //stmt.executeUpdate(updt);
                        PreparedStatement ps=con.prepareStatement(ins);
        }
            //this.con.commit();
                        con.setAutoCommit(true);
            System.out.println("Records updated..!");
            con.close();

    }catch(Exception ex)
     { System.err.println(ex.getMessage());
       ex.printStackTrace(System.err);
     }
  }
    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        cp = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("...:::Civil First Sem:::...");
        setBounds(new java.awt.Rectangle(250, 250, 0, 0));
        setLocationByPlatform(true);

        cp.setBackground(new java.awt.Color(154, 95, 125));

        javax.swing.GroupLayout cpLayout = new javax.swing.GroupLayout(cp);
        cp.setLayout(cpLayout);
        cpLayout.setHorizontalGroup(
            cpLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 539, Short.MAX_VALUE)
        );
        cpLayout.setVerticalGroup(
            cpLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 308, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(cp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(cp, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new civil_fst().setVisible(true);
            }
        });
    }

But this code create a new table but problem is its not execute the query for insert. I tried a lot but not successes . Please help me

View Answers









Related Pages:
mysql
you need to download the mysql-connector jar file for connecting java program from mysql database.......   Hi friend, MySQL is open source database... is the link for the page from where you can understand how to Download and Install MySQL
java-mysql
java-mysql  how i retrive all the values of a table in mysql to java forms or java table
Java and MySQL
Java and MySQL   I am doing a project on an accounting system. I need to know to things: How do I write reports using information in an MySQL database . How get multiple MySQL database rows and assign them to variables r
Java and Mysql
Java and Mysql  Sir, I want to connect my java program with mysql server (mysql server is situated on another windows machine ) ??? ???? ?????   Put mysql jar file in your jdk lib and set the classpath. After
mysql-java
mysql-java   i try to execute this code stmt1.executeUpdate("insert... the manual that corresponds to your MySQL server version for the right syntax to use...) at Mydb.main(Mydb.java:111) Java Result: 1 please help me to find the error  
java & mysql
java & mysql  I wrote the code as shown below, i am getting the error... to your MySQL server version for the right syntax to use near '' at line 1" my...("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql
java & mysql
java & mysql  I wrote the code as shown below, i am getting the error... to your MySQL server version for the right syntax to use near '' at line 1" my...("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql
java & mysql
java & mysql  I wrote the code as shown below, i am getting the error... to your MySQL server version for the right syntax to use near '' at line 1" my...("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql
java & mysql
java & mysql  I wrote the code as shown below, i am getting the error... to your MySQL server version for the right syntax to use near '' at line 1" my...("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql
java & mysql
java & mysql  I wrote the code as shown below, i am getting the error... to your MySQL server version for the right syntax to use near '' at line 1" my...("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql
MySql,java
MySql,java  In MySQL table i am adding the fields of name,photo,video,age,category.in the category i have some subjects.if one person login into my-site the he upload the one video under one subject.then i want the following
java with mysql
java with mysql  Hi, Here is my code: import java.awt.*; import...=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root...` VARCHAR(20) NOT NULL)"; con=DriverManager.getConnection("jdbc:mysql
connection with MySQL to java.
connection with MySQL to java.   how to connect MySQL database with jsp
Image in mysql
Image in mysql  Hi. How to insert and retrieve images in mysql db using JSP or JAVA Servlet? Thanks in advance
JAVA & MYSQL - JDBC
JAVA & MYSQL  How can we take backup of MySQL 5.0 database by using...;Hi Friend, Please visit the following page for working example of MySQL backup. This may help you in solving your problem. www.roseindia.net/mysql/mysql
mysql jsp - Java Beginners
mysql jsp  how to insert values to mysql? i want to insert values from a combo box to mysql... how to perform that. pls help me in urgent.  Hi friend, Plz give full source code where you having the problem
Mysql & java - JDBC
Mysql & java  Hi guys, please help! I'm new to mysql, I want to connect to mysql 5.1 using java. But it shows error about: Class.forName...) { System.out.println("MySQL Connect Example."); Connection conn = null
jsp, mysql - Java Beginners
jsp, mysql  i want to store / insert the selected value in the combo box (jsp), into the mysql. how to do it?... pls help me in urgent
mysql query
mysql query  how do transfer into the excel data to my sql  ... the mysql connection in your php and store the list values inside the mysql database using the loops. For more illustration, we are providing you java example
Connecting to MYSQL Database in Java
Connecting to MYSQL Database in Java  I've tried executing the code...("MySQL Connect Example."); Connection conn = null; String url = "jdbc:mysql://localhost/"; String dbName = "textbook"; String driver
mysql with jsp - Java Beginners
mysql with jsp  i wanted to insert a combo box value to mysql table usgin jsp. how to perform that. can anybody help me in urgent.  Hi friend, Code to help in solving the problem : Select
jsp_mysql
SELECTED columns from mysql table which are given dynamically through checkboxes.../TR/html4/loose.dtd"> <%@ page language="java" import="java.sql.*"%> <html> <head><title>Read from mySQL Database</title>
jsp and mysql
;option value="C#">C#</option> <option value="Java">Java<...").newInstance(); Connection con = DriverManager.getConnection("jdbc:mysql
About MYSQL
About MYSQL  is it possible to upload the video on mysql database   1)page.jsp: <%@ page language="java" %> <HTML> <... connectionURL = "jdbc:mysql://localhost:3306/test"; ResultSet rs = null
JBBC ,MYSQL ND JAVA
JBBC ,MYSQL ND JAVA  /* import java.sql.*; * import... Class.forName("java.sql.Driver"); con=DriverManager.getConnection("jdbc:mysql...=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root"); st
how to migrate java db to mysql
how to migrate java db to mysql  I have an aplication,for migrating java db to mysql db.how it will done
Servlets mysql connectivity
Servlets mysql connectivity  please tell me the steps to connect mysql with java servlets using connector j
Getting mysql table in textbox
Getting mysql table in textbox  how to get mysql table values into textbox in java using ajax and servlets
Java-mysql coding - Java Beginners
Java-mysql coding  Dear Sir, Suppose I have Employee master file in Mysql table format & I want to update that file thru JavaSwing Input format... employee joins, his master details are putted in Java-Swing Form, how I can insert
MySQL restore function in java - JDBC
MySQL restore function in java  I would like to import to a database .sql file. It is possible with the use of mysql administrator, however I would like to do the same with the use of java.Is it possible?If yes, how to do
image stored in mysql
image stored in mysql   how does an image store in mysql using java. gime an exam. code. thanks..   Insert Image in MySQL
jdbc driver for mysql - Java Beginners
jdbc driver for mysql  I need jdbc driver program for connecting java progrma to mysql. Please any one send me the url to download the driver... of jdbc-mysql database connectivity and idea about jdbc and mysql driver
MySql ClassNotFoundException - JDBC
install in linux any software making connection between java and MySQL. Or how can i...MySql ClassNotFoundException  Dear sir, i am working in Linux platform with MySQL database , actually i finished all installation in MySQL
mysql table extract
mysql table extract  Hello friends!! I am a trainee. I am learning connectivity of java with MYSQL. I want to extract table from mysql so that I can access it on another computer. I want to attach mysql table to my java NETBEANS
Mysql Date To Java Date
Mysql Date To Java Date       Mysql Date To Java Date retrieve the records from Mysql and display... 'Mysql Date To Java Date'. To understand and grasp the example we create a table
netbeans with mysql and tomcat
netbeans with mysql and tomcat  Hi. I have to run a JSP or JAVA file in netbeans with mysql database and tomcat server 7.0. But while the page loading itself it say error. ClassNotFoundException: com.mysql.jdbc.Driver. How
MySQL connectivity - JDBC
MySQL connectivity  hi all, i am not able to connect Mysql to java ..as i connect it ..i am getting the error ..saying classNotFoundException... to "com.mysql.jdbc.Driver" class not found In the lib folder "mysql-connector-java-5.0.6-bin.jar
java code for registration and login pages, mysql as a bankend.
java code for registration and login pages, mysql as a bankend.  please send me the java code for registration and login pages and to store the data in mysql
What is MySQL
, PHP, Java , Delphi etc. are available to connect to MySQL database. MySQL... What is MySQL       MySQL is a open source Relational Database Management System. MySQL is very fast
Java+JMX+Resin+MySQL - RMI
Java JMX Resin MySQL  I would like to a standalone JAVA program that can get the details about the session & threads and print it on screen or write.... It should be possible to invoke the JAVA class as and when needed to update
Login authentication & mysql - Java Beginners
Authentication with MySql using Java Swing: 1)Create a java class... their personal account with the username and password, must save it in database (MySQL... with the data in database. I am newbies to java & learning java by myself but I
MySQL Books
MySQL Books       List of many MySQL books. MySQL Books Hundreds of books and publications related to MySQL are in circulation that can help you get the most of out MySQL. These books
website creation using java and mysql - Java Beginners
website creation using java and mysql  i am going to create a website for some company using java and mySql... i dont know the procedure to create a website.can anybody give me the steps what i have to follow
MYSQL
MYSQL  How to create time and date based trigger in mysql   MySQL Time Trigger
mysql
mysql  how to open\import table in .dbf format in mysql
MySQL How to Topic
using Java? http://www.cs.columbia.edu/~crf/mysql/index.htm   ... password in MySQL    How do I access MySQL from Java...#java   How do I access MySQL from Python? http
database connectivity using mysql
database connectivity using mysql  java file: eg1.java package eg...[]) throws SQLException { try { String connectionURL = "jdbc:mysql... seconds) I am using Netbeans 5.5, mysql server 5.0, to get data from table
MySql
MySql  what is default password of mySql, and how i configure mySql.   Hi, If you are installing MySQL on windows then you will have to provide the Password for the user root at the installation time. You may try
not able to connect to mysql using.. jdbc
not able to connect to mysql using.. jdbc   i am not able to connect to mysql using jdbc .. is there any classpath that i need to set..because i am using mysql-connector-java jar file..to connect to mysql.. Pls provide the steps

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.