Connecting to mySQL Database with Java - java

In my program I am trying to connect to a mySQL database. This program is written in Java.
I am trying to connect to my database with this code here (? is a place holder b/c I dont know what does there.)
Connection conn = DriverManager.getConnection("jdbc:sqlite:*?*");
I need someone to help me replace the ? to connect to my database. I know the IP (Just call it ***.***.*** for security reasons, the port which is 3306 and the database is called devicede_Test).
Please help me replace the ? with the correct string with the info above, thanks!

Try this
Connection conn = DriverManager.getConnection("jdbc:mysql://***.***.***:3306/dbname");

Try this:
String url = "jdbc:mysql://localhost:3306/mysql";
Connection con = DriverManager.getConnection(url,"root", "");

SQLIte is not the right driver here. Use:
Connection conn = DriverManager.getConnection("jdbc:mysql://**.***.***.***/devicede_Test", user, pass);

The JDBC URL format for MySQL Connector/J is as follows, with items in square brackets ([, ]) being optional:
jdbc:mysql://[host][,failoverhost...][:port]/[database] »
[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
Here is a sample connection URL:
jdbc:mysql://localhost:3306/sakila?profileSQL=true
Source : http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html

Related

JDBC - Cant connect to Oracle using Service Name

I have been trying to connect to this Oracle database with JDBC thin driver with the following syntax:
var URL = "jdbc:oracle:thin:#//16.161.286.56:1522/Service_Name";
var USER = "user";
var PASS = "password";
var conn = Jdbc.getConnection(URL, USER, PASS);
I keep on having the same response when I execute this:
We're sorry, a server error occurred. Please wait a bit and try again. [87a99af]
Would anyone have an idea of what I am doing wrong ?
Also, when I change the IP address to its 'string version':
var URL = "jdbc:oracle:thin:#//mydomain.com:1522/Service_Name";
Then I get the error response:
Failed to establish a database connection. Check connection string, username and password.
Which does not make sense to me as both expressions are supposed to be equivalent ...
The actual format of Oracle JDBC connection using service name is:
#//host_name:port_number/service_name
Make sure that is service name is ok.
You can try with TNSNameListener
jdbc:oracle:thin:#(description=(address=(host=<HOSTADDRESS>)(protocol=tcp)(port=<PORT>))(connect_data=(service_name=<SERVICENAME>)(server=<SHARED>)))
The TNSNameListener file location:
<ORACLE_HOME>\network\admin\tnsnames.ora
example: /home/oracle/oracle/product/10.2.0/db_1/network/admin/tnsnames.ora
I am not sure which class is that Jdbc is. Take a look at the JDBCUrlSample.java and DataSourceSample.java

Java connect with JDBC to Postgres - SQLException

Iam tryig to connect to a Postgres Database. Iam really new to that and have read a post in the forum. But I didn't manage it.
public void connect() {
//Connection con = null;
try {
Class.forName("org.postgresql.Driver");
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
props.setProperty("ssl","true");
Connection conn = DriverManager.getConnection(url, props);
//String url = "jdbc:postgresql://localhost/test?user=fred&password=secret&ssl=true";
//Connection conn = DriverManager.getConnection(url);
System.out.println("Erfolgreich verbunden!");
}
catch (Exception e){
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
}
EDIT:
I updated my Code.
The database is deployed to heroku.
It throws the error:
java.sql.SQLException: No suitable driver found for jdbc:postgres://vuqmbekwlgohkw:******
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:189)
at com.company.Database.connect(Database.java:20) p
at com.company.Main.start(Main.java:16)
at com.company.Main.main(Main.java:25)
java.sql.SQLException: No suitable driver found for jdbc:postgres://vuqmbekwlgohkw:***************
I believe that your problem is that your connection URL is malformed.
When DriverManager.getConnection throws SQLException, the message includes the exact url value passed to the function. In your case, that looks like jdbc:postgres://vuqmbekwlgohkw:******.
But obviously that is not the URL you are using. You have replaced part of the URL with asterisks. That suggests that you think the format of the URL is:
jdbc:postgres://username:password#host:port/dbname
which seems to be what Heroku provides in the DATABASE_URL environment variable. You are using asterisks to prevent us from seeing the password.
However, it looks like the PostgreSQL JDBC driver does not accept URLs in this format. When I tried, I also got the "No suitable driver" error. According to the documentation, the format of the URL is:
jdbc:postgres://host:port/database
Some parts are optional, but the driver does not appear to support putting the user name or password in the URL.
I was able to connect to an AWS PostgreSQL instance by using the URL format described in the documentation and using the connection properties to set the user name and password.
You said you are new so I'm gonna start with the painfully obvious, do you have the driver on your classpath?
it's a jar you add to your project that you can download from https://jdbc.postgresql.org/
Otherwise I have an example of the url that worked for me, except I was not exactly using jdbc, it was a spring-boot project:
jdbc:postgresql://ec2-174-99-88-88.compute-1.amazonaws.com:5432/asdfasdfsadf?sslmode=require
There is no port number in your commented URL and not all parameters might be supported, like Willis pointed out.

Which is my "instance name" in Google MySQL

jdbc:google:mysql://[your-project-id]:[your-instance-name]/[your-database-name]
↑
This is the URL that Google Documents suggest for connecting to your database (taken from here https://developers.google.com/eclipse/docs/cloudsql-createapp).
I know my project ID, and I know it is correct. Same with the database name. But I'm not sure which is the [your-instance-name] parameter.
String url = "jdbc:google:mysql://elliptical-trend-259112:default/testdb";
conn = (Connection) DriverManager.getConnection(url, "root", "*****");
This is what I've tried until now.
Where can I get the instance name?
Thanks in advance!
Go to: The cloud SQL instances page you should be able to find it there.

Java MySql Connection Through DSN

I am trying to connect to one of my MySql Databases through a System DSN I set up. The DSN is set up correctly with my SSL certs, username, password, port, and the databases populate the DSN database drop down and the "Test" connection passes. I can't seem to get a connection in Java. I have spent 2 days looking through some examples on Stack but they all refer to an Access database and using JDBC-ODBC bridge which is no longer available in Java 8. I tried using UCanAccess with Jackcess but I have gotten no where. The code below is what I have been tinkering with the last few hours. I normally connect to MySql databases with PHP and receive result in JSON or directly with JDBC driver but for this project neither are really an option. Any ideas. I appreciate the help.
//String username = "<username>";
//String password = "<password>";
//String database = "<database_name>";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
//Connect to cllients MySql Database
Connection conn = DriverManager.getConnection("jdbc:ucanaccess:" + database);
//Call VerifyLabel(<MAC>,<MODEL>); Call provided client
CallableStatement cStmt = conn.prepareCall("{CALL verify(?, ?)}");
//MAC
cStmt.setString(1, "mac address");
//model
cStmt.setString(2, "model");
cStmt.execute();
//Getting results from "Status" column
ResultSet rs1 = cStmt.getResultSet();
//Iterate results and print.
while (rs1.next()) {
System.out.println(rs1.getString("Status"));
}
//Close connection conn
rs1.close();
} catch (SQLException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
}
Using MySql Driver:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:"+ database);
also tried:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ database);
Error for MySql Driver:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
1) DSN is most commonly assocatiated with ODBC (and often with MS-Access). Hence all the links. ODBC is NOT required for a DSN.
2) Do NOT use Ucanaccess. Use J/Connector for mySQL.
3) Make sure you can communicate with mySQL from the command line. Then focus on getting a small "hello world" JDBC app to connect. Your second and third examples look OK. Be sure to check the mySQL logs for any warnings/errors.
Well, after an entire day of trying to get this to work and sleeping on it for a couple hours I finally got it to work. UCanAccess and mysql-connector did not work. The easiest thing since no other method of connecting to this clients database was acceptable was to push this application in Java 7 rather than 8. This allowed me to Coo=nnect to my DSN with no problems. I understand that this method is not the best solution but it is what is working flawlessly and efficiently. Also, instead of using some rigged up 3rd party libs and jars, I am able to use Connector/J. Thanks everyone for trying to help me. Just incase anyone else runs into this issue, this is how I made it work.
Develope app in Java 7 - not 8.
Set Up System DSN
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//You do not need to provide username or password if it is setup in DSN
Connection conn = DriverManager.getConnection("jdbc:odbc:"+ database);

