Android connection error java.lang.UnsupportedOperationException [duplicate] - java

This question already has answers here:
UnsupportedOperationException with DriverManager.getConnection() on Android
(3 answers)
Closed 3 years ago.
I have a problem on android studio when I try to make a connection to a mysql database
This is the code:
public Connection getMySqlConnection()
{
/* Declare and initialize a sql Connection variable. */
Connection ret = null;
try
{
/* Register for jdbc driver class. */
Class.forName("com.mysql.cj.jdbc.Driver");
/* Create connection url. */
String mysqlConnUrl = "jdbc:mysql://ip/ristorante?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
/* db user name. */
String mysqlUserName = "guest";
/* db password. */
String mysqlPassword = "guestpass";
/* Get the Connection object. */
ret = DriverManager.getConnection(mysqlConnUrl , mysqlUserName , mysqlPassword );
/* Get related meta data for this mysql server to verify db connect successfully.. */
DatabaseMetaData dbmd = ret.getMetaData();
String dbName = dbmd.getDatabaseProductName();
String dbVersion = dbmd.getDatabaseProductVersion();
String dbUrl = dbmd.getURL();
String userName = dbmd.getUserName();
String driverName = dbmd.getDriverName();
System.out.println("Database Name is " + dbName);
System.out.println("Database Version is " + dbVersion);
System.out.println("Database Connection Url is " + dbUrl);
System.out.println("Database User Name is " + userName);
System.out.println("Database Driver Name is " + driverName);
}catch(Exception ex)
{
ex.printStackTrace();
}finally
{
return ret;
}
}
This is the main error:
W/System.err: java.lang.UnsupportedOperationException
at java.util.regex.Matcher.group(Matcher.java:383)
at com.mysql.cj.conf.ConnectionUrlParser.isConnectionStringSupported(ConnectionUrlParser.java:152)
at com.mysql.cj.conf.ConnectionUrl.acceptsUrl(ConnectionUrl.java:258)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:195)
at java.sql.DriverManager.getConnection(DriverManager.java:569)
at java.sql.DriverManager.getConnection(DriverManager.java:219)
at com.example.spara.restaurant.activity_home.getMySqlConnection(activity_home.java:163)
at com.example.spara.restaurant.activity_home.onCreate(activity_home.java:80)
I tried the same code in eclipse java and it worked.
I had tried several times in different ways but without positive results.
so the database connection works.
I just cannot find a solution, I hope you can help me.

