简体   繁体   中英

How to store data in databse using setters in java

i am developing simple program in which i have to accept personal data of a user and store it in DB. In main class i am accepting the parameters of a person like name,age etc and sending that parameters to SimpleExample class's setter method where it will check for its validity and if data is valid then i want to store it in DB.

this is my Main Class.

public class Football {

    public static void main(String[] args) throws SQLException, Exception {

        Scanner in= new Scanner(System.in);
        String name,education;
        int age;

            SimpleExample s=new SimpleExample();
        System.out.println("Enter your name:");
        name=in.next();
        s.setName(name);
        System.out.println("Enter you Age");
        age=in.nextInt();
        s.setAge(age);
        System.out.println("Enter your Education");
        education=in.next();
        s.setEducation(education);
        s.insert();     

    }

And this is my SimpleExample class.

   public class SimpleExample {


    private String name,education;
    private int age;


    public void setName(String name) {
        this.name = name;
    }
    public void setEducation(String education) {
        this.education = education;
    }
    public void setAge(int age) {
        this.age = age;
    }



    public void insert() throws SQLException,Exception{
        Connection con;
        Statement stmt;

            Class.forName("com.mysql.jdbc.Driver");  
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/person","root","Welcome123"); 
            stmt=con.createStatement();

            String sql="INSERT INTO personalInfo (name,age,education) VALUES ('"+name+"','"+age+"','"+education+"')";
            stmt.executeUpdate(sql);
    }
}

But it is giving me error ClassNotFoundException.

Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) –

Most probably the error is caused because the mysql JDBC driver jar is not present or not added to classpath.

To connect to MySQL from Java, you have to use the JDBC driver from MySQL. The MySQL JDBC driver is called MySQL Connector/J. You find the latest MySQL JDBC driver under the following URL: http://dev.mysql.com/downloads/connector/j .

Then you need to add the JDBC driver to your classpath.

Since it is not clear if you are using an IDE or not, not putting the instructions for the same.

Once you have completed the above steps your program should work. If not try the program below to check if mysql connection is correct.

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCExample {

  public static void main(String[] argv) {

    System.out.println("-------- MySQL JDBC Connection Testing ------------");

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println("Where is your MySQL JDBC Driver?");
        e.printStackTrace();
        return;
    }

    System.out.println("MySQL JDBC Driver Registered!");
    Connection connection = null;

    try {
        connection = DriverManager
        .getConnection("jdbc:mysql://localhost:3306/person","root", "Welcome123");

    } catch (SQLException e) {
        System.out.println("Connection Failed! Check output console");
        e.printStackTrace();
        return;
    }

    if (connection != null) {
        System.out.println("You made it, take control your database now!");
    } else {
        System.out.println("Failed to make connection!");
    }
  }
}

I have tested your code and it is working. So either you are mising some import statement or JDBC jar file or your jar file is not in your classpath .

Try placing the jar file in your ext folder of java installation . inside java\\jre.xx\\lib\\ext folder. If it works after that then it was a classpath problem.Fix that.

Pasting your code with import statement etc(tested code which ran successfully)

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

public class SimpleExample {


    private String name,education;
    private int age;


    public void setName(String name) {
        this.name = name;
    }
    public void setEducation(String education) {
        this.education = education;
    }
    public void setAge(int age) {
        this.age = age;
    }



    public void insert() throws SQLException,Exception{
        Connection con;
        Statement stmt;

            Class.forName("com.mysql.jdbc.Driver");  
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/person","root","Welcome123"); 
            stmt=con.createStatement();

            String sql="INSERT INTO personalInfo (name,age,education) VALUES ('"+name+"','"+age+"','"+education+"')";
            stmt.executeUpdate(sql);
    }
}

Football.java

import java.sql.SQLException;
    import java.util.Scanner;

public class Football {

    public static void main(String[] args) throws SQLException, Exception {

        Scanner in= new Scanner(System.in);
        String name,education;
        int age;

            SimpleExample s=new SimpleExample();
        System.out.println("Enter your name:");
        name=in.next();
        s.setName(name);
        System.out.println("Enter you Age");
        age=in.nextInt();
        s.setAge(age);
        System.out.println("Enter your Education");
        education=in.next();
        s.setEducation(education);
        s.insert();     

    }

} 

For more info look at the links below

http://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/

http://www.vogella.com/tutorials/MySQLJava/article.html

Add mysql JDBC driver jar is not present or not added to classpath

package in.india.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class Football {

    public static void main(String[] args) throws SQLException, Exception {

        Scanner in = new Scanner(System.in);
        String name, education;
        int age;

        SimpleExample s = new SimpleExample();
        System.out.println("Enter your name:");
        name = in.next();
        s.setName(name);
        System.out.println("Enter you Age");
        age = in.nextInt();
        s.setAge(age);
        System.out.println("Enter your Education");
        education = in.next();
        s.setEducation(education);
        s.insert(s.getName(), s.getAge(), s.getEducation());

    }

}

class SimpleExample {

    private String name, education;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEducation() {
        return education;
    }

    public void setEducation(String education) {
        this.education = education;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void insert(String name, int age, String education)
            throws SQLException, Exception {
        Connection con;
        Statement stmt;

        Class.forName("com.mysql.jdbc.Driver");
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/person",
                "root", "Welcome123");
        stmt = con.createStatement();

        String sql = "INSERT INTO personalInfo (name,age,education) VALUES ('"
                + name + "','" + age + "','" + education + "')";
        stmt.executeUpdate(sql);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM