Openshift - Cannot connect to mysql with Java - mysql

I am Harold and Im new in Openshift, Im using below code to connect to MySQL with java through example here
https://www.openshift.com/forums/openshift/no-suitable-driver-found-error,
Unfortunately, I was'nt able to make it work.
At first, it says "No suitable driver found" so I added the mysql-connector to WEB-INF/lib folder and add Class.forName("com.mysql.jdc.Driver");
Then, its not working and not showing error either.
Any help would highly appreciated
import java.lang.String;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class someClass {
public String databaseCall() {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String myVersion = "";
String url = "jdbc:mysql://127.x.xxx.x:3306/testdb"; //make sure that this database name exists;
String user = "admin";
String password = "xxxxxxxxxxxxxxx";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
myVersion = rs.getString(1);
}
} catch (SQLException ex) {
myVersion = ex.getMessage();
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
myVersion = ex.getMessage();
}
}
return myVersion;
}
}

Try reading through this KB article on how to use the default mysql & postgresql connections provided by each Servlet or Application container: https://www.openshift.com/kb/kb-e1086-how-to-use-the-pre-configured-mysqlds-and-postgresqlds-data-sources-in-the-java

Related

Azure Webapp is not updating Azure database for mysql

I have a web application that needs to communicate with azure mysql database. I have included the connection string for jdbc as given in the portal and also modified the connection parameters to allow all inbound IPs. Still the database wont update with the input data. What should I do more?
My connection string is:
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students? useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
My controller servlet code:
package Controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.util.Base64;
import java.sql.*;
import Model.*;
#WebServlet(name = "controller")
#MultipartConfig(maxFileSize = 16177215)
public class controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String v1 = request.getParameter("email");
String v2 = request.getParameter("password");
String v4 = request.getParameter("act");
String v5 = request.getParameter("name");
if(v4.equals("Register"))
{
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
if (v4.equals("SignUp"))
{
Part filePart = request.getPart("photo");
String email="";
String name="";
String base64Image="";
InputStream image= filePart.getInputStream();
newuser r = new newuser();
r.register(v5, v1, v2, image);
try{
PreparedStatement statement = null;
ResultSet resultSet = null;
//Class.forName("com.mysql.jdbc.Driver");
//Connection con = DriverManager.getConnection("jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false", "****", "****");
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
statement = myDbConn.prepareStatement("select * from studentdata where email=?");
statement.setString(1, v1);
resultSet=statement.executeQuery();
while(resultSet.next()) {
email=resultSet.getString("email");
name=resultSet.getString("name");
Blob blob = resultSet.getBlob("photo");
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageBytes);
inputStream.close();
outputStream.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
request.setAttribute("name", name);
request.setAttribute("email", email);
request.setAttribute("image",base64Image);
request.getRequestDispatcher("/UserAccount.jsp").forward(request, response);
}
if(v4.equals("Log In"))
{
request.getRequestDispatcher("/SignIn.jsp").forward(request, response);
}
if(v4.equals("SignIn"))
{
String email="";
String name="";
String base64Image="";
Check c= new Check();
String res=c.checker(v1,v2);
if(res.equals("SUCCESS")) {
try{
PreparedStatement statement = null;
ResultSet resultSet = null;
//sClass.forName("com.mysql.jdbc.Driver");
//Connection myDbConn = DriverManager.getConnection("jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false", "****", "****");
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
statement = myDbConn.prepareStatement("select * from studentdata where email=?");
statement.setString(1, v1);
resultSet=statement.executeQuery();
while(resultSet.next()) {
email=resultSet.getString("email");
name=resultSet.getString("name");
Blob blob = resultSet.getBlob("photo");
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageBytes);
inputStream.close();
outputStream.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
request.setAttribute("name", name);
request.setAttribute("email", email);
request.setAttribute("image",base64Image);
request.getRequestDispatcher("/UserAccount.jsp").forward(request, response);
}
}
if(v4.equals("Sign Out"))
{
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}```
If you haven't turned the "Allow access to Azure services" option to 'ON', kindly turn it On and then verify the connection.
To do this > On the MySQL server blade > open 'Settings' blade >> click 'Connection Security' > Select ON in "Allow access to Azure services", then Save.
I believe when you mentioned 'modified the connection parameters to allow all inbound IPs' - You have added/allowed Firewall rules for App Service 'outbound IP address' list to MySQL 'Connection security'.
Note that Azure Database for MySQL has SSL enabled by default. If your application is not using SSL to connect to the database, then you need to disable SSL on the MySQL server.
Just to isolate, also please to review the connections via "Diagnose and solve problems'

MySQL JDBC connection stop working

String url = "jdbc:mysql://localhost:3306/mysql";
String user = "root";
String pass = "root1";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, pass);
System.out.println("Connected to database");
} catch (Exception e) {
System.out.println(e);
System.out.println("Could not connect to database");
}
Password should be "root". The program does not display the message in the catch block and stops working. Can anyone tell me what happens?
[UPDATE]
I apologise I asked a bad question. The problem is already solved, Thanks. This helps to properly check whether the connection exists.
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
There are three different ways to connect to SQL data base as shown in below code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MySQLConnectExample {
public static void main(String[] args) {
// creates three different Connection objects
Connection conn1 = null;
Connection conn2 = null;
Connection conn3 = null;
try {
// connect way #1
String url1 = "jdbc:mysql://localhost:3306/test1";
String user = "root";
String password = "secret";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
// connect way #2
String url2 = "jdbc:mysql://localhost:3306/test2?user=root&password=secret";
conn2 = DriverManager.getConnection(url2);
if (conn2 != null) {
System.out.println("Connected to the database test2");
}
// connect way #3
String url3 = "jdbc:mysql://localhost:3306/test3";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "secret");
conn3 = DriverManager.getConnection(url3, info);
if (conn3 != null) {
System.out.println("Connected to the database test3");
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}

Can't parse JSON data from URL with only username authentication

I'm using an url in order to read json data but it doesn't work because there is an authentication requested to get access to it using only the username (no login, no password only username). so my code show me the error :
java.io.IOException: Server returned HTTP response code: 401 for URL
My code is working using another URL with no authentication.
Could someone help me or give me and example that do the same thing.
many thanks to you in advance
package javaapplication3;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
public class JSONREST {
public static String callURL(String myURL) {
System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null) {
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
public static void main(String[] args) {
String jsonString = callURL("MY URL");
System.out.println("\n\njsonString: " + jsonString);
try {
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}

how do i use select statment

I want to use select max from a table. I want to use a PreparedStatement. I have a composite primary key which consists of the t.v series and the epo number. When I add new epo it will for table and bring the t.v series code from guidline table the content of all the programs and the code for each and then add to the new table. I want it to get the last epo by getting the max and then increment +1 "an automation app".
So how can I select max where id =??
If you get me its like
pstm2=con.prepareStatement(max);
String max="select MAX(epono) as eponoo from archieve wwhere id like ? ";
This program would be helpful
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SelectRecordsUsingPreparedStatement {
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:databaseName";
String username = "name";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select deptno, deptname, deptloc from dept where deptno > ?";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setInt(1, 1001); // set input parameter
rs = pstmt.executeQuery();
// extract data from the ResultSet
while (rs.next()) {
int dbDeptNumber = rs.getInt(1);
String dbDeptName = rs.getString(2);
String dbDeptLocation = rs.getString(3);
System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

JavaServlet handling SQL errors

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
{
PrintWriter out=res.getWriter();
res.setContentType("text/html");
Connection conn = null;
final String id = UUID.randomUUID().toString();
Map m = req.getParameterMap();
Set s = m.entrySet();
Iterator it = s.iterator();
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "username", "password");
String sqlStr = "insert into transactions (LogID,KeyName,KeyValue) "
+ "values (?,?,?)";
while(it.hasNext()){
Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>)it.next();
String key = entry.getKey();
String[] value = entry.getValue();
try (PreparedStatement stmt = conn.prepareStatement(sqlStr)) {
stmt.setString(1, id);
stmt.setString(2, key);
stmt.setString(3, value[0].toString());
out.println("<html><head><title>Callback Script</title></head><body>");
out.println("<h3>Inserted into the database:</h3>");
out.println("<p>Parameter: " + key + " and Value = " + value[0].toString() + "</p>");
int updateCount = stmt.executeUpdate();
for (Enumeration<String> en = req.getParameterNames(); en.hasMoreElements();) {
String paramName = en.nextElement();
String paramValue = req.getParameter(paramName);
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
out.close();
try {
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
If some error happens with the MySQL Database like wrong credentials, any SQL syntax error at all should be handled and displayed but it is not displaying at all.
Any advice on this or am I coding it wrong?
Cheers
What you have will only print to the logs. To print to the page, use out.print
catch (SQLException ex)
{
ex.printStackTrace(); //print to log
out.print("<br/>Error: " + ex.getMessage()); //print to page
}
On credentials errors you won't want to print the actual message to the page, as it might include the credentials. So you should isolate the part the opens the connection with its own try-catch, which can be nested inside this one.
try
{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "username", "password");
}
catch(Exception ex_connError)
{
out.print("<br/>Error making db connection");
}