Connect to MySQL using JDBC driver through a proxy [duplicate] - java

This question already has an answer here:
MySQL Connect via proxy in Java
(1 answer)
Closed 2 years ago.
In Java, I would like to make a connection to a MySQL server which is on the web from a client computer that is behind a http proxy. I have read few solutions some say http tunnelling might work and some suggest a very old link from oracle which is not available anymore. So the question is:
How can we connect to a MySQL server from a computer which is behind a http proxy?

You can try the following code and see if it works. It worked for me over TCP
package indika.jdbc.connectivity;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class ConnectOverProxy {
public static void main(String[] args) {
new ConnectOverProxy();
}
public ConnectOverProxy() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
Properties info = new Properties();
//info.put("proxy_type", "4"); // SSL Tunneling
info.put("proxy_host", "[proxy host]");
info.put("proxy_port", "[proxy port]");
info.put("proxy_user", "[proxy user]");
info.put("proxy_password", "[proxy password]");
info.put("user", "[db user]");
info.put("password", "[db pass word]");
conn = DriverManager.getConnection("jdbc:mysql://[db host]/",info);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select NOW()");
rs.next();
System.out.println("Data- " + rs.getString(1));
rs.close();
stmt.close();
conn.close();
} catch (SQLException er) {
er.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Also look at "http://www.idssoftware.com/jdbchttps.html", However I have not used this personally.

Related

NonWritableChannelException when trying to update an Access database

Using UCanAccess for the first time for a project and I am having a lot of trouble inserting a row into one of my database tables (in Microsoft Access).
My code makes sense but once I execute I end up getting the same error every time, even though NetBeans is able to connect to my database.
package Vegan;
import java.sql.Connection;
import java.sql.DriverManager;
public class connectionString {
static Connection connection = null;
public static Connection getConnection()
{
try
{
connection = DriverManager.getConnection("jdbc:ucanaccess://C://MyDatabase1.accdb");
System.out.println("---connection succesful---");
}
catch (Exception ex)
{
System.out.println("Connection Unsuccesful");
}
return connection;
}
package Vegan;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DB {
private static ResultSet rs = null;
private static PreparedStatement ps = null;
private static Connection connection = null;
public DB() {
connection = connectionString.getConnection();
}
public void AddTest() {
try {
String sql = "INSERT INTO CategoryTbl(CategoryName) VALUES (?)";
ps = connection.prepareStatement(sql);
ps.setString(1, "Flours");
ps.executeUpdate();
System.out.println("Inserted");
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage().toString());
}
}
After that, when I execute the the AddTest() method, I get this system output:
run:
---connection succesful---
java.nio.channels.NonWritableChannelException
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:724)
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:297)
UCAExc:::3.0.6 null
at com.healthmarketscience.jackcess.impl.PageChannel.writePage(PageChannel.java:234)
at com.healthmarketscience.jackcess.impl.TableImpl.writeDataPage(TableImpl.java:1375)
at com.healthmarketscience.jackcess.impl.TableImpl.addRows(TableImpl.java:1624)
at com.healthmarketscience.jackcess.impl.TableImpl.addRow(TableImpl.java:1462)
at net.ucanaccess.converters.UcanaccessTable.addRow(UcanaccessTable.java:44)
at net.ucanaccess.commands.InsertCommand.insertRow(InsertCommand.java:101)
at net.ucanaccess.commands.InsertCommand.persist(InsertCommand.java:148)
at net.ucanaccess.jdbc.UcanaccessConnection.flushIO(UcanaccessConnection.java:315)
at net.ucanaccess.jdbc.UcanaccessConnection.commit(UcanaccessConnection.java:205)
at net.ucanaccess.jdbc.AbstractExecute.executeBase(AbstractExecute.java:161)
at net.ucanaccess.jdbc.ExecuteUpdate.execute(ExecuteUpdate.java:50)
at net.ucanaccess.jdbc.UcanaccessPreparedStatement.executeUpdate(UcanaccessPreparedStatement.java:253)
at Vegan.DB.AddTest(DB.java:91)
at Vegan.TestDB.main(TestDB.java:17)
BUILD SUCCESSFUL (total time: 1 second)
With no changes being made to the database when I check on it again Access.
What could be causing this, and what does the error message mean? Thank you
"java.nio.channels.NonWritableChannelException" means that the database file cannot be updated. In your case that was because the database file was in the root folder of the Windows system drive (C:\) and mere mortals have restricted permissions on that folder.
Solution: Move the database file to a folder where you have full write access.