Cant connect to mariadb from java - only with mysqldeveloper [duplicate]

I am trying to connect to a database in Mariadb through a simple java application but the connection is told to be unsuccessful and an Exception is thrown. I have done the similar connection using mysql and it was working correctly. The problem is maybe with the driver here.
try{
Class.forName("org.mariadb.jdbc.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:mariadb://localhost:3306/project", "root", "");
Statement statement = connection.createStatement();
String uname="xyz",pass="abc";
statement.executeUpdate("insert into user values('"+uname+"','"+pass+"')");}//end of try block
I looked up the internet for the help and came by that driver class provided by the MariaDB Client Library for Java Applications is not com.mysql.jdbc.Driver but org.mariadb.jdbc.Driver! I changed it accordingly but it seems the problem is with the very first line inside the try block. The driver is not loading at all.
Also, I have added the mysql jar file to the libraries of my java application as in the screen-shot below. Please help me through this.
It appears that you are trying to use jdbc:mariadb://... to establish a connection to a MariaDB server instance using the MySQL JDBC Driver. That probably won't work because the MySQL JDBC Driver would use jdbc:mysql://..., regardless of whether it is connecting to a MySQL server or a MariaDB server. That is, the connection string must match the driver that is being used (rather than the database server being accessed).
The MySQL and MariaDB drivers are supposed to be somewhat interchangeable, but it only seems prudent to use the MariaDB connector when accessing a MariaDB server. For what it's worth, the combination of mariadb-java-client-1.1.7.jar
and
Connection con = DriverManager.getConnection(
"jdbc:mariadb://localhost/project",
"root",
"whatever");
worked for me. I downloaded the MariaDB Client Library for Java from here:
https://downloads.mariadb.org/client-java/1.1.7/
which I arrived at via
https://downloads.mariadb.org/
Additional notes:
There is no need for a Class.forName() statement in your Java code.
The default configuration for MariaDB under Mageia may include the skip-networking directive in /etc/my.cnf. You will need to remove (or comment out) that directive if you want to connect to the database via JDBC because JDBC connections always look like "network" connections to MySQL/MariaDB, even if they are connections from localhost. (You may need to tweak the bind-address value to something like 0.0.0.0 as well.)
An additional note:
Exploring the MariaDB JDBC driver, I found this inside the url parsing file:
Project: https://github.com/MariaDB/mariadb-connector-j.git
File: src/main/java/org/mariadb/jdbc/UrlParser.java
public static UrlParser parse(final String url, Properties prop) throws SQLException {
....
if (url.startsWith("jdbc:mysql:")) {
UrlParser urlParser = new UrlParser();
parseInternal(urlParser, url, prop);
return urlParser;
} else {
if (url.startsWith("jdbc:mariadb:")) {
UrlParser urlParser = new UrlParser();
parseInternal(urlParser, "jdbc:mysql:" + url.substring(13), prop);
return urlParser;
}
}
As you can see, the string "jdbc:mariadb:" is always replaced with "jdbc:mysql:" internally. So when it comes to the MariaDB driver, whether it is :mariadb: or :mysql: it always gets parsed as "jdbc:mysql:".
No difference.
if (url.startsWith("jdbc:mariadb:")) {
....
parseInternal(urlParser, "jdbc:mysql:" + url.substring(13), prop);
....

Categories

Resources