I have already created the data base. Just looking for how to write the function
ID: 3687265 • Letter: I
Question
I have already created the data base. Just looking for how to write the function.
1) Create a database with the following requirements:
- Name: userdb
- Table: usertb
- Fields: username, password
Add these 2 records to the table:
- userone, pwo
- usertwo, pwt
2) Write and test a function that has the following requirements:
- the function accepts 2 variables (username & password)
- the function connect to the database created in section 1 (above)
- the function returns true if the username exist in the database and matches its password else, it returns false
- remember to close the connection to the database before the return so other parts of this program will work properly
Explanation / Answer
As you said data base was already created .. here is the function to validation ,,
import java.sql.*;
import java.util.Scanner;
public class CheckData {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/usertb";
// Database credentials
static final String USER = "john";
static final String PASS = "iamback";
public static void checkExistInDatabase(String username, String password){
Connection conn = null;
Statement stmt = null;
try{
//Setting up driver
Class.forName("com.mysql.jdbc.Driver");
//connection .. opening
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected to database ... ");
//stattement created
stmt = conn.createStatement();
String sql = "SELECT userName, password FROM usertb";
ResultSet rs = stmt.executeQuery(sql);
//getting results in result set
while(rs.next()){
//Retrieve by column name
string uname = rs.getString("username");
String pword = rs.getString("password");
if(uname.equals(username) && pword.equsls(password)){
System.out.println("Account details found");
}
else{
System.out.println("Account details not found");
}
}
rs.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
public static void readUserNameAndPwd(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter username: ");
String username = sc.nextLine();
System.out.println("Enter password: ");
String password = sc.nextLine();
checkExistInDatabase(username,password);
}
public static void main(String[] args) {
readUserNameAndPwd();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.