connecting to MySQL using JDBC in eclipse - mysql

So I want to create a JDBC connection to MySQL server that is installed on my pc, here are the steps,
I installed MySQL with the username and password "root", downloaded mysql-connector-java and from theere I coped the JAR "mysql-connector-java-5.1.12-bin" to "C:\Sun\SDK\jdk\jre\lib\ext", I then added it as an external JAR in my project in eclipse, now in my class I have this code:
public void initialiseDatabase()
{
try {
// Load the Driver class.
Class.forName("com.mysql.jdbc.Driver");
//Create the connection using the static getConnection method
databaseConnection = DriverManager.getConnection (databaseUrl+databaseName,
dbUserName, dbPassword);
sqlStatement = databaseConnection.createStatement();
}
catch (SQLException e) {e.printStackTrace();}
catch (Exception e) {e.printStackTrace();}
}
(this is going to be psuedocode cause I am reading from a properties file and don't want the one helping me reading through long lines of code from main to figure out all the variables),
where databaseUrl = "127.0.0.1"
dbUserName = "root"
dbPassword = "root"
databaseName = "MySQL" //this one I am not sure of, do I need to create it or is it set inherenrly?
now the MySQL server is up and running, but when I call the method initialiseDatabase the following exception is thrown:
"java.sql.SQLException: No suitable driver found for rootroot
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Proxy$JDBCConnection.initialiseDatabase(Proxy.java:721)"
when line 721 is:
sqlStatement = databaseConnection.createStatement();
Where have I gone wrong?
thanks

Your database url should look like this:
jdbc:mysql://host:port/database
Example, if you use localhost, the default port and a database named cachedb, your url would be:
jdbc:mysql://localhost/cachedb

Related

Mysql.Data and Azure Mysql error 'Table 'mysql.proc' doesn't exist'

When I try to execute the stored procedure against Azure MySQL version 8.0.15 server using following code I get the error saying 'Table 'mysql.proc' doesn't exist'. This error does not happen with older versions. some search says to use MySQL_upgrade but I don't get that to work against azure MySQL. How do I overcome this error? Everything works fine when I connect to local MySQL version which is same as azure hosted.
Sample code
static async Task Main(string[] args)
{
var builder = new MySqlConnectionStringBuilder
{
Server = "myserver.mysql.database.azure.com",
Database = "mydb",
UserID = "myserver#myserver",
Password = "password",
SslMode = MySqlSslMode.Prefered,
};
using (var conn = new MySqlConnection(builder.ConnectionString))
{
Console.WriteLine("Opening connection");
await conn.OpenAsync();
using (var command = conn.CreateCommand())
{
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "prc_myprocedure";
var reader = await command.ExecuteReaderAsync(CommandBehavior.Default);
while (reader.Read())
{
Console.WriteLine(reader.GetValue(0));
}
}
Console.WriteLine("Closing connection");
}
Console.WriteLine("Press RETURN to exit");
Console.ReadLine();
}
}
Complete error:
Unhandled exception. MySql.Data.MySqlClient.MySqlException (0x80004005): Table 'mysql.proc' doesn't exist
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.SchemaProvider.GetProcedures(String[] restrictions)
at MySql.Data.MySqlClient.ISSchemaProvider.GetProcedures(String[] restrictions)
at MySql.Data.MySqlClient.ISSchemaProvider.GetSchemaInternal(String collection, String[] restrictions)
at MySql.Data.MySqlClient.SchemaProvider.GetSchema(String collection, String[] restrictions)
at MySql.Data.MySqlClient.MySqlConnection.GetSchemaCollection(String collectionName, String[] restrictionValues)
at MySql.Data.MySqlClient.ProcedureCache.GetProcData(MySqlConnection connection, String spName)
at MySql.Data.MySqlClient.ProcedureCache.AddNew(MySqlConnection connection, String spName)
at MySql.Data.MySqlClient.ProcedureCache.GetProcedure(MySqlConnection conn, String spName, String cacheKey)
at MySql.Data.MySqlClient.StoredProcedure.GetParameters(String procName)
at MySql.Data.MySqlClient.StoredProcedure.CheckParameters(String spName)
at MySql.Data.MySqlClient.StoredProcedure.Resolve(Boolean preparing)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteDbDataReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at AzureMySqlExample.MySqlUpdate.Main(String[] args) in C:\Users\sammo\source\repos\ConsoleApp1\Program.cs:line 31
at AzureMySqlExample.MySqlUpdate.<Main>(String[] args)
ISSUE: You are getting the below error because when you start a connection to Azure MySQL, the gateway of Azure MySQL will first send back a greeting package with a default server version "5.6.42.0 MySQL Community Server (GPL)". This make the MySQL.Data driver treat the server version as 5.6. But actually it is 8.0 and in MySQL 8.0, the table mysql.proc not exists anymore.
Workaround: You can use ProxySQL to fix the version issue:
Set up ProxySQL for Azure MySQL
https://techcommunity.microsoft.com/t5/Azure-Database-for-MySQL/Load-balance-read-replicas-using-ProxySQL-in-Azure-Database-for/ba-p/880042
Update the server version in ProxySQL
Connecting to ProxySQL with admin account, run the following commands.
a. mysql –u admin –padmin -h 127.0.0.1 -P 6032
b. UPDATE global_variables SET variable_value='' WHERE variable_name='mysql-server_version';
c. load mysql variables to runtime;
d. save mysql variable to disk;
To complement Mike Ubezzi's answer (credit to this post to point me in the right direction), the solution was to simply change the port from 3306 to 3309 in the database connection string. More information here.
In my case, I was running an ASP.NET app linked to a MySQL database version 8.0. After editing the connection string in the web app's configuration settings and restarting the web app, my stored procedures executed as expected.