Windows authentication failing when connecting to sql server using JDBC

I have SQL server on a machine under the domain DOM005 and I am trying to connect to it using JDBC driver from my local machine that is in another domain. I am using windows authentication for the connection through domain administrator account.
I cannot use "integratedSecurity=true" in my connection URL since both machines are in different domain. Hence I use "authentication=ActiveDirectoryIntegrated" but I am getting the following error:
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'DOM005\administrator'. ClientConnectionId:84224bcd-d2f1-4386-aadf-397c1ef3eadf
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:251)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:3077)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2360)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2346)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:6276)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1793)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1404)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1068)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:904)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:451)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1014)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at TestJDBCsqlServer.main(TestJDBCsqlServer.java:23)
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class TestJDBCsqlServer {
private static final String SQLSERVER_URL_NTLM = "jdbc:sqlserver://10.20.13.4:1433;databaseName=DB1;authentication=ActiveDirectoryIntegrated";
public static void main(String[] args) throws Exception {
boolean isNTLM = true;
Connection conn = null;
Statement stmt = null;
if(isNTLM){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(SQLSERVER_URL_NTLM, "DOM005\\administrator", "abc");
stmt = conn.createStatement();
ResultSet set = stmt.executeQuery("select 1");
System.out.println("NTLM connection is successful");
set.next();
System.out.println(set.getString(1));
}finally{
if(stmt != null)
stmt.close();
if(conn!=null)
conn.close();
}
}
}
}
Can anyone help me resolve the issue?

java style database connection on android

package com.example.wgame;
import java.sql.Connection;
import java.sql.DriverManager;
import android.util.Log;
public class connDB {
Connection conn = null;
public static Connection connectDB() {
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:wSdict.sqlite");
Log.v("DBCon","Connected!");
return conn;
}catch (Exception r) {
Log.e("DBCon","Not Connected");
return null;
}
}
}
is it possible to connect my sqlite database file this way on android and not having to use SQLiteHelper class ?
No you can not. Android uses sqlite3, and can only be accessed by the API provided by android. There is no third party library or any helper class to achieve this.
refer this link for more info.
http://developer.android.com/reference/android/database/package-summary.html

Unable to connect to SSAS using olap4j on Linux

