android - sql server - connection either null or no suitable driver found - java

My connection java file contains :
try {
Log.i("Login", "Establishing Connection...");
// SET CONNECTIONSTRING
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
Log.i("JDBC","found");
Connection DbConn = DriverManager.getConnection("<connection_string>");
Log.i("Login","Connected");
Statement stmt = DbConn.createStatement();
ResultSet insert = stmt.executeQuery("insert into UserLogin(username, password) values (admin, admin);");
ResultSet reset = stmt.executeQuery(" select * from UserLogin ");
Toast.makeText(this, reset.getString(1), Toast.LENGTH_SHORT).show();
DbConn.close();
// go to newsfeed
} catch (Exception e) {
Log.e("Error connection","" + e.getMessage());
}
When my connection string contains:
jdbc:jtds:sqlserver://, I gets error in connection :null,and when it's
jdbc:sqlserver://, I gets error in connection:no suitable driver found.
I'm trying to connect Android with Azure SQL DB.
I've seen Question1, Question2, Question3, Question4.
No Answer.

#NiravMadariya, The JDBC connection string with jTDS shoule be jdbc:jtds:sqlserver://<server>:<port>/<database>, please see the jTDS FAQ which includes URL format and the reason for No suitable driver exception.
Note, if you are using the JTDS JDBC driver for Auzre SQL DB, then you will need to add ssl=require to the URL of the connection string as like this jdbc:jtds:sqlserver://<server>:<port>/<database>?ssl=require.
Meanwhile, using Microsoft JDBC Driver for SQL Server is a recommend way for Azure SQL DB, please see https://azure.microsoft.com/en-us/documentation/articles/sql-database-develop-java-simple/.

Related

Unable to connect to mysql server because of "java.sql.SQLNonTransientConnectionException: Could not create connection to database server"

