Write a program to create simple JDBC application to insert and retrieve records from mysql database. code example
Example: Write a program to create simple JDBC application to insert and retrieve records from mysql database.
import java.sql.*;
public class SqlDb {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/student_database";
static final String USER = "root";
static final String PASS = "";
public static void main(String[] args) throws Exception {
try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement s = conn.createStatement();) {
Class.forName(JDBC_DRIVER);
System.out.println("Connected to database...");
s.execute(
"create table student( enroll_no varchar(15) primary key,stud_name varchar(20),stud_address varchar(30) )");
s.execute("insert into student values('181230107017','sudip','navsari')");
s.execute("insert into student values('181230107005','bhavyesh','surat')");
ResultSet rs = s.executeQuery("select * from student");
if (rs != null)
while (rs.next())
{
System.out.println("______");
System.out.println("Enrollnment Id : " + rs.getString(1));
System.out.println("Name : " + rs.getString(2));
System.out.println("Address : " + rs.getString(3));
System.out.println("______");
}
} catch (SQLException err) {
System.out.println("ERROR : " + err);
}
}
}