Connect to SQL server from Java - java

I'm trying to connect from SSMS(SQL Server Management Studio) to Eclipse(Java), but I keep getting this error message:
com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host localhost, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.getInstancePort(SQLServerConnection.java:6132)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.primaryPermissionCheck(SQLServerConnection.java:2609)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2346)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2213)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1276)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:861)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.sql.JavaConnect2SQL.main(JavaConnect2SQL.java:16)
The code I do have is:
import java.sql.DriverManager;
import java.sql.SQLException;
//import com.sun.jdi.connect.spi.Connection;
public class JavaConnect2SQL {
public static void main(String[] args) {
// TODO Auto-generated method stub
String url = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=students"; // This is where I think the error is
String user = "sa";
String password = "123";
try {
java.sql.Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Succesfully connected to Microsoft SQL Server");
}catch (SQLException e) {
System.out.println("Oops! There was an error: ");
e.printStackTrace();
}
}
}
I think the problem is in the connection URL, but I don't know the host name/instance name. If you can tell me how to get my host name/instance name, that would be appreciated. But if the problem is something else, please tell me!
Edit: I have changed the code, and I'm now getting a different. Here is the new code:
package net.codejava.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JavaConnect2SQL {
public static void main(String[] args) {
// Create a variable for the connection string.
String url = " jdbc:sqlserver://LAPTOP-5697KK36:1433;databaseName=students";
String user= "sa";
String password = "123";
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connection succesful!");
}
// Handle any errors that may have occurred.
catch (SQLException e) {
System.out.println("Here is your error message: ");
e.printStackTrace();
}
}
}
The new error message is this:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://LAPTOP-5697KK36:1433;databaseName=students
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.sql.JavaConnect2SQL.main(JavaConnect2SQL.java:40)
I think the problem is that I installed the wrong version of JDBC Driver. My JRE version is 12.0.1. What is the correct JDBC Driver to install.

You can check in SQL server configuration manager and Microsoft SQL server management studio. The state must be running in server configuration manager and you can try to connect your database in Microsoft SQL server management with your password.
if you connect successfully then there is another problem but it looks like the database is stopped.

Related

How to connect to Apache Hive Using SSL certificate from Java JDBC?

I am currently trying to make a simple connection between a Java class and an Apache Hive server.
However, I have not been able to do it due to a javax.net.ssl.SSLPeerUnverifiedException error.
This is the Java code that I am executing:
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
Connection con = null;
try {
String conStr = "jdbc:hive2://{{domain}}:{{port}}/default;ssl=true;sslTrustStore=C:/DBVisualization/gateway.jks;trustStorePassword=Password1;transportMode=http;httpPath=/gateway/default/hive";
Class.forName("org.apache.hive.jdbc.HiveDriver");
con = DriverManager.getConnection(conStr, "user", "password");
if(con != null)
System.out.println("Connected");
} catch (Exception ex) {
Logger.getAnonymousLogger().severe("There was an error while connecting to Hive");
}
}
}
And this is the error I am getting:
Could not open client transport with JDBC Uri: jdbc:hive2:{{url}}:{{port}}/default;ssl=true;sslTrustStore=C:/DBVisualization/cacerts;trustStorePassword=changeit;transportMode=http;httpPath=/gateway/default/hive: Could not establish connection to jdbc:hive2://{{url}}:{{port}}/default;ssl=true;sslTrustStore=C:/DBVisualization/cacerts;trustStorePassword=changeit;transportMode=http;httpPath=/gateway/default/hive: javax.net.ssl.SSLPeerUnverifiedException: Certificate for <IP> doesn't match any of the subject alternative names: []
As you can see I am pointing to the file where the certificate is, I used that same certificate for set up a DB visualizer connection and it worked. I am just do not know if for Java a different certificate is required. What am I doing wrong?

Android Crash When Connecting to SQL Server

I am having an issue with an app I am testing. I am using Android Studio and JTDS 1.3.1. I am just trying to test connecting to the database. The end product will be a label application only used within our company on our network. I have tried Microsoft's JDBC driver as well, with no success. The app crashes when it tries to create a connection. I have added JTDS as a module and a dependency. The app is just a button that calls a static method and a text view to display an error or success if it works. If I don't load the database driver I do get a SqlException error for no suitable driver found. When I do load the driver the app closes with no error reported.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBHelper {
public static String checkConnection() {
String message;
String username = "username";
String password = "password";
String connectionURL = "jdbc:jtds:sqlserver://server-name/database-name";
try (Connection connection = DriverManager.getConnection(connectionURL, username, password)) {
message = "Success";
return message;
} catch (SQLException sqle) {
message = sqle.getMessage();
return message;
}
}
}
I know it is too late but try using jtds 1.2.7 version jar