Here is the code which i use to connect to the server:
String records = "",error="";
void connectToDatabase() {
try {
String ip = "";//mysql server ip(removed due to privacy reasons)
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection("jdbc:mysql://" + ip +":3306/androiddb?user=andro&password=andro");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM mainTable");
while (resultSet.next()) {
records += resultSet.getString(1) + " " + resultSet.getString(2) + "\n";
}
System.out.println(records);
} catch (Exception e) {
error = e.toString();
System.out.println(error);
}
}
Exception i get:
java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
my.ini file:
[mysqld]
basedir=C:\\Program Files\\MySQL\\MySQL Server 8.0
datadir=C:\\Program Files\\MySQL\\MySQL Server 8.0\\data
bind-address = *mysql server ip*
I use mysql server 8.0.24 and jdbc 8.0.24
UPD: I don't know why but it started to work after i installed jdbc 5.0.41
I got the same error with MySQL 8.0.23 and jdbc connector 8.0.24. It seems to me that the connection is successful by adding the params `&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=GMT%2B9:00&rewriteBatchedStatements=true&connectionTimeZone=SERVER' at the string. See the Release Notes for details.
MySQL :: MySQL Connector/J 8.0 Release Notes :: Changes in MySQL Connector/J 8.0.23 (2021-01-18, General Availability)
I hope it is helpful.

"Could not create connection to database server" netbeans google cloud sql error

I am trying to create my first API using java httpServlet and netbeans which will be connected to a database on google cloud based its examples and documentations. I have not created the database, but I was given the necessary credentials and vars to create the connection. So I have downloaded the project from github, and when I tried to open it from netbeans there was some issues concerning dependencies ... So I resolved them, I replaced the credentials with their values and run the project; Unfortunately an error was thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. I made some searches but did not get any result... Could it be an error from this code ? an error from database security if it was invisible on cloud? Any help is more than appreciated.
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
String instanceConnectionName = "<foo:foo:bar>";
String databaseName = "myDatabaseName ";
String username = "myUsername ";
String password = "<myPass>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
databaseName,
instanceConnectionName);
try{
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
/* try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("select * from wf_accounts;");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}*/
}catch(Exception ex){
System.out.println("Error: " + ex.toString());
}
Update
Same error was thrown when I did this:
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
"",
"");
Any hints?
First you have to check whether the mysql server is running on.If you are Windows user you can simply
Go to Task Manager
Go to Services
then search for your Mysql server(eg:for my case its MYSQL56)
then you will see under the status column it says its not running
by right clicking and select start
If it's already running then you have to do as in mysql Documentation,
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem

Java Connection String to Oracle Cloud Database

I had problem when connecting to Oracle Cloud Database from java code.
I have no problem connecting other non-cloud oracle databases.
I can connect to the Oracle Cloud Database with sql tools, except from the java codes.
The hostname, username and password is correct one, i don't reveal the real username and password.
Error: java.sql.SQLException:
SQLException: SQLState(null) vendor code(17002)
java.sql.SQLException: Io exception: Oracle Error ORA-12650: No common encryption or data integrity algorithm
My code as following:
String dbURL = "jdbc:oracle:thin:#192.133.133.23:1521:ORCL";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(dbURL, "username1", "password");
}catch(Exception)
{
e.printStacktrace();
}
/**
* The below one is for oracle thin client
Its worked for the ojdbc6 driver.
*/
public Connection conCheck() {
Connection con=null;
try { //step1 load the driver class
Class.forName("oracle.jdbc.OracleDriver");
Properties props = new Properties();
props.put("oracle.net.encryption_client", "REQUIRED");
props.put("oracle.net.encryption_types_client", "( " + AnoServices.ENCRYPTION_AES256 + "," +AnoServices.ENCRYPTION_AES192 + ")");
props.put("oracle.net.crypto_checksum_types_client", "( SHA1 )");
props.put("user", "username");
props.put("password","password");
//step2 create the connection object
con=DriverManager.getConnection( "jdbc:oracle:thin:#host:port:serveiceid",props);
System.out.println("Con"+con);
}catch(Exception e) {e.printStackTrace(); }
return con;
}
Seems like changing syntax in your connection string to lookup SERVICE_NAME instead of SID must help you connect your database.
String dbURL = "jdbc:oracle:thin:#192.133.133.23:1521/ORCL";
Additional Read : Thin-style Service Name Syntax
If this as well doesn't help, then would suggest to add below 2 lines to your sqlnet.ora in database.
SQLNET.CRYPTO_CHECKSUM_TYPES_CLIENT= (SHA1)
SQLNET.CRYPTO_CHECKSUM_CLIENT = requested
First mandatory check is to verify the oracle jdbc version. if you use incompatible version,we will get this kid of errors.

Get the connected mysql database name (JDBC)

How can get the name of the database name from connection object
try {
this.ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/amger");
} catch (NamingException ne) {
}
Connection conObj = ds.getConnection();
How do I get that Database name from con
Probably the most straightforward way to get the database name from the JDBC Connection object itself is via the getCatalog() method:
Connection#getCatalog()
However, as Konstantin pointed out in his comment below, that value will not change if the current MySQL database is changed by issuing a USE dbname statement.
getCatalog() might still be useful in an application that
does not change databases, or
does things "The JDBC Way" by using setCatalog() to change the current database,
but for MySQL, using SELECT DATABASE() appears to be safer overall.
Note also that this potential discrepancy between getCatalog() and the actual current database depends on the behaviour of the particular JDBC driver. Out of curiosity I tried something similar with the Microsoft JDBC Driver 4.0 for SQL Server and .getCatalog() was indeed aware of the change to the current database immediately after running a USE dbname statement. That is, the code
String connectionUrl = "jdbc:sqlserver://localhost:52865;"
+ "databaseName=myDb;" + "integratedSecurity=true";
try (Connection con = DriverManager.getConnection(connectionUrl)) {
System.out.println(String.format(
"getCatalog() returns: %s",
con.getCatalog()));
try (Statement s = con.createStatement()) {
System.out.println(" Executing: USE master");
s.execute("USE master");
}
System.out.println(String.format(
"getCatalog() returns: %s",
con.getCatalog()));
} catch (Exception e) {
e.printStackTrace(System.out);
}
produced the following results:
getCatalog() returns: myDb
Executing: USE master
getCatalog() returns: master
If you know that DB is Mysql you could just perform SELECT DATABASE() on your connection and read the resulset with current database name in it.
Here is description of DATABASE function.
Let's assume you used url as "jdbc:mysql://localhost/test"
Then do the following:
DatabaseMetaData dmd = connection.getMetaData();
String url = dmd.getURL();
System.out.println(url.substring(url.lastIndexOf("/") + 1));
Run
System.out.println(connection.getMetaData().getURL());
Paste the output in notepad
search the value for 'databaseName=yourDBName'

Why am I receiving this SQLException error stating that no suitable driver can be found?

I'm on a mac, running a MAMP instance of MySQL. I'm trying to use a jdbc driver to connect my java code to a database called 'test', working with a table called 'customer.' I keep getting an error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8889/test
I'm not sure if the problem is with my code, or if it's a configuration problem with the MAMP instance of MySQL, or if it's something else entirely.
I have an initialize driver method:
public void initializeDriver(){
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println(e.toString());
}
}
And I have a connection created in the following way:
public void insertCustomer(String connectionUrl, String connectionUser, String connectionPassword, Customer customer) {
try{
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
Statement constat = conn.createStatement();
String query = "INSERT INTO customers (customer_id, email, deliverable, create_date) VALUES (" + customer.id + ", " + customer.emailAddress + ", " + customer.deliverable + ", " + customer.createDate + ")" ;
constat.executeQuery(query);
conn.close();
}
catch(SQLException e){
System.out.println(e.toString());
}
}
And I have downloaded mysql-connector-java-5.1.20 and set it in my classpath.
If anyone has any suggestions for how I could correct this error, I would be really grateful!
You have to put MySQL jdbc connector jar library into the classpath.
Then initialize the driver before opening the connection with code like the following :
Class.forName("com.mysql.jdbc.Driver").newInstance();
You will need the corresponding mysql JDBC driver jar in your classpath or loadable by your container. See the doc for ConnectorJ and note the installation instructions.
Try to add mysql-connector-java-5.1.20.jar to Glassfish (or Tomcat) lib folder.
you have also a error in this row
constat.executeQuery(query);
if you want insert some data in data base you have to use this code
constat.executeUpdate(query);

Categories

Resources