I am using a Google Cloud SQL using Java-SQL connector. The issue I am facing is that the connection to database drops unexpectedly. While Googling I came across this question and tried the solution suggested in the same question.
In your console click the project, on the left side click Storage > CloudSQL then click on your database name. You will see an 'Edit' button on top. Click that and scroll down to Activation Policy, change it to Always On and then click save.
But I'm still facing the same issue. Fortunately I have been keeping the logs on Google App Engine and I have attached the snapshot of the exception that occurred while connecting to database.
Gist of the code that I've posted below is used to establish connection to the database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import com.google.appengine.api.utils.SystemProperty;
import static com.google.appengine.api.utils.SystemProperty.environment;
import static com.google.appengine.api.utils.SystemProperty.Environment.Value.Development;
import static com.google.appengine.api.utils.SystemProperty.Environment.Value.Production;
Connection con=null;
SystemProperty.Environment.Value env = environment.value();
if(env == Production)
{
System.out.println("Inside Production Phase");
// Load the class that provides the new "jdbc:google:mysql://" prefix.
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://<my-project-id>:<cloud-sql-instance>/<database-name>?user=<user-name>&password=<database-password>&useUnicode=true&characterEncoding=UTF-8";
}//if
else if(env == Development)
{
System.out.println("Inside Development Phase");
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://127.0.0.1:3306/<database-name>?user=root";
}//else if
con = DriverManager.getConnection(url);
Is anyone facing the same problem, Please help.
Got a temporary fix, used following parameters while making connection to Google Cloud SQL
url = "jdbc:google:mysql://my-app:mysql2/project-name?user=root&password=password&autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
Reference URL: https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html
Related
This question already has answers here:
JDBC connection to MSSQL server in windows authentication mode
(11 answers)
Closed 1 year ago.
I have made a simple java project in which I am attempting to connect to an SQL Server 2019 (Developer Edition) database. However, when I try to do so, I get a login authentication error.
This is my code for the project:
package javafxapplication12;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
/**
*
* #author param
*/
public class FXMLDocumentController implements Initializable {
Connection con;
#FXML
private Label label;
#FXML
private void handleButtonAction(ActionEvent event) {
label.setText("Hello World!");
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=Financials;user=dbo;password=;Trusted_Connection=False;MultipleActiveResultSets=True");
System.out.println("Connected to database !");
}
catch(Exception sqle) {
System.out.println("Sql Exception :"+sqle.getMessage());
label.setText("Failed");
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
However, when I compile this file, I am always getting this error:
Sql Exception :Login failed for user 'dbo'. ClientConnectionId:053ffe3f-aa4b-4c6b-86ee-df080cd91cf6
After reading for some time on Stack, I tried changing the hostname from localhost to myLaptopName, but I am still getting the same error, which leads me to believe that I am going wrong somewhere fundamentally.
Further, as suggested by some other users, I enabled SQL Server and Windows Authentication mode in Server Security settings, but even this didn't help resolve the error.
I am using JDK 1.8 with Netbeans 8.2 and mssql-jdbc-9.4.0.jre8.jar connector to connect to a MS SQL SERVER 2O19 database.
Also, I wanted to add that when I used this query SELECT HOST_NAME() in SSMS, I got the result myLaptopName. This is why I tried replacing localhost with myLaptopName.
Additional Information:
User name: dbo
Password: (no password)
myLaptopName refers to "LAPTOP-UQQOO5F7"
Database details:
SSMS Login Screen:
Update: I tried to change the database name in the link to something different, just to check if that is causing any errors. Inspite of purposefully entering a wrong DB name (eg. FinAANCNAials), I am getting the same error !
From the Screenshots, what I understood is that You are using Windows authentication to connect to the DB from SSMS, but you're using the SQL authentication connection string in the JDBC Code. There are 2 possible solutions
Change the exiting connection string to Windows authentication.
All You've to do is to remove the username and password fields and provide integrated security as True in the existing connection string. Like this
jdbc:sqlserver://localhost:1433;databaseName=Financials;integratedSecurity=true
Create a new SQL Authentication User and provide the credentials in the connection string.
You can create a new SQL user with the required roles in the system and replace the credentials in the existing connection string
Please refer to the following articles for more details
https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15
I noticed that my Play Framework application is not sending the read queries to the read-only MySql slave.
I am using
com.mysql.cj.jdbc.Driver as javax.persistence.jdbc.driver.
jdbc:mysql:replication://write-db-url,read-db-url/db_name as javax.persistence.jdbc.url
The db's are AWS aurora MySQL-compatible with multi-az replica.
I am using hibernate as ORM.
I am using play framework.
Am I missing any configuration/code?
Everything else looks good as stated in question, like jdbc driver and url.
Because in your question very less information is provided related to ORM or JPA and connection codes that you are using.
I'm here by providing a simple main program that you could use debug your issue. Once that is done, focus on your app to see, are you missing same thing.
Here is how JDBC driver determines, whether to connect master or read replica.
If connection mode is read+write, which is default, then it goes to master.
If connection mode is read, then it goes to one of read-replica.
Here officially documentation.
import java.sql.Connection;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Properties;
import java.sql.DriverManager;
public class ReplicationDemo {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
// We want this for failover on the slaves
props.put("autoReconnect", "true");
// We want to load balance between the slaves
props.put("roundRobinLoadBalance", "true");
props.put("user", "foo");
props.put("password", "password");
//
// Looks like a normal MySQL JDBC url, with a
// comma-separated list of hosts, the first
// being the 'master', the rest being any number
// of slaves that the driver will load balance against
//
Connection conn =
DriverManager.getConnection("jdbc:mysql:replication://master,slave1,slave2,slave3/test",
props);
//
// Perform read/write work on the master
// by setting the read-only flag to "false"
//
conn.setReadOnly(false);
conn.setAutoCommit(false);
conn.createStatement().executeUpdate("UPDATE some_table ....");
conn.commit();
//
// Now, do a query from a slave, the driver automatically picks one
// from the list
//
conn.setReadOnly(true);
ResultSet rs =
conn.createStatement().executeQuery("SELECT a,b FROM alt_table");
.......
}
}
Hope it helps.
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
Code snippet:
package dbIntegrationwithJDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Example1 {
public static void main(String[] args) throws SQLException, InterruptedException {
String host = "localhost";
String port = "3306";
Connection con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/mastro1729", "root",
"mysql123");
Statement s = con.createStatement();
ResultSet rs = s.executeQuery("select*from credentials where Scenario='mastro1729'");
System.out.println(rs.getString("Username"));
System.out.println(rs.getString("Password"));
while (rs.next()) {
WebDriver driver = new ChromeDriver();
driver.get("https://login.salesforce.com");
driver.findElement(By.name("usernameOrEmail")).sendKeys(rs.getString("Username"));
driver.findElement(By.xpath("//button[text()='Continue']")).click();
Thread.sleep(3000);
driver.findElement(By.name("password")).sendKeys(rs.getString("Password"));
driver.findElement(By.xpath("//button[text()='Log In']")).click();
Thread.sleep(3000);
}
}
}
Error message:
Exception in thread "main" java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mastro1729
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at dbIntegrationwithJDBC.Example1.main(Example1.java:23)
I'm trying to connect to a MySQL database with JDBC API. I created the MySQL database with mastro1729 on localhost. My code seems correct and I have added mysql-connector-java.jar file to eclipse. While I am trying to integrate my database with JDBC API I am getting java.sql.SQLException at DriverManager.getConnection(); statement. I have tried my best and but I could not be able to resolve the problem.
What am I doing wrong?
It seems there is no suitable JDBC driver found in project classpath...
Download platform independent MySQL JDBC Driver from here.
Extract downloaded .zip
Add executable .jar to your project's classpath.
You have to provide the mysql connector jar file in the classpath.
If you are using maven, import mysql-connector-java dependency.
If not, you can download the binary and provide it in classpath (either via shell or using IDE)
See: https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-installing-classpath.html
My application uses a database based on sqlite-jdbc. When I generate the runnable jar file, connecting to my database works fine however if I let Proguard process my application, it breaks the database connection.
The following code establishes a connection with the database file's path submitted. When using Proguard, the message "Got connection!" is never printed hence getConnection() is stuck.
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
private void loadDatabase(String databaseName) throws SQLException
{
String databaseLibrary = "jdbc:sqlite:";
JOptionPane.showMessageDialog(null, "Getting connection...");
Connection databaseConnection = DriverManager.getConnection(databaseLibrary
+ databaseName);
JOptionPane.showMessageDialog(null, "Got connection!");
// ...
}
Only if the Shrink and Obfuscate options are disabled in Proguard the database connectivity does not break after processing.
Any ideas on how this can be fixed and why this happens?
I try to connect from eclipse emulator android to an sql server using this code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://83.212.240.15:1521/hua;encrypt=false;user=xxxxxx;password=xxx;instance=SQLEXPRESS;";
String username = "xxxxx";
String password = "xxxxx";
conn = DriverManager.getConnection(connString,username,password);
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("insert into picture values('hi');");
conn.close();
but in the database nothing happens.Any ideas?
Thanks in adnvanced
Well this is not directly the answer you are expecting but I would not suggest to access a database directly. Better use e.g. a REST webservice for all database access. So you don't need to make your credentials public.
It is quiet simple so observe the network traffic so it would be realy easy to hack you database server(s).
Anyway if your App is really only for private usage you need to check that you app has the Internet permission for accessing your network ressources.