I try to connect to my BD
This is my code
public class JavaSQLTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://FRANK-PC\\SQLEXPRESS" +
"databaseName=Pendu;";
Connection con = DriverManager.getConnection(connectionUrl);
} catch (SQLException e) {
System.out.println("SQL Exception: "+ e.toString());
} catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
}
I get Class Not Found Exception: java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver after running....
How to connect properly on a sql server ???
Thanks Frank
You have to put the SQL Server JDBC driver library into the classpath .
Related
I need to connect hive(kerberos + SSL) using jdbc, i tried this code but getting error like :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/hadoop/util/VersionInfo
at org.apache.hadoop.hive.shims.ShimLoader.getMajorVersion(ShimLoader.java:155)
at org.apache.hadoop.hive.shims.ShimLoader.loadShims(ShimLoader.java:134)
at org.apache.hadoop.hive.shims.ShimLoader.getHadoopThriftAuthBridge(ShimLoader.java:120)
at org.apache.hive.service.auth.HttpAuthUtils.getKerberosServiceTicket(HttpAuthUtils.java:52)
at org.apache.hive.jdbc.HttpKerberosRequestInterceptor.process(HttpKerberosRequestInterceptor.java:63)
at org.apache.http.protocol.ImmutableHttpProcessor.process(ImmutableHttpProcessor.java:109)
at org.apache.http.protocol.HttpRequestExecutor.preProcess(HttpRequestExecutor.java:176)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:518)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:827)
at org.apache.thrift.transport.THttpClient.flushUsingHttpClient(THttpClient.java:235)
at org.apache.thrift.transport.THttpClient.flush(THttpClient.java:297)
at org.apache.thrift.TServiceClient.sendBase(TServiceClient.java:65)
at org.apache.hive.service.cli.thrift.TCLIService$Client.send_OpenSession(TCLIService.java:141)
at org.apache.hive.service.cli.thrift.TCLIService$Client.OpenSession(TCLIService.java:133)
at org.apache.hive.jdbc.HiveConnection.createHttpTransport(HiveConnection.java:267)
at org.apache.hive.jdbc.HiveConnection.openTransport(HiveConnection.java:201)
at org.apache.hive.jdbc.HiveConnection.(HiveConnection.java:168)
at org.apache.hive.jdbc.HiveDriver.connect(HiveDriver.java:105)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at prodhive.main(prod_test.java:25)
Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.util.VersionInfo
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
System.out.println("Driver Registered");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("Exception Occured");
System.exit(1);
}
System.out.println("before connection");
Connection con = DriverManager.getConnection(
("jdbc:hive2://abc.xyz.com:10000/default;principal=hive/_HOST#XYZ.COM;KrbRealm=PQR.COM;KrbHostFQDN=abc.xyz.com;KrbServiceName=hive;KrbAuthType=0;SSLKeyStore=/home/arcosadmin/va.xyz.com.jks;SSLKeyStorePwd=1234;transportMode=http;httpPath=cliservice;SSL=1;AuthMech=3;UID=HS2;PWD=1234")
System.out.println("Connection Established Successfully");
Statement stmt = con.createStatement();
System.out.println("Table Creation Started");
String tableName = "hive_con";
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS " + tableName + "(eid int, name String,destination String)");
System.out.println("Table have been created");
con.close();
System.out.println("Connection Closed");
}
I wanted to connect DB to Java application in Intellij.
I set the classpath correctly, so that javac from cmd is working correct.
I have also downloaded all the jar files needed as a libary, but I still get java.sql.SQLException: No suitable driver found for jdbc:derby
What can be the problem?
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
final String DATABASE_URL = "jdbc:derby:myDB;create=true;user=user;password=pass";
try (
Connection connection = DriverManager.getConnection(DATABASE_URL, "user", "pass");
)
{
// ...
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
}
You can try if org.apache.derby.jdbc.EmbeddedDriver works. And it seems your connection url is wrong.
final String DATABASE_URL = "jdbc:derby://localhost:1527/myDB;create=true;user=user;password=pass";
Connection connection = null;
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager.getConnection(DATABASE_URL );
}
catch (Exception e)
{
e.printStackTrace();
}
I have a problem with JDBC drivers. I can't connect with my SQL Server database. Following code for test:
public class Test {
public static void main(String[] args) {
Connection con = null;
String conUrl = "jdbc:sqlserver://localhost:1433; databaseName=mydb; user=root; password=psswd;";
try {
con = DriverManager.getConnection(conUrl);
System.out.println("OK");
} catch (Exception e) { e.printStackTrace(); }
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
}}
When i try run this code i still getting error:
java.sql.sqlexception no suitable driver found for (..)
I have added path to sqljdbc4.jar to classpath variable and enu\auth\x64 localization to Path variable. I'm working on JRE 1.8, SQL Server 2014 and Windows 7.
It's because you haven't loaded the driver. Just modify your existing code
try {
//this will load the driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(conUrl);
System.out.println("OK");
} catch (Exception e) { e.printStackTrace(); }
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
So i am facing the following problem.
I have developed an web app that has the following connection to a SQL Server database. (db connection code attached)
public class DBConnection
{
private DatabaseMetaData dma;
private static Connection con;
private static DBConnection instance = null;
private static String security = "integratedSecurity=true;";
private DBConnection()
{
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (Exception e) {
System.out.println("Can not find the driver");
System.out.println(e.getMessage());
}
try{
con = DriverManager.getConnection("jdbc:jtds:sqlserver://<Machine>;databaseName=<DBName>; useNTLMv2=true;");
//set autocommit
con.setAutoCommit(true);
dma = con.getMetaData(); // get meta data
System.out.println("Connection to " + dma.getURL());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Database product name " + dma.getDatabaseProductName());
}
catch(Exception e){
System.out.println("Problems with the connection to the database");
System.out.println(e.getMessage());
System.out.println(con);
}
}
public static void closeConnection()
{
try{
con.close();
System.out.println("The connection is closed");
}
catch (Exception e){
System.out.println("Error trying to close the database " + e.getMessage());
}
}
public Connection getDBcon()
{
return con;
}
public static DBConnection getInstance()
{
if (instance == null)
{
instance = new DBConnection();
}
return instance;
}
public static void startTransaction()
{ try{
con.setAutoCommit(false);
}
catch(Exception e){
System.out.println("fail start transaction");
System.out.println(e.getMessage());
}
}
public static void commitTransaction()
{ try{
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail commit transaction");
System.out.println(e.getMessage());
}
}
public static void rollbackTransaction()
{
try
{
con.rollback();
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail rollback transaction");
System.out.println(e.getMessage());
}
}
I am using a Tomcat 8 on InteliJ IDE for running the app and debugging. Which works fine. (DB connection is established)
The problem is that when i take the war file and deploy it in the same Tomcat Server i get no DB Connection. (No DB connection)
I have checked all the .jar files in the tomcat and the project and I have added all the needed files.
Can't seem to find what is causing this issue. Maybe there is someone who got stuck with the same issue
I can't get a proper undertanding what is causing this issue and how to fix it
**EDIT: Following I have added the error displayed when trying to load data
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is java.lang.NullPointerException
root cause
java.lang.NullPointerException
com.lifeletapp.business.dataLayer.DbLogIn.isValidUser(DbLogIn.java:27)
com.lifeletapp.business.HelloController.verifyLogin(HelloController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
DbLogin class:
public class DbLogIn implements ILogIn
{
private Connection conn;
public DbLogIn()
{
conn = DBConnection.getInstance().getDBcon();
}
public Staff isValidUser(String userName, String password)
{
Staff staff = new Staff();
try {
String query = "SELECT * FROM Staff WHERE userName=? AND pass=?";
PreparedStatement preparedStatement = conn.prepareStatement( query );
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
while( resultSet.next() ) {
staff.setUserID(resultSet.getInt("userID"));
staff.setfName(resultSet.getString("fName") );
staff.setlName(resultSet.getString("lName") );
staff.setUserName(resultSet.getString("userName") );
staff.setPass(resultSet.getString("pass") );
staff.setEmail(resultSet.getString("email") );
}
resultSet.close();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return staff;
}
}
This is more a config or server issue. Not a code issue.
As mentioned in the comments I have tested if var conn == null -> resulted true. And the connection dose not get nulled anywhere. Please view code. Then again the above code works when run from the InteliJ debugger.
So finally figured out what was the issue.
Why was it working on my IDE config:
1. I was using java JDK 1.7 as JAVA_HOME
2. I was using an older version of Tomcat as a build
3. In order to work with JDTS you need to extract the nlmauth.dll from the .jar archive and copy it to the configured env JDK(jdk1.7-->>bin->>copy here)
Why was it not working on Tomcat server:
1.I was using Tomcat 8.xxx
2.Tomcat 8.xx require JDk 8
3. In the JDK 8 i have not past the nlmauth.dll ( once i have done this everything was working)
In order to approach this issue the first clue will be looking into the tomcat server logs.
On my presumption this issue is prom to occur only when you have an Database connection establish via Integrated Security.
My presumption is related to the fact that in the tomcat log the main error that was denying the JDBC driver was based on the integrated security credentials.
Best of luck to you all out there.
I'm learning how to connect to mysql from java from a book, but I get one error, the first line..the package declaration. I copied the code(given bellow) exactly as it was in the book and I have downloaded everything correctly, please help! Thanks!
package mysql;
import java.sql.*;
public class test {
Connection connection;
private void displaySQLErrors(SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
public test() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (SQLException e) {
System.err.println("Unable to find and load driver");
System.exit(1);
}
}
public void connectToDB() {
try {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost/accounts?user=&password=");
}
catch(SQLException e){
displaySQLErrors(e);
}
}
public void executeSQL() {
try{
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(
"SELECT * FROM acc_acc");
while (rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();
statement.close();
connection.close();
}
catch(SQLException e) {
displaySQLErrors(e);
}
}
public static void main(String[] args){
test test1 = new test();
test1.connectToDB();
test1.executeSQL();
}
}
If you have an error on your package declaration, it's probably because you don't have it in the right package!
If you have package mysql; as you state in your code, then you need it to be in the mysql folder in your source tree.
Add Mysql jar then this code will be connect.
You should write
Class.forName("com.mysql.jdbc.Driver");
to load the drivers and
connection = DriverManager.getConnection("jdbc:mysql://localhost/accounts","yourUsername","yourPassword");