Connecting an Android Java app to a MySQL database using JDBC (Java Database Connectivity) is a common requirement for many applications. JDBC is a Java API that enables Java programs to interact with databases such as MySQL.
In this blog, we will explore how to establish a connection between an Android Java app and a MySQL database using JDBC to create a login screen for email and password.
Step 1: Add JDBC driver to the project using Gradle
The first step is to add the JDBC driver to the project using Gradle dependencies. JDBC driver is a jar file that contains the necessary classes to connect to the database. In this case, we need to download the JDBC driver for MySQL. You can add the driver to your Android project by adding the following lines to the build.gradle (Module:app) file:
dependencies {
// add this line
implementation 'mysql:mysql-connector-java:5.1.49'
}
This will add the MySQL JDBC driver to your project. If you're using a different version of the driver, replace 5.1.49 with the version you're using.
Step 2: Declare permission
Add the following permission in the AndroidManifest.xml file to allow the app to connect to the internet:
<uses-permission android:name="android.permission.INTERNET"/>
Step 3: Connect to the database
To connect to the database, we need to create a connection string that contains the database URL, username, and password. Here's an example of how to create a connection string:
//load the MySQL JDBC driver class dynamically at runtime
Class.forName("com.mysql.jdbc.Driver");
String connectionString = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";
//establish a connection to a MySQL database using the JDBC driver
Connection con = DriverManager.getConnection(connectionString, username, password);
This creates a Connection object that can be used to execute SQL statements on the database. Replace mydatabase, myusername, and mypassword with the actual values for your database.
Step 4: Execute SQL statements
After creating the Connection object, we can execute SQL statements on the database. Here's an example of how to execute a simple SQL query to retrieve data from a table:
// Get the input values from the EditText
String email = binding.editTextEmail.getText().toString();
String password = binding.editTextPassword.getText().toString();
if (isValidEmail(email) && password.length() > 0) {
// Show the progress bar
binding.progressBar.setVisibility(View.VISIBLE);
new Thread(() - > {
try {
//load the MySQL JDBC driver class dynamically at runtime
Class.forName("com.mysql.jdbc.Driver");
//establish a connection to a MySQL database using the JDBC driver
Connection con = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
String query = "SELECT * FROM student WHERE email = ? AND password = ?";
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, email);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
boolean exists = rs.next();
runOnUiThread(() - > {
//Hide the progress bar
binding.progressBar.setVisibility(View.INVISIBLE);
if (exists) {
Toast.makeText(getApplicationContext(), "Login successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Invalid email or password", Toast.LENGTH_SHORT).show();
}
});
con.close();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}).start();
} else {
Toast.makeText(getApplicationContext(), "Please enter a valid email and password", Toast.LENGTH_SHORT).show();
}
Here's a brief explanation of the code:
- First, the code gets the email and password values from two EditText fields.
- It checks if the email is a valid email address and if the password has a length greater than 0.
- If the email and password are valid, it shows a progress bar to indicate that the login process is in progress.
- It creates a new thread to execute the database query.
- Inside the thread, it loads the MySQL JDBC driver class dynamically at runtime using Class.forName("com.mysql.jdbc.Driver").
- It establishes a connection to the MySQL database using the DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD) method, where DB_URL, DB_USER, and DB_PASSWORD are the database connection details.
- It creates a SQL statement to retrieve data from the database table student where the email and password match.
- It sets the email and password values in the prepared statement using stmt.setString(1, email) and stmt.setString(2, password).
- It executes the query using ResultSet rs = stmt.executeQuery().
- It checks if the result set has at least one row by calling rs.next(), indicating that the user exists in the database.
- Finally, it hides the progress bar and shows a Toast message to indicate whether the login was successful or not.
Step 5: Close the connection
After executing the SQL statements, it's important to close the connection to the database to free up resources. Here's an example of how to close the connection:
con.close();
Conclusion
In this blog, we have explored how to connect an Android Java app to a MySQL database using JDBC to create a login screen for email and password. By following the steps outlined above, you can establish a connection between your Android app and a MySQL database and execute SQL statements on the database to implement a login screen.
The full source code for this example can be downloaded from here.