I wish to connect to SSAS 2012 using Java and have tried olap4j driver for the same.
I am working on Linux (Ubuntu 14.04) platform.
I have read that Olap4j works for Windows but will it work on Linux ?
I have written some Java code which gives runtime error. This error is because the Linux machine is unable to connect to SSAS.
I have set http access and IIS server and using msmdpump.dll to connect.
Below is the Java code and the error.:
CODE
package ssas;
import java.sql.Connection;
//import java.lang.*;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.olap4j.Cell;
import org.olap4j.CellSet;
import org.olap4j.OlapConnection;
import org.olap4j.OlapException;
import org.olap4j.OlapStatement;
import org.olap4j.OlapWrapper;
import org.olap4j.Position;
import org.olap4j.metadata.Member;
public class connexionSSAS
{
public static void main(String[] args) throws ClassNotFoundException,
OlapException {
Class.forName("org.olap4j.driver.xmla.XmlaOlap4jDriver");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:xmla:Server=http://01XXXXXXXX/olap/msmdpump.dll;" +
"Catalog=sample_Cube");
} catch (SQLException e) {
e.printStackTrace();
}
if (null == connection) {
System.out.println("Cnul");
}
OlapWrapper wrapper = (OlapWrapper) connection;
OlapConnection olapConnection = null;
try {
olapConnection = wrapper.unwrap(OlapConnection.class);
} catch (SQLException e) {
e.printStackTrace();
}
olapConnection.setCatalog("sample_Cube");
OlapStatement statement = null;
CellSet cellSet = null;
System.out.println(olapConnection.getCatalog());
try {
statement = (OlapStatement) olapConnection.createStatement();
CellSet=statement.executeOlapQuery(
"Summarize(FactDiagnosis,FactDiagnosis[ImportDateKey])");
args}
catch(SQLException e) {
e.printStackTrace();
}
}
}
ERROR
Exception in thread "main" java.lang.RuntimeException: org.olap4j.OlapException: This connection encountered an exception while executing a query.
at org.olap4j.driver.xmla.DeferredNamedListImpl.getList(DeferredNamedListImpl.java:96)
at org.olap4j.driver.xmla.DeferredNamedListImpl.size(DeferredNamedListImpl.java:116)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.getOlapDatabase(XmlaOlap4jConnection.java:451)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.getOlapCatalogs(XmlaOlap4jConnection.java:527)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.setCatalog(XmlaOlap4jConnection.java:483)
at ssas.connexionSSAS.main(connexionSSAS.java:49)
Caused by: org.olap4j.OlapException: This connection encountered an exception while executing a query.
at org.olap4j.driver.xmla.XmlaHelper.createException(XmlaHelper.java:43)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.executeMetadataRequest(XmlaOlap4jConnection.java:878)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getMetadata(XmlaOlap4jDatabaseMetaData.java:137)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getMetadata(XmlaOlap4jDatabaseMetaData.java:67)
at org.olap4j.driver.xmla.XmlaOlap4jDatabaseMetaData.getDatabaseProperties(XmlaOlap4jDatabaseMetaData.java:1044)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.makeConnectionPropertyList(XmlaOlap4jConnection.java:324)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.generateRequest(XmlaOlap4jConnection.java:1037)
at org.olap4j.driver.xmla.XmlaOlap4jConnection.populateList(XmlaOlap4jConnection.java:849)
at org.olap4j.driver.xmla.DeferredNamedListImpl.populateList(DeferredNamedListImpl.java:136)
at org.olap4j.driver.xmla.DeferredNamedListImpl.getList(DeferredNamedListImpl.java:90)
... 5 more
This code will run if I comment the statements containing 'OlapConnection'.
Any help would be appreciated.

Java JDBC connection to MySQL

I am trying to connect to mysql from java web application in eclipse.
Connection con = null;
try {
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/db_name","root" ,"");
if(!con.isClosed())
System.out.println("Successfully connected to " +
"MySQL server using TCP/IP...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {
System.out.println(e.toString());
}
}
I am always getting the Exception: com.mysql.jdbc.Driver
I have downloaded this jar http://forums.mysql.com/read.php?39,218287,220327
import it to the "java build path/lib"
the mysql version is 5.1.3 under.
running:
mysql 5.1.3 (db is up and running queries form PHP)
windows XP
Java EE
you say you placed the JAR on the build path, is it in the runtime class path? you said "java EE", so i assume you are deploying this as a web app? in that case you need to put the JDBC JAR file into WEB-INF/lib of your web app.
You have to download the mysql jdbc connector und use it as lib. You can get it here:
http://www.mysql.com/downloads/connector/j/
Have u added it in your build configuration also, if the location is not in classpath then it wont work by mere keeping it in lib folder.
check your .classpath file
You can find a full documentation (Chapter 14) on how to connect to MySQL database through any web application (JBOSS, Glassfish etc...), if you download the MySQL JDBC driver.
After doing your configuration, you have to get the connection from your server by getting your server connection ressource.
Here is a sample code of how to get a connection ressource from a Glassfish server :
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
#Stateless
public class AppConnection {
private InitialContext context;
private DataSource source;
private Connection connection;
public AppConnection() {
this.initConnection();
}
private void initConnection() {
try {
context = new InitialContext();
source = (DataSource)context.lookup("jdbc/MySQLDataSource");
connection = source.getConnection();
} catch (SQLException ex) {
Logger.getLogger(AppConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (NamingException ex) {
Logger.getLogger(AppConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Connection getContextConnection() {
return connection;
}
public void closeContextConnection() throws SQLException {
if(connection != null) {
connection.close();
}
}
}
Note that this class is an EJB and "jdbc/MySQLDataSource" is the name of the connection configured on your server. It can be inject in other EJB to get your current connection and create other needed objects as Statements or Resultsets.

Categories