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
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
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
I have a big question...
I have a database java program creation.
I want to know if the database exists or not, and the if exists just connect, if not to create it.
I tried this one:
if (dbName.exists() == false) {}
THIS IS ALL THE CODE...
Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL JDBC driver loaded ok.");
THIS IS A BACKUP CODE FOR IT, JUST TO WORK FOR NOW....
PARTIAL CODE THAT WORKS !
conn = DriverManager.getConnection(DBurl + url
+ "?createDatabaseIfNotExist=true& + "
+ "useUnicode=true&characterEncoding=utf-8&user="
+ userName + "&&password=" + password);
System.out.println("Connected to database ");
System.out.println("Connected to the database " + url);
BUT I WANT SOMETHING LIKE:
FILE dbName = new FILE (url);
Statement stmt = new Statement;
if (dbName.exists() == true)
System.out.println("Database exists ! Connecting ... ");
else {
String sql = "CREATE DATABASE "+url;
stmt.executeUpdate (sql);
}
I don't want to put the url with the password and username in the same place... because they are provided from an external part, but that is allready implemented and working.
So I want to rip in 2 peaces, 1 Connect "jdbc:mysql://localhost:3306/"; WITHOUT URL which is the database NAME ...
AND THEN IF A DATABASE DOES NOT EXISTS THERE WITH THAT NAME JUST CREATE ON.
It is not working.... not entering in the else more, and says that Exeption Database already exists.
Thanks you very much.
If it is a MySQL database, the following code should work. Other databases may give a different error code, but the general way should be clear. Important is that you connect to the instance, not a specific database initially. For creating the tables, you will need to connect to the newly created database. You can't use the instance connection that I use in my example for creating the tables:
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/",
"root", "admin");
statement = connection.createStatement();
String sql = "CREATE DATABASE DBNAME";
//To delete database: sql = "DROP DATABASE DBNAME";
statement.executeUpdate(sql);
System.out.println("Database created!");
} catch (SQLException sqlException) {
if (sqlException.getErrorCode() == 1007) {
// Database already exists error
System.out.println(sqlException.getMessage());
} else {
// Some other problems, e.g. Server down, no permission, etc
sqlException.printStackTrace();
}
} catch (ClassNotFoundException e) {
// No driver class found!
}
// close statement & connection
Without knowing much about what's going on here simply trying to connect to a database that doesn't exists should throw a TimeoutException error or something similar. Just catch the exception and do stuff if you cannot connect.
boolean canConnect = false;
Connection conn = null;
try{
conn = DriverManager.getConnection(...);
canConnect = true;
}(Exception ex){
canConnect = false;
}
if (!canConnect){
makeDatabase(...);
}
Enjoy your day!
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "admin");
Statement statement = connection.createStatement();
String sql = "CREATE DATABASE IF NOT EXISTS DBNAME";
statement.executeUpdate(sql);
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Kindly Note a Two things
The new driver class is `com.mysql.cj.jdbc.Driver'
The query CREATE DATABASE IF NOT EXISTS DBNAME means you dont have to check if database exits
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"
I am using the SphinxQL MySQL client which stores indexes as "tables" but has no real notion of a "database"...One specifies the port (9306 in my case) at which the sphinx mysql instance listens and in theory should be able to communicate as normal.
I have the following test code:
import java.sql.*;
public class Dbtest {
public static void main (String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:9306",
"user","password");
con.setReadOnly(true);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT * from index_turned_table");
while (res.next()) {
String stuff1 = res.getString(1);
String stuff2 = res.getString(2);
System.out.println("Adding " + stuff1);
System.out.println("Adding " + stuff2);
}
res.close();
stmt.close();
con.close();
}
catch(Exception e)
{
System.out.println (e);
}
}
Upon execution, the code just hangs and does nothing and doesn't print out an exception. What are useful things I can do to figure this out or if any one has direct experience what might be going on?
This work with 1.10-beta http://www.olegsmith.com/2010/12/scalalift-sphinxql.html
and not work with 2.0.1-beta. Use mysql-connector-java 5.1.15.
Your SphinxQL instance is listening on port 9306. Your MySQL is listening on some other port, likely on the default 3306. You can use MySQL JDBC driver to connect to MySQL, but you cannot use it to connect to SphinxQL. It just doesn't understand JDBC driver communication protocol.