JDBC




 Java වලින් applications ලියන විට, application code ටික එක තැනක තියනවා සහ database එක තව තැනක තියනවා.Application එක එක server එකක deploy වෙනවා සහ database එක තව  server එකක තියනවා.නමුත් එක හරහා database එකට save කිරීම්,update කිරීම්,read කිරීම් සහ delete කිරීම් කරන්න ඕනේ.එනම් CURD operations  කරන්න ඕනේ(create, update, read, delete).නමුත් මෙම application and database connect වී ඒ දෙකට data හුමාරු කරගැනීම ඉතා අවශ්‍යම දෙයක්.මෙන්න මේ වැඩේ කරගන්න තමා JDBC බාවිතා කරන්නේ.මෙහිදී එක කරන්න ඕනේ විදිහ පහත අකර වලට වෙන් කරන්න පුළුවන්.

Steps

01.import the packages.

     (import java.sql.*)

02. Load and register driver.

    Class.forName("com.mysql.jdbc.Driver")

03. Establish the connection.

  Connection con = DriverManager.getConnection(url,username,password)

04. Execute the query.

05. Process the result.

06. Close the connection.


Sample code

 

public List<Student> getStudentss()throws SQLException{

String url = "jdbc:mysql://localhost:3306/jerseyTutorilas";
String username = "root";
String password = "root";
List<Student>students = new ArrayList<Student>();
try {
Class.forName("com.mysql.jdbc.Driver");    
Connection con = DriverManager.getConnection(url,username,password);

String sql = "select * from student";

Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);

//If Query is “insert" or "update” or “delete” then st.executeUpdate();

while(rs.next()){
     Student st = new Student ();
    st.setName(rs.getString(1));
    st.setPoints(rs.getInt(2));
    students.add(al);
}
} catch (Exception e) {e.printStackTrace();}
finally {con.close();}
returnstudents;
}

Comments

Popular posts from this blog

09.Data Binding.

Database - Topics

02. Spring – Creating spring project clone it with GIT step by step.