I am trying to connect to a cube i created in SSMS,using JDBC (My database name is AdventureWorks).
Where should i put connection URL, and
Is my connection URL correct or not?
I have already added the jar files for olap4j, but on executing i am getting classNotFoundException. This is the code I have used:
package oLapConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.olap4j.OlapConnection;
public class Olap {
public static void main(String [] args) throws SQLException {
// Load the driver
try {
Class.forName("org.olap4j.driver.xmla.XmlaOlap4jDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Connect
final Connection connection =
DriverManager.getConnection(
// This is the SQL Server service end point.
"jdbc:xmla:Server=http://localhost/olap/msmdpump.dll;Catalog=myCatalog"
// Tells the XMLA driver to use a SOAP request cache layer.
// We will use an in-memory static cache.
+ ";Cache=org.olap4j.driver.xmla.cache.XmlaOlap4jNamedMemoryCache"
// Sets the cache name to use. This allows cross-connection
// cache sharing. Don't give the driver a cache name and it
// disables sharing.
+ ";Cache.Name=MyNiftyConnection"
// Some cache performance tweaks.
// Look at the javadoc for details.
+ ";Cache.Mode=LFU;Cache.Timeout=600;Cache.Size=100",
// XMLA is over HTTP, so BASIC authentication is used.
null,
null);
// We are dealing with an olap connection. we must unwrap it.
final OlapConnection olapConnection = connection.unwrap(OlapConnection.class);
// Check if it's all groovy
ResultSet databases = olapConnection.getMetaData().getDatabases();
databases.first();
System.out.println(
olapConnection.getMetaData().getDriverName()
+ " -> "
+ databases.getString(1));
// Done
connection.close();
}
}
Thanks for you help. You can tell me any related articles or links that would help. Please guide me if the question is not clear.
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
am getting an exception as java.sql.Connection.prepareStatement(String) because con is null, I don't know why as I have already added MySQL Connector jar file.
import java.sql.Connection;
import java.sql.PreparedStatement;
public class Studentdao {
public static boolean insertStudenttoDB(Student st) {
boolean f=false;
try {
Connection con =CP.createc();
//jdbc code
String q="insert into students(sname,sphone scity)values(?,?,?)";
PreparedStatement pstmt=con.prepareStatement(q);
pstmt.setString(1,st.getStudentname());
pstmt.setString(2,st.getStudentcity());
pstmt.setLong(3,st.getStudentphone());
//execute
pstmt.executeUpdate();
f=true;
}
catch(Exception e) {
e.printStackTrace();
}
return f;
}
}
This is my connection program
import java.sql.Connection;
import java.sql.DriverManager;
public class CP {
static Connection con;
//load driver
public static Connection createc() {
try {
Class.forName("com.sql.jdbc.Driver");
//creating connection
String user="mysql";
String password="mysql";
String url="jdbc:mysql://localhost:3306/student_manage";
con=DriverManager.getConnection(url,user,password);
}catch(Exception e) {
e.printStackTrace();
}
return con;
}
}
Incorrect class name
You appear to have an incorrect class name, if you are using the Connector/J product as your JDBC driver.
Section 3.6.1 of the Connector/J manual shows the use of "com.mysql.cj.jdbc.Driver" versus your use of "com.sql.jdbc.Driver". Here is their code example:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!
public class LoadDriver {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
}
}
DataSource
Note that your use of Class.forName is generally not needed in modern Java. The JDBC architecture was years ago revamped so that now drivers are automatically located and loaded using the Java Service Provider Interface (SPI) technology.
I do suggest you make a habit of using a DataSource to obtain connections rather than calling on the DriverManager. Using DataSource makes your code much more flexible. You will be able to switch JDBC drivers, add connection pooling, and externalize configuration info (server address, database name, user name, password, etc.) for deployment.
Usually your JDBC driver comes with a basic implementation of DataSource. Check the documentation for all the various options you can set, specific to your database (MySQL in this case).
For MySQL, I understand the implementation of DataSource currently provided in Connector/J is com.mysql.cj.jdbc.MysqlDataSource. Caveat: I make regular use of Postgres & H2, not MySQL, so I may not be up-to-date.
See my Answer to another Question for source code of a full example of connecting and working with MySQL. Here are the parts relating to DataSource and Connection.
private DataSource configureDataSource ( )
{
System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );
com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() ); // Implementation of `DataSource` bundled with H2.
dataSource.setServerName( "db-mysql-sfo3-422-do-user-8982-1.x.db.ondigitalocean.com" );
dataSource.setPortNumber( 24_090 );
dataSource.setDatabaseName( "defaultdb" );
dataSource.setUser( "scott" );
dataSource.setPassword( "tiger" );
return dataSource;
}
Early in the lifecycle of your app, instantiate and retain the DataSource object returned from that method. Remember, a DataSource holds only the configuration details; it is not an open resource itself, and need not be closed.
DataSource dataSource = this.configureDataSource();
To open a connection, pass the DataSource to your method that wants to connect to the database.
private void dumpTable ( DataSource dataSource ) { … }
Here is a piece of that dumpTable method.
Notice the use of try-with-resources syntax to automatically close the open resources in the order in which they were declared, even in case of failure with exceptions being thrown.
String sql = "SELECT * FROM event_ ;";
try (
Connection conn = dataSource.getConnection() ; // 🡄 Use the passed `DataSource` object to ask for a `Connection` object.
Statement stmt = conn.createStatement() ;
ResultSet rs = stmt.executeQuery( sql ) ;
)
{
…
}
catch ( SQLException e )
{
e.printStackTrace();
}
here's the code I tried to connect java class with mysql. Make sure you have to add the required driver to your libraries.
import java.sql.Connection;
import java.sql.DriverManager;
public class Server {
public static Connection getConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
String urls = "127.0.0.1";//you can even replace this with localhost
String username = "yourusername";
String password = "1234";
Connection conn = DriverManager.getConnection("jdbc:mysql://"+urls+":3306/yourdb?useUnicode=yes&characterEncoding=UTF-8", username, password);
return conn;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
I would like to write to SQL database by Java based Azure Functions.
I have SQLconnstring of JDBC in local.settings.json. How to get this connection correctly from settings file instead of hard coding to java file?
package com.function;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Azure Functions with Azure Storage Queue trigger.
*/
public class TopicTriggerSQLOutput {
/**
* This function will be invoked when a new message is received at the specified path. The
message contents are provided as input to this function.
*/
#FunctionName("TopicTriggerSQLOutput")
public void run(
#ServiceBusTopicTrigger(
name = "message",
topicName = "newtopic",
subscriptionName = "newsubscription",
connection = "topicconnstring"
) String message,
final ExecutionContext context
) {
/*Creating SQL Connection. I need help here:
*/
/*How to get connection string from local.settings.json instead of hard coding?*/
String connectionUrl =
"jdbc:sqlserver://yourserver.database.windows.net:1433;"
+ "database=AdventureWorks;"
+ "user=yourusername#yourserver;"
+ "password=yourpassword;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "loginTimeout=30;";
try (Connection connection = DriverManager.getConnection(connectionUrl);) {
// SQL Code here.
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
//context.getLogger().info(message);
}
}
You can use System.getenv("") to get the value from local.settings.json file. For example, we can use String connectionUrl =System.getenv("SQLConnectionString"); to get the sql connection string in the local.settings.json file.
I have created a simple Java connection script in Java to connect to a database shown below.
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class dbconn {
public static void main(String[] args) throws ClassNotFoundException
{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:C:/Program Files (x86)/Spiceworks/db/spiceworks_prod.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
Now I have tested this connection via some SQL queries inside the dbconn script and it works.
However my question is, how would Icall this instance of the database into another form in the same project to preform the same SQL queries which are:
ResultSet resultSet = null;
resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next())
{
System.out.println("EMPLOYEE Email: " + resultSet.getString("email"));
}
You can retain and reuse the Connection, saving it probably in some static field. If you access it from multiple threads, SQLite must work in the Serialized mode. You must have the code somewhere to re-establish the connection if it has been lost for some reason.
If the use of Connection is not heavy, you can also have some method that opens it and close when no longer needed, better inside the finally block.
So I just finished learning JDBC this weekend and have successfully transferred my code from the main method into an MVC app. The purpose of this application is to hold a roster of players and display a users credentials if requested. The program works great and when I request a url like...
http://localhost:8084/gmustudent/players?id=1
I get the correct output for that player! The problem is I am performing the database connection within my PlayersDAO class and I assume that this is not the "best" way to do this. So I have two questions.
Is there a way to perform the database connection within the web.xml
file or some other file so that when the server is initially started it will
immediately perform the connection to the database and be ready to
query when asked?
And is this actually a better alternative to having the connection in the DAO or would this have unforeseen negative drawbacks. AKA would a constant connection to my database be exactly what I do not want?
Any comments or links would be greatly appreciated. And I'll share the code I currently have for my DAO class so that you can see what I have so far. Thank you all!
package com.jdbc.test;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
public class PlayersDAO
{
public static Players viewPlayer(int id) throws SQLException
{
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
Players playerObject = null;
try
{
String url = "jdbc:mysql://localhost:3306/gmustudent";
String username = "root";
String password = "root";
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException error)
{
System.out.println("Error: " + error.getMessage());
}
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
resultSet = statement.executeQuery("SELECT * FROM players WHERE id = " + id);
if(resultSet.next())
playerObject = new Players(resultSet.getLong("id"), resultSet.getString("name"), resultSet.getString("position"), resultSet.getString("height"), resultSet.getString("year"), resultSet.getString("hometown"), resultSet.getString("highschool"), resultSet.getString("headshot"));
}
finally
{
if (connection != null) try{connection.close();} catch(SQLException ignore) {}
if (statement != null) try{statement.close();} catch(SQLException ignore) {}
if (resultSet != null) try{resultSet.close();} catch(SQLException ignore) {}
}
return playerObject;
}
}
You can create database connection in web.xml file by using resource. I hope this tutorial will help you.
http://viralpatel.net/blogs/database-connection-pooling-tomcat-eclipse-db/
You can use JDBC Connection Pooling.It can provide significant benefits in terms of application performance, concurrency and scalability.
IMHO, its always a good approach to hide the instantiation details of any resources. You can use factory method to do this. The advantage of this approach is that you can always change the way to manage the resources - e.g. You can have one instance of JDBCConnection per DAO or you can have connection pool. Any time you can provide your development specific db connection, test specific db connection or production db connection. All these details you can hide doing such approach.
I just got some errors in my Java oracle connectivity. Could anyone please help me with this? I have enclosed the code below. I'm getting this error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver..
this is the code
package md5IntegrityCheck;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class MD5IntegrityCheck
{
public static void main(String[] args)
{
String fileName,Md5checksum ,sql;
Connection con;
PreparedStatement pst;
Statement stmt;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con1 =DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
}
catch(Exception ee)
{ee.printStackTrace( );}
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
/****insert method******/
private static void setDefaultCloseOperation(String exitOnClose) {
// TODO Auto-generated method stub
}
static void setVisible(boolean b) {
// TODO Auto-generated method stub
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:RecordTbl","scott","tiger");
PreparedStatement pst = con.prepareStatement("insert into RecordTbl values(?,?)");
String fileName = null;
pst.setString(1,fileName);
String Md5checksum = null;
pst.setString(2,Md5checksum);
int i=pst.executeUpdate( );
System.out.println("recorded in database");
con.close( );
}
catch(Exception ee)
{ee.printStackTrace( );}
}
}
if (args.length <= 0)
{
Md5Gui gui = new Md5Gui();
gui.runGui();
}
else
{
DoWork runningProgram = new DoWork();
runningProgram.run(args);
}
}
}
Your question is vague:
In your exception, you're getting a ClassNotFoundException for a driver that pertains to MySQL. On your code, you're using a JDBC-ODBC Driver.
My suggestion is how did you configure your database connectivity. Let's start from there. Also, it would be better to add the exception stack trace to see exactly what's happening.
Edit: Visit this example if you want to know how to configure JDBC connection to Oracle Database. I fully recommend using the Oracle JDBC driver directly instead of connecting it to an ODBC Bridge.
I assume you might be running your program in IDE, so please add drivers jars in the classpath of project
You should look into any 3rd party library you're using whether there a MySQL database driver is needed. Although you write you are using an Oracle driver (though the JdbcOdbcDriver is provided by Java itself and has nothing to do with Oracle DB's) the exception is clearly stating that the MySQL is requested. Since you don't use it in the code you provided, there must be another database connection using MySQL.