I'm a little new at that, but after starting my ec2 instance, and installing MySQL instance through RDS, I manage to connect to it through MySQL Workbench using ssh (.pem file).
My problem is I can't seem to have it right, when I'm trying to connect with jdbc, how exactly the authentication suppose to be done?
Here is my code, hope somebody can give me a hint on how to proceed:
public void create_table(){
Connection c = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");
// c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE USERS " +
"(ID INT PRIMARY KEY ," +
" DEVICE TEXT NOT NULL, " +
" NAME TEXT NOT NULL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
EDIT
I forgot few important details...
I wrote my code in Java using Jersey and servelt.
I Uploaded my WAR file to my ec2 instance.
Now after both web-app and MySQL server are running on the same instance, I want to build the communication..
Thank you!
Your SQL Syntax is incorrect. Text values are inserted as VARCHAR type in SQL. You can change the length of the text value depending on your need by changing the value with in the bracktes in VARCHAR(HERE). Try this code.
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE USERS " +
"(ID INTEGER not NULL," +
" DEVICE VARCHAR(255) not NULL," +
" NAME VARCHAR(255) not NULL,"+
"PRIMARY KEY (ID))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
how exactly the authentication suppose to be done?
you can use one of the form you use in your example but there are wrong things in both
c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");
you connect to localhost, if you have your test db on RDS you need to reference the end point of RDS like your second example
c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");
Here the end point will be correct but the string to connect is wrong. You can use the following form
String jdbcUrl = "jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test?user=root&password=password";
Connection con = DriverManager.getConnection(jdbcUrl);
or
String url = "jdbc:mysql://mydatabase.test.us-east-1.rds.amazonaws.com:3306/";
String userName = "root";
String password = "password";
String dbName = "test";
Connection connection = DriverManager.getConnection(url + dbName, userName, password);
To find precisely your database end-point, login to the RDS console (make sure to select the right region if not us-east-1), select your database and the Endpoint will be there
The other potential issue you might run is on Security Groups
The DB instance was created using a security group that does not authorize connections from the device or Amazon EC2 instance where the MySQL application or utility is running. If the DB instance was created in a VPC, it must have a VPC security group that authorizes the connections. If the DB instance was created outside of a VPC, it must have a DB security group that authorizes the connections.
Check your security group rules for both the RDS DB and the ec2 instance and make sure you can connect that the ec2 instance has access to RDS server
Related
screenshot of the codeI want to use statement in connecting mysql and java database, but the code is giving me errors, I want to know where did I go wrong and how I should do it without getting errore
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/sms","root","");
Statement st= (Statement)conn.createStatement();
String sql= "select * from user_login";
}
catch(Exception e){
}![this is the screenshot of the code](https://i.stack.imgur.com/lo8Yo.png)
I tried using this
Alright, so to do JDBC with MySql you need 4 things
Driver Class
Connection URL
Username
Password
Assuming you have already created the database, with name database_name and table data that has 3 columns as id, first_name & last_name
Connection and showing the data in as follows:
import java.sql.*;
import java.util.*;
class ConnectionToDatabase{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","username","Pa$$word");
Statement statement = connnection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from data");
while(resultSet.next()){
System.out.println(resultSet.getInt(1) + " " + resultSet.getString(2) + " " + resultSet.getString(3));
connection.close();
}
}catch(Exception e) { System.out.println(e); }
}
}
And of course, you can use Spring Boot, where a file named application.properties exists inside java.resources, you can specify the connection as - (Copied from Spring docs)
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=databaseusername
spring.datasource.password=databasepassword
package main.java;
import java.sql.*;
public class SQLSetup {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test_db";
// Database credentials
static final String USER = "Halli";
static final String PASS = "dragon";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
Why is CREATE TABLE REGISTRATION giving me the error "Unrecognized statement"? I am using Intellij, Java 13 and Maven and MySQL server.
This is just something to get my question through since the template is complaining about me not giving enough details and a lot of code, but I am not sure what more to say about the problem.
It did not even occur to me that I could run the code with Intellij giving me a red error on this, but it did not matter - I tried to run the code and Voila - it created a table, even with this error message.
I am trying to connect to a remote hive server. I have the following maven java code :
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
// Register driver and create driver instance
Class.forName(driverName);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ForHive.class.getName()).log(Level.SEVERE, null, ex);
}
// get connection
System.out.println("before trying to connect");
Connection con = DriverManager.getConnection("jdbc:hive://<hostip>:10000/", "hive", "");
System.out.println("connected");
// create statement
Statement stmt = con.createStatement();
// execute statement
stmt.executeQuery("CREATE TABLE IF NOT EXISTS "
+" consultant ( eid int, name String, "
+" salary String, destignation String)"
+" COMMENT ‘Employee details’"
+" ROW FORMAT DELIMITED"
+" FIELDS TERMINATED BY ‘\t’"
+" LINES TERMINATED BY ‘\n’"
+" STORED AS TEXTFILE;");
System.out.println("Table employee created.");
con.close();
}
But when I execute it gets stuck while trying to connect to the server and throws no exception either.
Try to use org.apache.hive.jdbc.HiveDriver driver.
Connection string
jdbc:hive2://<host>:10000/
Following ways are reasons for your problem.
1.Hive JDBC Class path is "org.apache.hive.jdbc.HiveDriver" and not "org.apache.hadoop.hive.jdbc.HiveDriver".
2.For hive server,
You can able to use like below.
Connection con = DriverManager.getConnection("jdbc:hive://:10000/default", "", "");
3.If you have using hiveserver2,
you have use below connection.
Connection con = DriverManager.getConnection("jdbc:hive2://:10000/default", "", "");
Above ways are surely helpful to you
when i ll try to connecting mysql using jdbc means its succeessfully connected on localhost.but i replaced localhost by my ip address means itz not connected..y dis error is came..how it is cleared..help me.
dis is my coding:
package com.retrieve;
import java.sql.*;
public class retrieve{
public static void main(String[] args) {
System.out.println("Getting All Rows from a table!");
Connection con = null;
String url = "jdbc:mysql://192.168.1.249:3306/";
String db = "login";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM login");
System.out.println("username: " + "\t" + "password: ");
while (res.next()) {
String s = res.getString("username");
String s1 = res.getString("password");
System.out.println(s1 + "\t\t" + s);
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
The error is:
Getting All Rows from a table!
java.sql.SQLException: Data source rejected establishment of connection, message from server: "Host '192.168.1.249' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:650)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1808)
at com.mysql.jdbc.Connection.(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at com.retrieve.retrieve.main(retrieve.java:15)
With your MySQL server you need to add permission for your user to be able to access your db from the specified IP
Execute following query from mysql console
GRANT ALL ON YOUR_DB.* TO 'root'#'192.168.1.249';
create user 'login'#'192.168.1.249' on your mysql server.
mysql builds users from 'name' (here - login you specified) and 'host' (address from which user connects to server). You can use '%' char to describe 'all hosts'.
consider reading this section of docs:
http://dev.mysql.com/doc/refman/5.1/en/user-account-management.html
Try to close all the resources like Statment, ResultSet objects etc.Also, as #Jigar mentione, grant permission to the users as well.
Please check your port .If you changed your port number ,you got this error like
"com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"
How to access the another system mysql database through java program?Am using the following program but i have get the communication error?what are the changes are need to connect the another system mysql database?
Public void dbconnection() {
String name = "";
String port = "3306";
String user = "system";
String pass = "system";
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);
}
}
You're not creating an instance of the driver class:
Class.forName("com.mysql.jdbc.Driver").newInstance();
[update: not necessary after all, ignore that]
And you're also referencing "sun.jdbc.odbc.JdbcOdbcDriver", is that necessary? If so, shouldn't you instantiate it also? [update: probably not]
If it works with localhost, and not with the IP specified, you need to configure mysql to listen on all ports.
jcomeau#intrepid:/tmp$ cat dbconnection.java; javac dbconnection.java; sudo java -cp .:/usr/share/maven-repo/mysql/mysql-connector-java/5.1.16/mysql-connector-java-5.1.16.jar dbconnection
import java.sql.*;
public class dbconnection {
public static void main(String args[]) {
String name = "";
String port = "3306";
String user = "root";
String pass = "";
String dbname = "imagetagging";
String host="127.0.0.1";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
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 taggers";
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);
}
}
}
URL:jdbc:mysql://127.0.0.1:3306/imagetagging
Name:1
Name:2
Name:3
Name:4
Name:5
Name:6
Name:7
Name:8
Name:9
Name:10
Name:11
Name:12
Name:13
Name:14
Name:15
Name:16
Name:17
Name:18
Name:19
Name:20
Name:21
As I understand you just need to specify another connection string, with another host and other credentials, e.g.:
...
String port = "3306";
String user = "user_name";
String pass = "password";
String dbname = "db_name";
String host="host_name";
...
You have to do 3(with 4th step optional) simple things to connect to your remote mysql database server.
Open up any GUI tool for mysql database management (your IDE, Mysql Workbench or smth else), check if you can connect to your database by specifying your credentials, host, port and database name.
If that succeeds you know there is nothing wrong on the db part (go to 3), if not, and you are sure you do everything correctly up to this point go to point 2.
check out this post on how to enable remote access to your db and try again (go to pkt 1)
You would have to clean up a bit your code, have a look into simple and to the point tutorial on how to connect and execute simple sql statements with java on Vogella tutorial
Once everything is working correctly, remember to give +1 on Vogella tutorial, praise the cybercity or any other website for the explanation on how to enable remote access on you db and don't forget to come back to stackoverflow and reward all good answers :)