In: Computer Science
android studio
-Starting with a basic activity, create a new Java class (use File->New->Java class) called DataBaseManager as in Lecture 5 and create a database table in SQLite, called StudentInfo. The fields for the StudentInfo table include StudentID, FirstName, LastName, YearOfBirth and Gender. Include functions for adding a row to the table and for retrieving all rows, similar to that shown in lecture 5. No user interface is required for this question, t
-Continuing from , follow the example in the lecture notes 5, create a menu (or action bar items) for “Add A Record” and “View Records”. When the menu item “Add A Record” is selected, the program shows a form for entering student information. The data will be added into the database table StudentInfo. When the menu item “View Records” is selected, the program shows all records of all students.
The following program will all the data to the database and also shows all the student records
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseManager {
//connection
private Connection connect() {
String url = "url of database";
Connection con = null;
try {
conn = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return con;
}
public void selectAll(){
String sql = "SELECT StudentID, FirstName, LastName, YearOfBirth ,
Gender FROM StudentInfo";
try (Connection con = this.connect();
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(sql)){
while (rset.next()) {
System.out.println(rset.getInt("StudentID") + "\t" +
rset.getString("FirstName") + "\t" +
rset.getString("LastName")+"\t"+
rset.getString("YearOfBirth")+"\t"+
rset.getString("Gender"));
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
public void insert(int StudentID,String FirstName,String
LastName,String YearOfBirth,String Gender ) {
String sql = "INSERT INTO
StudentInfo(StudentID,FirstName,LastName,YearOfBirth,Gender)
VALUES(?,?,?,?,?)";
try (Connection con = this.connect();
PreparedStatement pstmt = con.prepareStatement(sql)) {
pstmt.setInt(1, StudentID);
pstmt.setString(2, FirstName);
pstmt.setString(3, LastName);
pstmt.setString(4, YearOfBirth);
pstmt.setString(5, Gender);
pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
public static void main(String[] args) {
DatabaseManager db = new DatabaseManager();
//function call to view data from database
db.selectAll();
//funtion call to insert data to database
db.insert("StudentID","FirstName","LastName","YearOfBirth","Gender")
}
}