Java connection with sql server 2008 r2 type 4

Hello iam using eclipse and sql server 2008 r2 as database i get a error like this
com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host RITHISHABINAV, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.getInstancePort(SQLServerConnection.java:3589)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.primaryPermissionCheck(SQLServerConnection.java:1225)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:972)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.serv.sqlservertype4.fun(sqlservertype4.java:17)
at com.serv.sqlservertype4.main(sqlservertype4.java:39)
And my code is this
package com.serv;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class sqlservertype4 {
void fun()
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl="jdbc:sqlserver://RITHISHABINAV\\SQLEXPRESS;database=tempdatabase;integratedSecurity=true;";
Connection conn=DriverManager.getConnection(connectionUrl);
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * from customer");
while(rs.next())
{
System.out.println(rs.getString("id"));
System.out.println(rs.getString("name"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
sqlservertype4 b= new sqlservertype4();
b.fun();
}
}
I think that you have a wrong connectionURL, you need to create a vURL` like:
jdbc:sqlserver://HOST_SERVER:SQL_SERVER_PORT;databaseName=DATABASE_NAME;
But If you are using Named Instances to connect to your database (instead of PORT numbers), then use the following URL template
jdbc:sqlserver://DATABASE_HOST\\INSTANCE_NAME;databaseName=DATABASE_NAME;

Java Connect to a MySQL's sites DB

I have a site with a MySql Database, and I would like to retrieve the information via a Java Program. The problem is that I'm not sure about how to do it. I have tried a few methods, but none works.
Long story short, I need help with the following :
finding the IP of the server
connecting to the database via IP
creating a new connection with the details
I have tried the following : DriverManager.getConnection("jdbc:mysql://DOMAIN:3306/DB_NAME", "USER", "PASSWORD"); but doesn't work.
Thanks in advanced, and I apologize if the question is stupid, but I have no Java experience with DB's, and I can't understand how can a link between those 2 entities be established.
edit
The Class is the following
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class test {
/**
* #param args
*/
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://IP:3306/DB","USER", "PASS");
Statement statement = connection.createStatement();
ResultSet resultSet = statement .executeQuery("SELECT * FROM `categorii`");
System.out.println( resultSet.getNString(3));
}
catch (Exception M)
{
System.out.println(M.getMessage());
}
}
}
An Exception is thrown which says :
'Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.'
So it can't connect to the server, but I can't see why.
I've always had problems using this:
DriverManager.getConnection("jdbc:mysql://DOMAIN:3306/DB_NAME", "USER", "PASSWORD");
Try this instead
DriverManager.getConnection("jdbc:mysql://DOMAIN:3306/DB_NAME?user=USER&password=PASSWORD");

How do I connect to a SQL Server 2008 database using JDBC?

I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database. I am a new to MSSQL and I would like get some help on creating user login for my Java application and getting connection via JDBC. So far I tried to create a user login for my app and used following connection string, but I doesn't work at all. Any help and hint will be appreciated.
jdbc:jtds:sqlserver://127.0.0.1:1433/dotcms
username="shuxer" password="itarator"
There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:
String userName = "username";
String password = "password";
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
after adding sqljdbc4.jar to the build path.
For Window authentication you can do something like:
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).
Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!
You can use this :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from sysobjects where type='u'";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
"<password>");
}
}
I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName
I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress
Do not forget check if SQL Server Browser service is running.
You can try configure SQL server:
Step 1: Open SQL server 20xx Configuration Manager
Step 2: Click Protocols for SQL.. in SQL server configuration. Then, right click TCP/IP, choose Properties
Step 3: Click tab IP Address, Edit All TCP. Port is 1433
NOTE: ALL TCP port is 1433
Finally, restart the server.
Simple Java Program which connects to the SQL Server.
NOTE: You need to add sqljdbc.jar into the build path
// localhost : local computer acts as a server
// 1433 : SQL default port number
// username : sa
// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root'
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Conn {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Connection conn=null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");
if(conn!=null)
System.out.println("Database Successfully connected");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Try this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLUtil {
public void dbConnect(String db_connect_string,String db_userid,
String db_password) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from cpl";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
} }
public static void main(String[] args) {
SQLUtil connServer = new SQLUtil();
connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB",
"sa",
"0123");
}
}
Try this
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
String url ="Jdbc:jtds:sqlsever://ip/instanceName;instance=instanceName;databseName=dbName;user=yourUser;password=yourpass;";

Categories

Resources