I am trying to connect with mysql with Java.
I am using db.properties files to get the connection details.
I am kind of new guy to work with the db.properties file. What is the wrong with my code??
It is as below
#mysql DB properties
#DB_DRIVER_CLASS=com.mysql.jdbc.Driver
#DB_URL=jdbc:mysql://localhost:8080/ci_intro
#DB_USERNAME=root
#DB_PASSWORD=
My Java Class file is
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCExample {
public static void main(String[] argv) throws IOException,
ClassNotFoundException, SQLException {
System.out
.println("-------- MySQL JDBC Connection Testing ------------");
Properties props = new Properties();
FileInputStream in = new FileInputStream("db.properties");
props.load(in);
in.close();
String driver = props.getProperty("DB_DRIVER_CLASS");
if (driver != null) {
Class.forName(driver);
}
String url = props.getProperty("DB_URL");
String username = props.getProperty("DB_USERNAME");
String password = props.getProperty("DB_PASSWORD");
Connection con = DriverManager.getConnection(url, username, password);
if (con != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
I'm getting below error
-------- MySQL JDBC Connection Testing ------------
Exception in thread "main" java.sql.SQLException: The url cannot be null
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.avn.notificationengine.JDBCExample.main(JDBCExample.java:33)
Remove "#" in your *.properties file. All that follows "#" is comment. Your *.properties should be:
#mysql DB properties
DB_DRIVER_CLASS=com.mysql.jdbc.Driver
DB_URL=jdbc:mysql://localhost:8080/ci_intro
DB_USERNAME=root
DB_PASSWORD=
Related
I was trying to create a dynamic JDBC connection in java to connect to snowflake.
I am stuck at a point ,how can i pass the parameter from my property file into snowflake connection file
Please find the attached code
package com.cisco.export.utils;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.cisco.config.Configuration;
public class SFDbConnection {
public Connection getConnection(Configuration config) throws SQLException{
Connection connection=null;
try {
System.out.println(config.getProp("sf.driverclass"));
System.out.println(config.getProp("sf.url"));
System.out.println(config.getProp("sf.account"));
System.out.println(config.getProp("sf.username"));
System.out.println(config.getProp("sf.password"));
System.out.println(config.getProp("sf.warehouse"));
System.out.println(config.getProp("sf.db"));
System.out.println(config.getProp("sf.schema"));
System.out.println(config.getProp("sf.role"));
Class.forName(config.getProp("sf.driverclass"));
String connectStr = "jdbc:snowflake://mysnowflakeaccount.us-east-1.snowflakecomputing.com";
connection = DriverManager.getConnection()
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
Can some one Help me how can i make the parameters inside the getConnection() dynamic.
Appreciate your help.
Thanks,
Nikhil
The Snowflake JDBC Driver accepts connection properties via the connection-string or via a java.util.Properties class object.
Using the properties in a connection string:
String sfAccount = config.getProp("sf.account");
String sfUsername = config.getProp("sf.username");
String sfPassword = config.getProp("sf.password");
String sfWarehouse = config.getProp("sf.warehouse");
String sfDatabase = config.getProp("sf.db");
String sfSchema = config.getProp("sf.schema");
String sfRole = config.getProp("sf.role");
String connectionString =
String.format("jdbc:snowflake://%s.snowflakecomputing.com/?role=%s&warehouse=%s&db=%s&schema=%s",
sfAccount,
sfRole,
sfWarehouse,
sfDatabase,
sfSchema
);
return DriverManager.getConnection(connectionString, sfUsername, sfPassword);
The com.cisco.config.Configuration class is not a known public API type, but if it can be translated to a java.util.Properties object, you can pass it when building a connection. Here's a direct conversion:
java.util.Properties props = new java.util.Properties();
String connectionString =
String.format(
"jdbc:snowflake://%s.snowflakecomputing.com",
config.getProp("sf.account")
);
props.setProperty("user", config.getProp("sf.username"));
props.setProperty("password", config.getProp("sf.password"));
props.setProperty("role", config.getProp("sf.role"));
props.setProperty("warehouse", config.getProp("sf.warehouse"));
props.setProperty("db", config.getProp("sf.db"));
props.setProperty("schema", config.getProp("sf.schema"));
return DriverManager.getConnection(connectionString, props);
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
public class TestJdbc {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306?hb_student_tracker?useSSL=false&serverTimezone=UTC";
String user = "hbstudent";
String pass = "hbstudent";
try {
System.out.println("Conectiong to database: "+jdbcUrl);
Connection myConn =
DriverManager.getConnection(jdbcUrl,user,pass);
System.out.println("Connection succesful!!!");
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
It fails with the following error:
Conectiong to database:
jdbc:mysql://localhost:3306?hbstudent?useSSL=false&serverTimezone=UTC
java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception:
com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL,
failed to parse the connection string near '?useSSL=false&serverTimezone=UTC'.
What am I doing wrong?
You better check the documentation.
Probably, the problem is in URL. It should be a slash after port and before the database name.
String jdbcUrl = "jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC";
enter image description here
As I have import all required JAR file as shown in above image.
But still it gives me error while trying to connect hive2 via java program.
Error gives me on this line.
Connection connect = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", "");
Error:
18/05/30 17:12:15 INFO jdbc.Utils: Supplied authorities: localhost:10000
18/05/30 17:12:15 INFO jdbc.Utils: Resolved authority: localhost:10000
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.hadoop.hive.common.auth.HiveAuthUtils.getSocketTransport(Ljava/lang/String;II)Lorg/apache/thrift/transport/TTransport;
at org.apache.hive.jdbc.HiveConnection.createUnderlyingTransport(HiveConnection.java:519)
at org.apache.hive.jdbc.HiveConnection.createBinaryTransport(HiveConnection.java:539)
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:309)
at org.apache.hive.jdbc.HiveConnection.<init>(HiveConnection.java:196)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:107)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at Hive_java.main(Hive_java.java:15)
JAVA Code:
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class Hive_java{
private static String driver = "org.apache.hive.jdbc.HiveDriver"; //driver used for hiveserver2
public static void main(String[] args) throws SQLException {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
Connection connect = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", ""); //connecting to default database
Statement state = connect.createStatement();
System.out.println("!!!!!!!!!!Running 1st query!!!!!!!!!!");
System.out.println("Listing tables in hive");
ResultSet show_tables = state.executeQuery("show tables");
while (show_tables.next()) {
System.out.println(show_tables.getString(1));
}
System.out.println("!!!!!!!!!!Running 2nd query!!!!!!!!!!");
System.out.println("Describing slave3_tbl table");
ResultSet describe_table = state.executeQuery("describe slave3_tbl");
while (describe_table.next()) {
System.out.println(describe_table.getString(1) + "\t" + describe_table.getString(2));
}
}
}
I have a Java application and i need it to connect with my MySQL database's SQL script using JDBC.
Here is my Java application:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package basic;
import basic.ScriptRunner;
import javax.swing.*;
import java.sql.*;
import java.io.*;
/**
*
* #author User
*/
public class javaconnect {
Connection conn = null;
public static Connection ConnectDb(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/new","login","pass");
/*As we are creating a connection on a local computer we will write the url as jdbc:mysql://localhost:3306 */
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.runScript(new BufferedReader(new FileReader("D://Java Lenti/EkonomiSoftware/src/basic/new.sql")));
return conn ;
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;}
}
}
The problem is that the Java application connects through MySQL Server, not through the SQL Script. I think the problem is at Connection parameters I gave. Can anyone guide me how to change the connection to make it connect to the SQL script not to the server?
It worked for me:
package com.spring.sample.controller;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection) DriverManager
.getConnection(
"",
"", "");
ScriptRunner runner = new ScriptRunner(conn, false, false);
runner.runScript(new BufferedReader(new FileReader("new.sql")));
} catch (Exception e) {
e.printStackTrace();
}
}
}
new.sql
insert into hello(name) values ('test');
May be there're some mistakes at your sql file.
Could someone explain to me where I'm going wrong with the following code:
package newdbtet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewDBTet {
public static void main(String[] args) throws InstantiationException, SQLException, IllegalAccessException {
try {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "evidence_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
System.out.println("Connected to the database");
conn.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewDBTet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Exception error:
Jul 16, 2012 2:59:24 PM newdbtet.NewDBTet main
SEVERE: null
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Does this mean that I haven't installed the driver / library correctly? Sorry - not the best with Java.
download the MySQL Driver for Eclipse/Java then you should get a .jar driver. then right click on your class and go to build path. finally add the external library to your project, that should solve your problem.
Add the JDBC driver .jar into the class path with a -cp command, i.e. - java -cp MysqlDriver.jar; MyProgram or add the .jar into the build path in your IDE.