a very simple snippet:
private static final String mydriver="net.sourceforge.jtds.jdbc.Driver";
private static final String myurl="jdbc:jtds:sqlserver://xx.xxx.xxx.xxx/myDatabase";
private Connection myconn;
[stuff]
public int connect(final String username,final String password){
try{
Class.forName(mydriver);
myconn=DriverManager.getConnection(myurl,username,password);
} catch (ClassNotFoundException e) {
return 1;
} catch (SQLException e) {
return 2;
}
return 0;
}
Note please, a number of points:
1. As a control, I have installed a very simple client called MSSQL Client by Pascal Nunes. It takes IP,DB,user,pwd and connects SUCCESSFULLY (without specifying port 1433). I have verified with Pascal himself, he is using jTDS 1.2.7, so I made sure my jTDS version was in line with his.
2. I have tried a number of parameters and parameter combinations, but nothing seems to work
3. I know neither the server nor the network can be responsible, since Pascal's app works
4. Pascal's app has "Full Network Access" according to my Nexus 7. I have given my app:
android.permission.INTERNET in the manifest. I don't see any other permissions that might apply, but I'm new at this
5. Otherwise, there must be jTDS parameters that need to be morphed away from their default. If so, damned if I can find 'em.
Any ideas?
I am not sure if you still face this problem. Happened to find this question while searching for something else. But I believe I am the Pascal you mention and MSSQL client is the application you are referring to. I will try to answer your question as best I can:
jtds doesn't require you to specify a port. 1433 is taken by default.
Building a connection string is very well documented for jtds. This is how I build the connection string:
String properties = ";domain=" + domain + ";user=" + id + ";password=" + pass;
String conn = "jdbc:jtds:sqlserver://" + Server + "/" + Database + properties;
The app only needs network(android.permission.INTERNET) access.
Hope the answer helps you and others who come along.
Related
I am trying to connect to Hive2 server via JDBC with kerberos authentication. After numerous attempts to make it work, I can't get it to work with the Cloudera driver.
If someone can help me to solve the problem, I can greatly appreciate it.
I have this method:
private Connection establishConnection() {
final String driverPropertyClassName = "driver";
final String urlProperty = "url";
Properties hiveProperties = config.getMatchingProperties("hive.jdbc");
String driverClassName = (String) hiveProperties.remove(driverPropertyClassName);
String url = (String) hiveProperties.remove(urlProperty);
Configuration hadoopConfig = new Configuration();
hadoopConfig.set("hadoop.security.authentication", "Kerberos");
String p = config.getProperty("hadoop.core.site.path");
Path path = new Path(p);
hadoopConfig.addResource(path);
UserGroupInformation.setConfiguration(hadoopConfig);
Connection conn = null;
if (driverClassName != null) {
try {
UserGroupInformation.loginUserFromKeytab(config.getProperty("login.user"), config.getProperty("keytab.file"));
Driver driver = (Driver) Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
conn = DriverManager.getConnection(url, hiveProperties);
} catch (Throwable e) {
LOG.error("Failed to establish Hive connection", e);
}
}
return conn;
}
URL for the server, that I am getting from the properties in the format described in Cloudera documentation
I am getting an exception:
2018-05-05 18:26:49 ERROR HiveReader:147 - Failed to establish Hive connection
java.sql.SQLException: [Cloudera][HiveJDBCDriver](500164) Error initialized or created transport for authentication: Peer indicated failure: Unsupported mechanism type PLAIN.
at com.cloudera.hiveserver2.hivecommon.api.HiveServer2ClientFactory.createTransport(Unknown Source)
at com.cloudera.hiveserver2.hivecommon.api.ZooKeeperEnabledExtendedHS2Factory.createClient(Unknown Source)
...
I thought, that it is missing AuthMech attribute and added AuthMech=1 to the URL. Now I am getting:
java.sql.SQLNonTransientConnectionException: [Cloudera][JDBC](10100) Connection Refused: [Cloudera][JDBC](11640) Required Connection Key(s): KrbHostFQDN, KrbServiceName; [Cloudera][JDBC](11480) Optional Connection Key(s): AsyncExecPollInterval, AutomaticColumnRename, CatalogSchemaSwitch, DecimalColumnScale, DefaultStringColumnLength, DelegationToken, DelegationUID, krbAuthType, KrbRealm, PreparedMetaLimitZero, RowsFetchedPerBlock, SocketTimeOut, ssl, StripCatalogName, transportMode, UseCustomTypeCoercionMap, UseNativeQuery, zk
at com.cloudera.hiveserver2.exceptions.ExceptionConverter.toSQLException(Unknown Source)
at com.cloudera.hiveserver2.jdbc.common.BaseConnectionFactory.checkResponseMap(Unknown Source)
...
But KrbHostFQDN is already specified in the principal property as required in the documentation.
Am I missing something or is this documentation wrong?
Below is the one of the similar kind of problem statement in Impala (just JDBC engine changes others are same) that is resolved by setting "KrbHostFQDN" related properties in JDBC connection string itself.
Try to use the URL below. Hopefully works for u.
String jdbcConnStr = "jdbc:impala://myserver.mycompany.corp:21050/default;SSL=1;AuthMech=1;KrbHostFQDN=myserver.mycompany.corp;KrbRealm=MYCOMPANY.CORP;KrbServiceName=impala"
I suppose that if you are not using SSL=1 but only Kerberos, you just drop that part from the connection string and don't worry about setting up SSL certificates in the java key store, which is yet another hassle.
However in order to get Kerberos to work properly we did the following:
Install MIT Kerberos 4.0.1, which is a kerberos ticket manager. (This is for Windows)
This ticket manager asks you for authentication every time you initiate a connection, creates a ticket and stores it in a kerberos_ticket.dat binary file, whose location can be configured somehow but I do not recall exactly how.
Finally, before launching your JAVA app you have to set an environment variable KRB5CCNAME=C:/path/to/kerberos_ticket.dat. In your java app, you can check that the variable was correctly set by doing System.out.println( "KRB5CCNAME = " + System.getenv( "KRB5CCNAME" ) ). If you are working with eclipse or other IDE you might even have to close the IDE,set up the environment variable and start the IDE again.
NOTE: this last bit is very important, I have observed that if this variable is not properly set up, the connection wont be established...
In Linux, instead MIT Kerberos 4.0.1, there is a program called kinit which does the same thing, although without a graphical interface, which is even more convenient for automation.
I wanted to put it in the comment but it was too long for the comment, therefore I am placing it here:
I tried your suggestion and got another exception:
java.sql.SQLException: [Cloudera]HiveJDBCDriver Error
creating login context using ticket cache: Unable to obtain Principal
Name for authentication .
May be my problem is, that I do not have environment variable KRB5CCNAME set.
I, honestly, never heard about it before.
What is supposed to be in that ticket file.
I do have, however, following line in my main method:
System.setProperty("java.security.krb5.conf", "path/to/krb5.conf");
Which is supposed to be used by
UserGroupInformation.loginUserFromKeytab(config.getProperty("login.user"), config.getProperty("keytab.file"));
to obtain the kerberos ticket.
To solve this issue update Java Cryptography Extension for the Java version that you use in your system.
Here's the link when you can download JCE for Java 1.7
Uncompress and overwrite those files in $JDK_HOME/jre/lib/security
Restart your computer.
I know this has been asked a hundred times and I think I have read all the posts and tried every variation of the solutions. I'm using NetBeans and new to it. I'm sure I'm just missing some small step because it seems like its just not seeing the driver that I added to the library. This is the first time I have tried to connect to a database so please be gentle.
try
{
String host = "jdbc:sqlserver://Server:1433;Database";
String uName = "User";
String uPass = "Password";
Connection con = DriverManager.getConnection(host,uName,uPass);
System.out.println("Your are connected to SQLServer 2014");
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
You forgot to register the jdbc driver class.
Call
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
before calling Connection con = DriverManager.getConnection(host,uName,uPass);.
It will resolve the issue.
UPDATE
In documentation for new jdbc drivers it is declared that this step is not necessary. But in practical work, I have found that this step is required even for new drivers, otherwise you will get "No suitable driver found" error. This error occurs sometimes, for example it does not occur when you are making and running a console jar-application, but occurs when you have created and deployed a web-application.
So, I advise to register the jdbc driver class before getting the database connection via DriverManager.getConnection() call.
I am learning Java and trying to put together a simple App containing a few jTables connected to database that can be updated etc. To do this I have created a database with a few tables through Netbeans which I understand (and wish) to be embedded in the final distributable app.
I am following the Programming Knowledge tutorials on Youtube to create most of the GUI. Everting is OK as long as I open the Services tab on Netbeans and manually right-click my database(testDB) and click Start Server. Then when I run the following code I get a successful connection:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
//Register JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
//Open a connection
String DB_URL = "jdbc:derby://localhost:1527/testDB";
String u_name = jTextField1.getText();
String p_word = jPasswordField1.getText();
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/testDB",u_name,p_word);
JOptionPane.showMessageDialog(null,"Details Correct - Connection established");
Close_me();
Open_Table_GUI(u_name,p_word);
}
catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
However if I run that code WITHOUT manually clicking on start server I get the following:
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused.
I have read the apache documentation and due to my level of inexperience I am not getting anywhere.
I have also checked out the answers to similar connection questions on here but again I can't seem to relate the issue in a way that works.
The ultimate goal for me is to have an app I can distribute to run on windows machines that will have the database/tables all included individually editable etc. I would hope to eventually create a database that resides on a shared drive and each individual can connect to automatically - but that's way down the line for now.
My request here is that someone can help me understand what I need to change in my code so that the "Start Server" is automatically done.
Thanks in advance for nay response.
OK guys so I found code that seems to work for me from a question asked on here by LMS
private void setup(){
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection=DriverManager.getConnection("jdbc:derby:sheet;create=true","test","1234");
statement=connection.createStatement();
}
catch(ClassNotFoundException cnf){
System.out.println("class error");
}
catch(SQLException se){
System.out.println(se);
}
}
If anyone cares to link me to a reason why this in fact works that would be great, I'm assuming the Embedded driver doesn't go through the port and just looks within the project??
Anyway initially this seems to be solved!!
Please check your Server setting i.e.
-username and pwd in your program
and check that did you start the Derby server and is it listening at port 1527?
This question already has answers here:
IOException: Network adapter could not establish the connection [duplicate]
(2 answers)
Closed 5 years ago.
I'm randomly getting "IO Error: The Network Adapter could not establish the connection" when trying to connect to an Oracle database through Java. Sometimes I have to run my application a couple times before it stops throwing the error.
// initializes database connection
private static Connection initializeDatabaseConnection(Properties prop) {
System.setProperty("oracle.net.tns_admin", prop.getProperty("tnsLocation"));
try {
Class.forName("oracle.jdbc.OracleDriver");
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
}
String dbURL = "jdbc:oracle:thin:#" + prop.getProperty("serviceName");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
Connection conn = null;
try {
conn = DriverManager.getConnection(dbURL, username, password);
}
catch (SQLException ex)
{
System.out.println("Error initializing database connection. " + ex.getMessage());
System.exit(1);
}
return conn;
}
Any ideas as to why it throws that error randomly? I'm using JDK 1.7 with the ojdbc6.jar driver.
Download PingPlotter and turn it on (leave it running for 24 hours or so). Watch the historical graph, you'll likely find the IP address dropping or response times going through the roof at the same time your app can't connect to Oracle. You don't have a logic error, either the server is drastically overloaded, or you've got major congestion between you and it. Are you connecting through a VPN?
http://www.pingplotter.com/
Or just use ping from the command line in continuous mode for an hour or so:
ping -t <IP address or hostname>
Ping plotter doesn't ping as often and it creates nice graphs.
If you are working remotely, then it could be your ISP. Otherwise, talk to the network administrator or the DBA.
Obviously you can't go into production with a poor DB connection, so hopefully you just see this issue from your development environment. Try deploying to the machine where you plan to run the application eventually and see if it improves.
If there is nothing you can do to make it better, I recommend increasing your initial login timeout for your JDBC driver.
Google JDBC setLoginTimeout
Here is an example, although there are several ways to go about it, depending on your driver.
Connection timeout for DriverManager getConnection
Background: Working on an application to be run on an Apache server hosted by Network Solutions. Friend/Customer insisted on using an Access Database instead of SQL database.
Current Problem: Wrote a Java test program to make sure I can connect to the database before I dive head first into writing the whole backend. When I run this code on the JVM of the apache server the final product will be hosted:
import java.sql.*;
import java.io.*;
public class test {
public static void main(String[] args) {
try {
Class driverClass = Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
DriverManager.registerDriver((Driver) driverClass.newInstance());
// set this to a MS Access DB you have on your machine
String filename = new File(".").getCanonicalPath() + "/ITEMS.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim(); // add on to the end
// now we can get the connection from the DriverManager
System.out.println(database);
Connection conn = DriverManager.getConnection( database );
} catch (Exception e) {
System.out.println("Error: " + e.getMessage() + " " + e.getLocalizedMessage());
e.printStackTrace();
}
}
}
I get a null pointer exception on the line Connection conn= DriverManager.getConnection( database)
Here is the stacktrace:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(JdbcOdbcDriver.java:436)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:153)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at test.main(test.java:20)
To write this test I used this as my primary source: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2691&lngWId=2
String strconnect="jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ="
Sring filename="some path";
StringBuilder a =new StringBuilder();
a.append(strconnect);
a.append(filename);
String db = a.toString();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c= DriverManager.getrConnection(db,"","")
Statement stmt = c.createStament();
String query = "some query";
stmt.executeQuery(query);
c.close();
Never get canonical Path, Either Specify the path of the access file or use JFile Explore and get path
also don't forget to close connection
Since you mention apache, I will presume that the server is running Linux or BSD.
In that case, please have a look at the following:
Connecting to access database from linux
Good Linux ODBC drivers for Access are expensive! (US$850 for a single machine!)
There is no default drivers for Access provided on linux, and the JDBC ODBC won't work unless you install one.
Unless there is a very special and overwhelming good reason for using an Access database as the backend to a website on a linux server, tell your friend that this is not technically or even economically coherent.
If you need a lightweight database on the server, use SQLite: it's free, there is good support for connecting to it from Java in linux, there is good tooling (even browser plugins), and you can always convert that database to Access if your friend want to get an Access backup once in a while.
Otherwise, go for PostgreSQL or MySQL like everyone does (generally for a good reason).