JDBC Prepare Statement to select data from database MySQL
In this tutorial i will show how to read data from database MySQl using PrepareStatement.
You can read in this tutorial to create connection to database MySQL
By Mohd Zulkamal
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)
You can read in this tutorial to create connection to database MySQL
Full Example :
public void readDatabase()
{
String strsql = "SELECT * FROM sysusers WHERE UserID=?";
PreparedStatement prepStatement = null;
Connection dbConn = TestConnectionDb();
String uid = "";
String uemail = "";
try
{
prepStatement = dbConn.prepareStatement(strsql);
prepStatement.setString(1, "developersnote");
ResultSet rs = prepStatement.executeQuery();
while (rs.next()) {
uid = rs.getString("UserID");
uemail = rs.getString("UserEmail");
}
System.out.println(uid);
System.out.println(uemail);
}
catch (SQLException se) {
System.out.println(se.getMessage());
} finally {
try {
if (prepStatement != null) {
dbConn.close();
}
} catch (SQLException se) {
System.out.println(se.getMessage());
}
try {
if (dbConn != null) {
dbConn.close();
}
} catch (SQLException se) {
System.out.println(se.getMessage());
}
}
}
public Connection TestConnectionDb() {
String DbConnectionString ="jdbc:mysql://localhost:3306/blog";
//or you can directly connecto to your database schema like this :
//String DbConnectionString ="jdbc:mysql://localhost:3306/<schema name>";
String User = "root";
String Password = "P@ssw0rd";
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(DbConnectionString, User, Password);
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found");
} catch (SQLException ex) {
System.out.println("Connection Failed! Err Msg : " + ex.getMessage());
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return connection;
}
The Output
You made it, take control your database now!
developersnote
developersnote@gmail.com
By Mohd Zulkamal
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)