Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: Beginner Needs Help Inserting row to table

  1. #1
    Junior Member
    Join Date
    Dec 2010
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Beginner Needs Help Inserting row to table

    This is for a class assignment. I have to create a student class with three sub-classes(grad, undergrad, part-time). Within the student class I need to use set and get methods() to capture the data. The student object is then stored in the database. I can access the database. I was able to insert a record @ the cmd prompt using mysql. I can query the database in java and produce a reseultSet. I am unable to add data to the database. I know my get/set methods create the desired student object because I overrode the toString() method and was able to print the object info that was input at the prompts. Any help is greatly apprieciated.

    Thanks,
    Moni
    Student Class
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package registrar;
    import java.sql.*;
    import java.util.Scanner;
    /**
     *
     * @author Moni
     */
    public abstract class Student
    {
        private String firstName;
        private String lastName;
        private int studentID;
        private double gradeAverage;
        String status;
        private String mentorName;
        private String level;
        private String thesisTitle;
        private String thesisAdvisor;
        private String company;
     
        //overloaded constructors
        public Student()
        {
     
        }
        public Student(String first, String last, int id, double gpa,
                String stat, String mentor)
        {
            firstName = first;
            lastName = last;
            studentID = id;
            gradeAverage = gpa;
            status = stat;
            mentorName = mentor;
        }
        public Student(String first, String last, int id, double gpa,
                String stat, String mentor, String lvl, String title,
                String advisor, String comp)
        {
            firstName = first;
            lastName = last;
            studentID = id;
            gradeAverage = gpa;
            status = stat;
            mentorName = mentor;
            level = lvl;
            thesisTitle = title;
            thesisAdvisor = advisor;
            company = comp;
        }
        //getters and setters
        public String getFirstName()
        {
            return firstName;
        }
        public String getLastName()
        {
            return lastName;
        }
        public void setFirstName(String first)
        {
     
            firstName = first;
     
        }
        public void setLastName(String last)
        {
            lastName = last;
        }
        public int getStudentID()
        {
            return studentID;
        }
        public void setStudentID(int id)
        {
            studentID = id;
        }
        public String getStatus()
        {
            return status;
        }
        public void setStatus(String s)
        {
            status = s;
        }
        public double getGPA()
        {
            return gradeAverage;
        }
        public void setGPA(double gpa)
        {
            gradeAverage = gpa;
        }
        public String getMentor()
        {
            return mentorName;
        }
        public void setMentor(String mentor)
        {
            mentorName = mentor;
        }
        public String getLevel()
        {
            return level;
        }
        public void setLevel(String lvl)
        {
            level = lvl;
        }
        public String getTitle()
        {
            return thesisTitle;
        }
        public void setTitle(String title)
        {
            thesisTitle = title;
        }
        public String getAdvisor()
        {
            return thesisAdvisor;
        }
        public void setAdvisor(String advisor)
        {
            thesisAdvisor = advisor;
        }
        public String getCompany()
        {
            return company;
        }
        public void setCompany(String comp)
        {
            company = comp;
        }
        //toString override
        @Override
        public String toString()
        {
            return "student[Registration= " + studentID
                    + firstName + "\t"
                    + lastName + "\t"
                    + gradeAverage + "\t"
                    + status + "\t"
                    + mentorName + "\t"
                    + level + "\t"
                    + thesisTitle + "\t"
                    + thesisAdvisor + "\t"
                    + company + "]";
        }
        //abstract methods
        public abstract double calculateTuition();
     
        public abstract String add();
     
        public abstract boolean update();
     
        public abstract boolean delete();
     
     
     
        public static ResultSet getQuery() throws SQLException
        {
            Statement stmt = null;
            Connection conn = SimpleDataSource.getConnection();
            try
            {
                stmt = conn.createStatement(
                        ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
                String select = "SELECT * from student";
                ResultSet rs = stmt.executeQuery(select);
                System.out.println("Student Records:");
                while(rs.next())
                {
                    System.out.println("Student ID#:\t" + rs.getString("studentID"));
                    System.out.println("First Name:\t" + rs.getString("firstName"));
                    System.out.println("Last Name:\t" + rs.getString("lastName"));
                    System.out.println("Grade Avg:\t" + rs.getString("gpa"));
                    System.out.println("Status:\t" + rs.getString("status"));
                    System.out.println("Mentor:\t" + rs.getString("mentor"));
                    System.out.println("Level:\t" + rs.getString("level"));
                    System.out.println("Title:\t" + rs.getString("thesisTitle"));
                    System.out.println("Advisor:\t" + rs.getString("thesisAdvisor"));
                    System.out.println("Company:\t" + rs.getString("company"));
                }
                stmt.close();
                conn.close();
            }
            catch (SQLException e)
            {
                System.out.println(e.getMessage());
            }
            return null;
        }
     
     
    }
    Graduate sub-class
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package registrar;
    import java.io.File;
    import java.io.IOException;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.Scanner;
    /**
     *
     * @author Moni
     */
    public class Graduate extends Student
    {
        double rate;
        double creditHours = 16;
        public void setGradRate(double rate)
        {
            if (status.equalsIgnoreCase("non-resident"))
            {
                rate = 350;
            }
            else
            {
                rate = 300;
            }
        }
        @Override
        public double calculateTuition()
        {
            this.setGradRate(rate);
            double tution = rate * creditHours;
            return tution;
        }
     
        @Override
        public String add()
        {
            Connection conn = null;
            Statement stmt1 = null;
            try
            {
               Scanner in = new Scanner(System.in);
     
               conn = SimpleDataSource.getConnection();
               stmt1 = conn.createStatement();
     
               System.out.print("Enter the Student ID #: ");
               int id = in.nextInt();
               System.out.print("Enter First Name: ");
               String first = in.next();
               System.out.print("Enter Last Name: ");
               String last = in.next();
               System.out.print("Enter Student Status: ");
               String stat = in.next();
               System.out.print("Enter Mentor's Name: ");
               String mentor = in.next();
               double gpa = 3.5;
               System.out.print("Enter the Student's Level: ");
               String lvl = in.next();
               System.out.print("Enter the Thesis Title: ");
               String title = in.next();
               System.out.print("Enter the Thesis Advisor's Name: ");
               String advisor = in.next();
               System.out.print("Enter the Company's Name: ");
               String comp = in.next();
               //set variables
               this.setStudentID(id);
               this.setFirstName(first);
               this.setLastName(last);
               this.setGPA(gpa);
               this.setStatus(stat);
               this.setMentor(mentor);
               this.setLevel(lvl);
               this.setTitle(title);
               this.setAdvisor(advisor);
               this.setCompany(comp);
     
               stmt1.execute("INSERT into student"
                       + "(studentID, firstName, lastName, gpa, status, mentor,"
                       + "level, thesisTitle, thesisAdvisor, company)"
                       + "VALUES ('"
                       + getStudentID() + "','"
                       + getFirstName() + "','"
                       + getLastName() + "','"
                       + getGPA() + "','"
                       + getStatus() + "','"
                       + getMentor() + "','"
                       + getLevel() + "',"
                       + getTitle() + "','"
                       + getAdvisor() + "','"
                       + getCompany() + "')");
              // try
              // {
             //      stmt1.execute(addStudent);
                   //System.out.println("1 record added");
     
              // }
              // catch(SQLException s)
              // {
               //    
              //     System.exit(0);
              // }
               stmt1.close();
               conn.close();
            }
            catch(Exception e)
            {
                System.out.println("SQL statement is not executed!");
            }
            return null;
     
        }
     
        @Override
        public boolean update() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
     
        @Override
        public boolean delete() {
            throw new UnsupportedOperationException("Not supported yet.");
        }
     
    }
    Registration (main)
    /*
     * This is the main program that manipulates and queries the student
     * database table.
     * APA References:
     * [url=http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html]Using Prepared Statements (The Java™ Tutorials > JDBC(TM) Database Access > JDBC Basics)[/url]
     * retrieved March 5, 2011a
     *
     */
     
    package registrar;
    import java.io.File;
    import java.io.IOException;
    import java.sql.*;
    import java.util.Scanner;
    /**
     *
     * @author Moni
     */
    public class Registration
    {
     
        /**
         * Finds and returns a list of students registered
         */
        public static void main (String[] args) throws
                IOException, SQLException, ClassNotFoundException
        {
            //SimpleDataSource.init(args[0]);
     
            Scanner in = new Scanner(System.in);
     
            System.out.print("Welcome To Student Records. Select Action:"
                    + "[A]ADD, [D]DELETE, [E]EDIT: ");
            String action = in.next();
     
            if(action.equalsIgnoreCase("A"))
            {
     
               System.out.print("Enter Student Type: "
                       + "[G]Grad/[P]Part-time/[U]Undergrad: ");
               String type = in.next();
               //create graduate object to add
               if(type.equalsIgnoreCase("g"))
               {
                   Graduate grad = new Graduate();
     
                   // add to the database
                   grad.add();
                   //String gradString = grad.toString();
                   //System.out.println(gradString);
                   //System.out.println(grad.getFirstName());
     
               }
               //create undergrad object to add
               else if(type.equalsIgnoreCase("u"))
               {
     
               }
            }
     
     
            ResultSet query = Student.getQuery();
            System.out.print(query);
     
        }
     
     
     
    }
    Last edited by copeg; March 9th, 2011 at 09:17 PM.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Beginner Needs Help Inserting row to table

    For future reference, please see the following link for how to correctly use the highlight/code tags (I've edited your post for you) Announcements - What's Wrong With My Code?

    What exactly is the problem? You mention not being able to insert using jdbc, but does the statement execute and/or are there exceptions thrown?

  3. #3
    Junior Member
    Join Date
    Dec 2010
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Beginner Needs Help Inserting row to table

    Thanks for editing my post correctly. I am thorowing my sql exception in the add() method (located in the Graduate sub-class), it is catching exception e "SQL Statement not executed!". I am unsure if I am unable to add new data to the table because my java code/syntax for inserting into the table is incorrect. The assignment states that I have to use the get/set methods to store the variable information of my student object. I thought I was correctly calling back that information (in the grad-subclass) "stmt1.execute(INSERT into student ......)". Will the mysql language not allow me to call my get*() methods instead of using variables?

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Beginner Needs Help Inserting row to table

    Rather than printing out a custom statement when an exception is thrown, call printStackTrace() on the Exception object - this is MUCH more informative and typically will give a detailed description of the error. Recommend seeing what that prints out and posting it here.

  5. #5
    Junior Member
    Join Date
    Dec 2010
    Posts
    9
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: Beginner Needs Help Inserting row to table

    [ERROR]com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorEx ception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '','Theory','none')' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInsta nce(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newI nstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Construc tor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:40 6)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:1030)
    at com.mysql.jdbc.SQLError.createSQLException(SQLErro r.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:3491)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.ja va:3423)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:19 36)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java :2060)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionIm pl.java:2536)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionIm pl.java:2465)
    at com.mysql.jdbc.StatementImpl.execute(StatementImpl .java:734)
    at registrar.Graduate.add(Graduate.java:79)
    at registrar.Registration.main(Registration.java:48)[/ERROR]

    line 79 is the stmt1.execute(....insert into db table...)
    line 48 calls the method that holds the stmt1.execute code.
    My question is this: is MySQL not able to get the variable values from my get*() methods?

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Beginner Needs Help Inserting row to table

    My question is this: is MySQL not able to get the variable values from my get*() methods?
    No....SQL has nothing to do with those gets (that all happens on the java side). The exception is fairly descriptive: your SQL syntax is incorrect. My advice to debug is to first create a string that represents your query, then print that query out using System.out.println to see what it actually looks like - there is a syntax error that is not evident from the code itself and printing it out will allow you to see the query (and even test it directly with MySQL)

Similar Threads

  1. Check for duplicates before inserting into database
    By igor0203 in forum JDBC & Databases
    Replies: 1
    Last Post: December 2nd, 2010, 09:04 AM
  2. Beginner Problem
    By nve5009 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 19th, 2010, 11:29 AM
  3. Inserting Image Help
    By Bradshjo in forum What's Wrong With My Code?
    Replies: 1
    Last Post: September 22nd, 2010, 12:50 PM
  4. Beginner - Help with my code.
    By eddross in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 12th, 2010, 09:30 AM
  5. I need a help ! i am beginner
    By yinky in forum Java Theory & Questions
    Replies: 3
    Last Post: September 30th, 2009, 07:22 AM