Unable to connect to MySQL Database with Java through SSH

I know that there are many questions regarding this problem already, and believe me I've looked through all of them.
Some background, I'm using IntelliJ and I've been able to both connect to the database with IntelliJ's data source tool and I've been able to SSH into the server itself using the terminal. For some reason, even if I try to do the same thing with Java it doesn't work. Here's my code:
String serverIP = "123.45.67.890"
String username = "root";
String password = "password";
// Establish SSH tunnel with server if not running locally
try {
if (!Inet4Address.getLocalHost().getHostAddress().equals(ServerIP) {
System.out.println("Remote connection detected.");
System.out.println("Establishing SSH Tunnel...");
JSch jSch = new JSch();
Session session = jSch.getSession(username, ServerIP, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
System.out.printf("Connecting to remote server at %s...\n", ServerIP);
session.connect();
System.out.println("Connected!");
session.setPortForwardingL(3306, ServerIP, 3306);
}
} catch (Exception e) {
e.printStackTrace();
}
// Load mySQL Driver
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
String url = String.format("jdbc:mysql://%s:3306/db_name", ServerIP);
// Connect to database
System.out.println("Connecting to database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
this.connection = connection;
} catch (SQLException e) {
this.connection = null;
throw new IllegalStateException("Cannot connect to database!", e);
}
And here's the error I get:
Remote connection detected.
Establishing SSH Tunnel...
Connecting to remote server at 123.45.67.890...
Connected!
Loading driver...
Driver loaded!
Connecting to database...
java.lang.IllegalStateException: Cannot connect to database!
...
a bunch of crap
...
Caused by: java.sql.SQLException: null, message from server: "Host 'my.personal.computer.local.hostname' is not allowed to connect to this MySQL server"
...
a bunch more crap
...
It seems to me like for some reason, the Java code isn't using the SSH tunnel I put so much effort into copying StackOverflow code to make, and is instead rudely trying to connect normally. What am I doing wrong?
Some more info: The server itself is configured to listen for SQL on 0.0.0.0 and I also set the firewall to accept connections on port 3306.
Edit for clarity: I understand that I can probably fix this by giving my local computer privileges on the server, but I want to be able to connect through SSH.
Solution by OP.
The reason SSH wasn't working was because I needed to use a local open port, connect to SQL through that, then forward that to the remote port 3306. Also, I needed to port forward through localhost, not the server address.
(That is, change the session.setPortForwardingL(3306, ServerIP, 3306); line to session.setPortForwardingL(some-open-port, "localhost", 3306); and "jdbc:mysql://%s:3306/db_name" to "jdbc:mysql://%s:same-open-port/db_name".

MySQL JDBC Datasource lookup fails after updating to mysql-connector-java-5.1.44

Consider following code snippet:
try
{//try to connect
conn = DatasourceProvider.getDatasource("java:comp/env/jdbc/mysql/my_db").getConnection();
}
catch(Exception ex)
{//failed to acquire connection from the pool, retry
ex.printStackTrace();
}
When I run it with mysql-connector-java-5.1.10-bin.jar loaded in tomcat 8.5 it works gracefully, but when I update to mysql-connector-java-5.1.44-bin.jar it throws following exception:
javax.naming.NameNotFoundException: Name [jdbc/mysql/my_db] is not bound in this Context. Unable to find [jdbc].
at org.apache.naming.NamingContext.lookup(NamingContext.java:816)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
at org.apache.naming.NamingContext.lookup(NamingContext.java:159)
at org.apache.naming.NamingContext.lookup(NamingContext.java:827)
at org.apache.naming.NamingContext.lookup(NamingContext.java:173)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
This happens on both MySQL5.6 and MySQL5.7.
Any Idea?

JDBC Connection error persists

I am using MySQL Workbench (5.6.19). It has several connections among which the table that i want to access is in "Connection1"(name of connection). Connection Host: 122.0.0.0 . My database name is "sorder". user = "root", password = "password",port = 3306.
Here's my piece of code:
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("Driver Connection Failed.");
e.printStackTrace();
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try
{
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sorder","root", "password");
} catch (SQLException e)
{
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
My driver connection failed. Plus i am not sure what my path Strin url should be since there are more than 1 connections in mySQL workbench.
error :
-------- MySQL JDBC Connection Testing ------------
Driver Connection Failed.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:126)
at org.apache.jasper.servlet.JasperLoader.loadClass(JasperLoader.java:63)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at org.apache.jsp.NewFile_jsp._jspService(NewFile_jsp.java:65)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
I followed whatever suggestions i got in different forums, like:
reassured that JAR file is there in build path.
reassured that JAR file is there in Window>Prefernces>Java>Build Path>Classpath variable
JAR file explicitily in WEB-INF/lib buildpath.
Thankful for any suggestions.
Regards.
when we manually created a xml file and added welcome-file-list, it worked. Default xml file was missing.

Connect to remote mysql host from network with proxy

Ubuntu machine in internet zone with proxy server.
And i want to connect to remote mysql server mysql -u userName -p -h hostname.
And also i have java application that connect to that remote mysql host using hibernate ORM.
And i can't connect with the server.
Edit
I dont want to use mysql proxy but my database exists on remote server but my local machine have connection to the internet throw web proxy so i can't connect to remote db server.
And when i try connect from machine that has direct access to the internet That Work Perfectly
Trials.
1-System -> Preferences -> Network Proxy.
2- export http_proxy = http:userName:password#proxyserver:port
but that doesn't work.
and help will be appreciated..
Update:
static {
// SOCKS Proxy
System.setProperty("proxySet", "true");
System.setProperty("socksProxyHost", "proxy-host");
System.setProperty("socksProxyPort", "proxy-port");
System.setProperty("http.proxyHost", "proxy-host");
System.setProperty("http.proxyPort", "proxy-port");
System.setProperty("java.net.socks.username", "username");
System.setProperty("java.net.socks.password", "password");
Authenticator.setDefault(new ProxyAuthenticator("username", "password"));
// Open Web Site Work good
try {
URL url = new URL("http://www.kooora.com/");
URLConnection con = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
// Read it ...
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();
} catch (IOException iOException) {
iOException.printStackTrace();
}
// But open mysql connection throw exception
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection(getDBUrl(), USERNAME, PASSWORD);
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.