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");
Related
I'm trying to connect to a sql database with java but this isn't really working out. normally people say they have a user and password but I never created anything like that. I downloaded sqlite studio and you can pretty much just make a database without having to create some kind of account but when i'm trying to connect it gives me an error that it can't connect com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure.
How do I resolve this issue? This is the code I have right now:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MyJDBC {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBC-video");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from people");
while (resultSet.next()) {
System.out.println(resultSet.getString("firstname"));
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
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.
I have java based Azure Functions with, which is writing to Azure SQL.
However I get error when Function is triggered.
What I need to do with VS Code for driver issue?
I'm fine with JDBC or any other drive which is best with Azure Functions
https://learn.microsoft.com/en-us/sql/connect/jdbc/step-3-proof-of-concept-connecting-to-sql-using-java?view=sql-server-ver15
ERROR:
17.4.2020 13.06.39] java.sql.SQLException: No suitable driver found for jdbc:sqlserver://sql...;
[17.4.2020 13.06.39] Function "TopicTriggerSQLOutput" (Id: 70a1ce4c-3828-4280-81cf-dafa61956cb5)
invoked by Java Worker
[17.4.2020 13.06.39] at java.sql.DriverManager.getConnection(DriverManager.java:689)
CODE:
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;
import java.sql.Statement;
import java.sql.ResultSet;
/**
* 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:
https://learn.microsoft.com/en-us/sql/connect/jdbc/step-3-proof-of-concept-connecting-to-sql-
using-java?view=sql-server-ver15
*/
String connectionUrl = "jdbc:sqlserver://sql...";
ResultSet resultSet = null;
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 10 artist FROM [dbo].[RadioEventsTarget]";
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " " + resultSet.getString(3));
}
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
//context.getLogger().info(message);
}
}
What I need to do with VS Code for driver issue?
You need to add the jdbc driver dependency to the pom.xml file. Here is the dependency sample I used to connect to Azure SQL.
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>8.2.2.jre8</version>
</dependency>
Reference:
https://learn.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver15
Iam new to the hadoop ecosystem. Tried to access hive through jdbc. For that I have written the following code
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveConnection {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select * from test.employees");
while (res.next()) {
System.out.println(res.getString(1));
} }}
and started the hiveserver2 (hive version 0.12 & hadoop version 1.1.2) through the terminal and im getting the status as "Starting HiveServer" . When i tried executing the above code from eclipse im no getting any error and any results neither(Got the same when i executed the executable "hiveserver" ).
Can any one help me out.
Thanks in advance.
Following ways are most really reason for your problem.
1.Is the hive-jdbc-*.Jar having classpath like this "org.apache.hadoop.hive.jdbc.HiveDriver" or "org.apache.hive.jdbc.HiveDriver"?
2.While connection,you need to pass the user name and password like this?
If you use hive server2 then you have to set the connection like below.
con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", "");
Above ways are really helpful for you.
Thanks in advance.
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.