I have a same problem as yours. When I find a guy meeting a same proble with me in StackOverFlow, I am so exciting. But When I find there is 0 answer, I feel so hopeless and sad. (ಥ_ಥ)
After painful tryings , I replace mysql-connector-java 8.x with 5.1.47. Then the confusing errors java.lang.UnsupportedOperationException disappear. ( But I don't know whether other bugs will appear. At least other bugs appear at sql connect stage and they look resolvable. I think it may be related with SDK version? ) hope I can help you :)

Related

Does MySQL Connector/J driver implement JdbcRowSet interface?

I'm trying to get acquainted with JDBC basics throuhg Oracle's "The Java™ Tutorials" and now I got stuck right here: https://docs.oracle.com/javase/tutorial/jdbc/basics/jdbcrowset.html.
For my examples, I exploit MySQL Server with the latest version of Connector/J (mysql-connector-java-8.0.16.jar). So far, the driver worked as expected. It gets connection to MySQL Server, creates database, tables, populates them with data and fills ordinary ResultSet objects with the retrieved data. However, as soon as I try to create JdbcRowSet object and perform execute(), I get SQL exception reporting: "No suitable driver found..."
So, now I'm in doubts: whether JdbcRowSet (as well as CachedRowSet / JoinRowSet / FilteredRowSet / WebRowSet) is just not implemented by Connector/J driver, or I'm doing something wrong? Or maybe this functionality is no longer supported in JDK 11?
Here is an example:
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.*;
import java.util.Properties;
public class JdbcRowSetTest {
public static void main(String[] args) {
String connectionURL =
"jdbc:mysql://localhost:3306/testdb?serverTimezone=Europe/Moscow";
String userName = "root";
String password = "root";
try {
Properties connectionProps = new Properties();
connectionProps.put("user", userName);
connectionProps.put("password", password);
System.out.println("Connect to database...");
Connection conn =
DriverManager.getConnection(connectionURL, connectionProps);
System.out.println("Retrieve and process data using ResultSet...");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from COFFEES");
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
float price = rs.getFloat("PRICE");
System.out.println(coffeeName + ", " + price);
}
System.out.println("Now, update the data using JdbcRowSet...");
JdbcRowSet jdbcRs = RowSetProvider.newFactory().createJdbcRowSet();
jdbcRs.setUrl(connectionURL);
jdbcRs.setUsername(userName);
jdbcRs.setPassword(password);
jdbcRs.setCommand("select * from COFFEES");
// it's where SQLException is thrown
jdbcRs.execute();
jdbcRs.absolute(2);
jdbcRs.updateFloat("PRICE", 10.99f);
jdbcRs.updateRow();
System.out.println("After updating the 2nd row:");
//... view updated table
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And it's the output:
Connect to database...
Retrieve and process data using ResultSet...
Colombian, 7.99
Espresso, 9.99
Now, update the data using ResultSet...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testdb?serverTimezone=Europe/Moscow
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at java.sql.rowset/com.sun.rowset.JdbcRowSetImpl.connect(JdbcRowSetImpl.java:643)
at java.sql.rowset/com.sun.rowset.JdbcRowSetImpl.prepare(JdbcRowSetImpl.java:654)
at java.sql.rowset/com.sun.rowset.JdbcRowSetImpl.execute(JdbcRowSetImpl.java:556)
at JdbcRowSetTest.main(JdbcRowSetTest.java:37)
Updated (possible solution):
As the commentators mentioned bellow, the problem described here has nothing to do with MySQL implementing rowset or not. For me, it seems to be just a bug of JDK 11.0.1, because as soon as I updated for the newer version of JDK 12.0.1, the problem dissipated, and now JdbcRowSet object is created without any MySQLException.

Connection code to database created through phpmyadmin [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
I'm trying to create a connection to a database in my Java program. I'm not sure if i have the correct address for it though in my code.
Below is my connection code:
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "n1nlhdb5501-02.shr.prod.ams1.secureserver.net";
Connection conn = DriverManager.getConnection(url, "user1", "password");
return conn;
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
Unfortunately, Im really unsure of whether I have put the correct information into the url and the "Class.forname()" lines. I know the one is to load the actual driver and the other is the address of the database but i'm not sure if the information I have input is correct, because the connection is unsuccessful.
Is there anyway I could find the exact address that i need to use in the url string through an SQL statement maybe?
Also, I'm not sure if I'm loading the correct drivers for the jar file which i'm using, its called 'mysql-connector-java-5.1.35-bin.jar'
All help appreciated!
Thanks in advance
Marko
This is how you can connect MySQL database using Java.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://x.x.x.x:3306/databaseName", "username", "password");
Statement smt = con.createStatement(); //Create Statement to interact
ResultSet r = smt.executeQuery("select * from users where(AccountID='" + q + "');");
while (r.next()) {
name = r.getString("name");
}
con.close
} catch (Exception e) {
e.printStackTrace();
}
In your case URL will be like...
String URL = "jdbc:mysql://n1nlhdb5501-02.shr.prod.ams1.secureserver.net:3306/databaseName"
Edit:
It seems 3306 port is closed.
Nmap scan report for n1nlhdb5501-02.shr.prod.ams1.secureserver.net (37.148.204.135)
Host is up (0.075s latency).
Not shown: 97 filtered ports
PORT STATE SERVICE
80/tcp open http
443/tcp open https
3306/tcp closed mysql

Connection to Oracle Database with Java

I can't connect to my Oracle database server. This is the code :
import java.util.*;
import java.sql.*;
import java.io.IOException;
public class Knigi {
public static void main(String[] args) {
String baza_DRIVER="oracle.jdbc.driver.OracleDriver";
String baza_STRING="jdbc:oracle:thin:#localhost:1521:";
String baza_USERNAME="knigi";
String baza_PASSWORD="knigi";
Locale.setDefault(Locale.ENGLISH); // Vazhno e bidejkji Oracle treba da znae kakvi poraki da pojavuva
try {
Driver Driver = (Driver)Class.forName(baza_DRIVER).newInstance();
Connection Conn = DriverManager.getConnection(baza_STRING,baza_USERNAME,baza_PASSWORD);
PreparedStatement Statement = Conn.prepareStatement("SELECT * FROM zhanrovi");
ResultSet zhanrovi = Statement.executeQuery();
boolean isEmpty = !zhanrovi.next();
boolean hasData = !isEmpty;
while (hasData) {
System.out.println("Zhanr: "+zhanrovi.getString("ZH_IME"));
PreparedStatement Statement2 =
Conn.prepareStatement("select * from knigi where ZH_BR = ?");
Statement2.setInt(1,zhanrovi.getInt("ZH_BR"));
ResultSet knigi = Statement2.executeQuery();
boolean isEmpty2 = !knigi.next();
boolean hasData2 = !isEmpty2;
if (isEmpty2) {
System.out.println(" - nema knigi");
} else {
System.out.println(" - Knigi:");
};
while (hasData2) {
System.out.println(
" " +
knigi.getString("ISBN") +
" - " +
knigi.getString("NASLOV")+" ");
hasData2=knigi.next();
}
knigi.close();
hasData=zhanrovi.next();
}
zhanrovi.close();
Conn.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
And I am getting this message:
java.sql.SQLException: Io exception: Connection refused(DESCRIPTION=(TMP=)(VSNNUM=186646784)(ERR=12504)(ERROR_STACK=(ERROR=(CODE=12504)(EMFI=4))(ERROR=(CODE=12504)(EMFI=4))))
In school, this example works. Where is the problem??
Try this, might help
jdbc:oracle:thin://<host>:<port>/<SERVICE_NAME>
service_name=SID of the database, most often ORCL.
cheers,
Do you have your DB server running at your local machine at: localhost:1521?
Your school machine might have DB server running on it but your home machine simply doesn't.
The db connection URL "jdbc:oracle:thin:#localhost:1521:" is normally not hard coded. Point it to localhost almost always fail it when you run your code on a different machine.
There are three major instances when you get such Connection refused error
There is no database server running at the host:port you have specified i.e at localhost:1521
Password you have entered is wrong.
The port you have specified is blocked by a firewall or you are behind some proxy that does not allow you to connect to that port.
You can manually try to connect to your database from command line and see if the connection is live.
Question has been closed ... I had to do a tunneling because my Faculty server has closed connection from out side the faculty network, also they told me that the password had been changed ....
btw tnx for the answers they helped me to connect to my local server and access my local data base ..
Thanks again mates ^_^

H2: Error on all other computers

I'm using the H2 database in my Java project (embedded mode).
On my computer at home everything works, the connection can be established, but on all other computers I always receive the following error:
org.h2.jdbc.JdbcSQLException: Table "CUSTOMERS" not found; SQL
statement: SELECT * FROM CUSTOMERS [42102-162]
I'm sure, that within the DB everything is alright, it should be something with the connection.
But even if I import the h2-1.3.162.jar file, the error still remains.
String dbClass = "org.h2.Driver";
String dbDriver = "jdbc:h2:~/cc";
String user = "user1";
String pass = "test1";
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public void connect() {
boolean done = false;
//load driver
try {
Class.forName(dbClass).newInstance();
System.out.println("driver loaded"); // This is shown in the Compiler
} catch (Exception ex) {
System.out.println("error while loading driver");
System.err.println(ex);
}
// Connection
try {
conn = DriverManager.getConnection(dbDriver, user, pass);
System.out.println("connected"); // This is shown in the Compiler
done = true;
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
public Vector select() {
data = new Vector();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM CUSTOMERS");
while (rs.next()) {
Vector row = new Vector();
row.add(rs.getInt("id"));
row.add(rs.getString("fname"));
row.add(rs.getString("lname"));
row.add(rs.getString("street"));
row.add(rs.getString("city"));
row.add(rs.getString("zip"));
row.add(rs.getString("state"));
row.add(rs.getString("phone"));
row.add(rs.getString("birthday"));
row.add(rs.getString("email"));
row.add(rs.getInt("code"));
data.add(row);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
System.out.println("error while selecting"); // I receive this error
System.err.println(ex);
}
return data;
}
The problem isn't with your connection as you'd receive an exception well before then if it was failing to connect to the database. The exception is pretty clear about what the issue is, as well - it can't find the CUSTOMERS table. That could be because the table doesn't exist at all, or the connection is pointing at the wrong database; try putting in the full schema information of the table, rather than just its name, and see if that works.
I'm sure, that within the DB everything is alright, it should be
something with the connection. But even if I import the h2-1.3.162.jar
file, the error still remains.
Check your assumptions. This one is incorrect.
There's nothing in the message to suggest that you couldn't connect. Either you connected to the wrong database OR the one you did connect to didn't CREATE TABLE CUSTOMERS. (Should be named CUSTOMER, not plural.)
You'll fix your error faster if you stop assuming that everything you did is correct. You should be assuming that everything is wrong.
I'd print the stack trace when you catch that exception. It'll give you more information.
Finally I figured it out!
It had nothing to do with my tables, the database couldn't be found. When trying to connect to a database which can't be found with String dbDriver = "jdbc:h2:~/cc";, a new database with the name cc (in my case) will be created (of course an empty one with no tables) and the connection is established. That's why I haven't received any connection errors.
In the next step I tried to retrieve some data from the new created empty database and therefore received the error, that my table doesn't exist.
So I changed this line: String dbDriver = "jdbc:h2:file:lib/cc"; and copied into the lib directory of my application my old database cc.h2.db.
That's all!
PS: Here is a similiar problem: h2 (embedded mode ) database files problem

Access mysql data base from another system using java

I am working on a interface in java swing.we have four system connected with a lan.the interface is for accessing the database from the other system in the same local area network i used the following code to access the database by giving the ip address,database name,tablename but i could not connect the other systems database.how can i do this?
public void dbconnection() {
String name = "";
String port = "3306";
String user = "systech";
String pass = "systech";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
Use below code
public void dbconnection() {
String name = "";
String port = "3306";
String user = "systech";
String pass = "systech";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
Class.forName("com.mysql.jdbc.Driver").newInstance ();
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
System.out.println("Name:" + rs.getString(1));
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
Also, make sure to include jar file for connecting. You will get jar file here.
Update 1:
So, you have a
CommunicationsException: Communications link failure
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
Update 2
If your system is Windows, go to Start>>Run.
Type command. This will open command prompt.
Type "ping 192.168.1.61"
You might get reply in below format.
Pinging 192.168.1.61 [192.168.1.61] with 32 bytes of data:
Reply from 192.168.1.61: bytes=32 time=101ms TTL=124
If you don't get something in above format, then your MYSQL Server with ip 192.168.1.61 is NOT REACHABLE. Ask your team to start the server first. :(
If you have Linux version, open terminal and follow step 3.
Also check below link. Those might help you...
http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html
You should down load the jdbc driver and replace
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
by
Class.forName("com.mysql.jdbc.Driver");
If you still have issues asfter replacing Obdc stuff, please post the exception.
ALso check firewall settings and DB permissions.
If you'll get exception your app will not free system resources. This will work better:
} finally {
try {
rs.close();
st.close();
con.close();
} catch( Exception e ) {
e.printStackTrace();
}
}

Categories