JDBC TUTORIAL

JDBC Tutorial

JDBC PreparedStatement Select example using Mysql

JDBC PreparedStatement Select:

Create a table and insert few records in test database in mysql before executing this program,

Create query

create table student(id int NOT NULL AUTO_INCREMENT, name varchar(100), password varchar(100), PRIMARY KEY(id));

Insert Query

insert into student(name, password) values('candidjava','123345');

Also make sure to add Mysql jar file in classpath

Mysql jar can be downloaded from

http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.6

Example:

package com.candidjava.jdbc;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
public class BasicSelect {
 
  public static void main(String[] args) throws ClassNotFoundException, SQLException {
 
    String n = "candidjava";
 
    Class.forName("com.mysql.jdbc.Driver"); // loads driver
    Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); // gets a new connection
 
    PreparedStatement ps = c.prepareStatement("select * from student where name=?");
    // / select * from user stds where name=?;
    ps.setString(1, n);
 
    ResultSet rs = ps.executeQuery();
 
    while (rs.next()) {
      int id = rs.getInt(1);
      String name = rs.getString(2);
      String pass = rs.getString("password");
 
      System.out.println(id + "   " + name + "   " + pass);
    }
 
  }
 
}
Output:
candidjava 123345