Insert and read data mysql - Java JDBC

Java examples for JDBC:MySQL

Description

Insert and read data mysql

Demo Code



import java.sql.*;

public class Mysql {
  public static void main(String[] args) {
    try{//from w  w  w .j  a  v a  2  s .c  om
      Mysql mysql = new Mysql();
      String sql = "create table users(id int primary key not null,name varchar(20),email varchar(20))";
      mysql.execute(sql);
      
      String sql1 = "insert into users values(1,'Jack','Jack@live.com')";
      mysql.execute(sql1);
        String sql="select id,name,email from users";
        ResultSet rs = mysql.select(sql);
        while(rs.next()){
        System.out.println("ID "+rs.getString(1)+"\n"+" "+rs.getString(2)+"\n"+" "+rs.getString(3));
        }
    }catch (Exception e){
      e.printStackTrace();;
    }
  }
  
  private Connection conn = null;
  private String url = "jdbc:mysql://localhost:3306/Jack";
  private String driver = "com.mysql.jdbc.Driver";
  private String user = "Jack";
  private String password = "Jack";

  public Connection create() {
    try {
      Class.forName(driver);
      conn = DriverManager.getConnection(url, user, password);
    } catch (Exception ex) {
      System.out.println(ex);
    }
    return conn;
  }

  public ResultSet select(String sql) {
    Connection conn = create();
    ResultSet rs = null;
    try {
      Statement st = conn.createStatement();
      rs = st.executeQuery(sql);
    } catch (Exception e) {
      System.out.println(e);
    } finally{
      //conn.close();
    }
    return rs;
  }

  public void execute(String sql) {
    Connection conn = create();
    ResultSet rs = null;
    try {
      Statement st = conn.createStatement();
      st.executeUpdate(sql);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
}

Related Tutorials