General JDBC Setup - java

So I have a MySQL database set up on a Debian server and it works fine from a phpMyAdmin client. I'm currently working on a project to write a Java server that would be able to use the MySQL database that is already on this server through a JDBC connection. I've looked at many tutorials and documentations but all of them seem to just explain how to do client-side code, but I have yet to figure out how to even successfully open a JDBC connection to the server. As far as I am concerned, I believe that program has the drivers properly set up because it's not crashing anymore (I simply direct the Java Build Path of my program to the Connector/J provided by MySQL). As far as my program goes, this is what it looks like...
import java.sql.*;
public class JDBCTest {
public static void main(String[] args) {
System.out.println("Started!");
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
System.out.println("Driver registered. Connecting...");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/", "root", "password");
System.out.println("Connected!");
conn.close();
} catch (SQLException e) {
System.out.println("Error!");
e.printStackTrace();
}
}
}
This is what's printed...
Started!
Driver registered. Connecting...
It's as if the DriverManager.getConnection(String) just freezes there. I'm sure this is a problem with the server because when I intentionally misspell localhost, or an IP address, the program crashes within 20 seconds. This just hangs there forever.
Sorry about this wall of text, but my final question is if anyone has any information what I should do or install on the server to get this to work? Thank you so much!

Try following:
public class MySqlDemo {
public static void main(String [] args) {
java.sql.Connection conn = null;
System.out.println("SQL Test");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test?user=root&password=");
}
catch (Exception e) {
System.out.println(e);
System.exit(0);
}
System.out.println("Connection established");
}

You have to provide the name of the Schema to which you are connecting. Usually, the port is also added.
This is a sample connection string:
jdbc:mysql://repos.insttech.washington.edu:3306/johndoe?user=johndoe&password=jddb
3306 is the port and the first instance of johndoe is the name of the Schema. The second instance of johndoe is the username.

It could be that the Connector/J library is trying to use a named pipe to connect to the MySQL server rather than using TCP/IP and for some reason the named pipe isn't available. Try specifying a port number.
You may also want to try turning on some logging in Connector/J's configuration as described here.

Try putting port number and schema there
Try logging into database using some SQL client, may be SQL console
Try other drivers, may be some newer or perhaps older

Related

Ucanaccess Connection not being created

I have a very interesting issue and I'm not having any luck finding the source of the issue.
My company recently updated to a newer version of Java and the old ODBC connection method for connecting to an MS Access DB is no longer working. So I'm in the process of updating to a new method.
I found Ucanaccess which seems to be a good alternative as the connection is read only.
So following the getting started I updated the details in the code for Ucanaccess.
This is where i ran into a interesting problem.
I've added the following to my project
ucanaccess-3.0.4.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.1.3.jar
and update the connection creation code to the following
System.out.println("Establisting Connection.....");
Connection con = DriverManager.getConnection("jdbc:ucanaccess://Z:\\Database\\test.accdb");
System.out.println("Connection Establisted.....");
The first database I used was password protected so I thought that might be causing the issue so I switched to a new database. The second database was on a shared drive so i mapped the location to the above. Even with those two changes I'm still getting the same issue.
The problem is that each time i run the DriverManager.getConnection line the code it never reaches the System.out.println("Connection Establisted....."); line. There is no error messages and the program is still running so no crash. The strange thing is that if i put an invalid path in i do get to that line. Though i do get an error saying the file doesn't exist.
I've had no luck tracking down a solution to this issue.
I think could be problems with the URL connection. It works for me:
public class ConnectionUcanaccess {
static
{
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
System.out.println("driver loaded");
} catch (ClassNotFoundException e) {
System.out.println("the class driver can't be loaded");
}
}
static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:ucanaccess:///Users/shared/Desktop/database.accdb");
}
public static void main(String[] args){
try {
Connection con = ConnectionUcanaccess.getConnection();
System.out.println("Connected: " + !con.isClosed());
} catch (SQLException e) {
System.out.println("Error:" + e.getMessage());
}
}
}

Centos7 + Oracle12c driver fails to get connection

There seems to be an issue with Centos7 and the ojdbc6 driver that is used for Oracle connections. The connection hangs and or fails resulting in a timeout. The following is the simplest program I could derive to show this issue:
import java.sql.*;
public class Test{
public static void main(String[] args){
try{
Class.forName("oracle.jdbc.OracleDriver"):
}catch(ClassNotFoundException e){System.out.println(e);}
Connection conn = null;
try{
conn = DriverManager.getConnection(...);
}catch(SQLException e){System.out.println(e);}
}
}
The odd thing is this code executes perfectly fine on Centos6.
I don't think the JDBC drivers are operating system-dependent. However, for the issue you are facing, you can try setting the JVM property like this:
-Djava.security.egd=file:///dev/urandom
Please refer to this issue Oracle JDBC intermittent Connection Issue.
The issue on connection timeout and its relation with server randomness is mentioned in details there.

Connection to derby database refused

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?

Java connection to sql server

Ok so I have this code:
package com.andrewxd.banksystem;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Interface
{
public static void main(String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1443;user=Andrew;password=andrei23;database=BankSystem");
System.out.println("test");
Statement sta = conn.createStatement();
String Sql = "select * from Clients";
ResultSet rs = sta.executeQuery(Sql);
System.out.println(rs.next());
} catch (Exception e){
e.printStackTrace();
}
}
}
but it gives me this error can somebody help me?:
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1443 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
I've tried searching but I didn't really understand much.
from what i understand the port is incorrect but how do i find the correct ip/port?
1) Open SQL Server configuration manager and check to see if the TCP/IP under Network configuration protocols is enabled.
2) Under properties of the SQL serve under Connections check to see if Allow remote connections to this server is allowed.
3) Check to see if you can connect via SSMS and query the database.
4) In SQL Server Configuration manager check to see if the SQL Server Browser service is running. (this is not enabled by default nor is it set up to start up automatically by default).
5) If all those are set up then I would check the firewall.
(For anyone that might come across this the solution was to allow SQL Server and windows authentication)
Make sure your sql server configuration
-has TCP configured, and configured at that IP address.
You can test a couple things:
turn off Windows Firewall, from services.msc.
try connecting to SQL Server through the IP address,username,pwd the
application is trying to use. (open enterprise manager, connect, enter IP address etc)
Try using jtds driver for SQLServer.
Installing Oracle JDBC driver from Here
And with your code looking like this:
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class OracleJDBC {
public static void main(String[] argv) {
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:BankSystem", "Andrew","andrei23");
}
catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
It should probably work, if not, what does the output look like now ? Still equal to what it was before ? Did you check firewalls ? Connectivity to server allowed ?
The standard port for sqlserver is 1433 and not 1443 as far as I recall it right.

connecting to remote MySQL server using JDBC issue

I am working on a dynamic webapp on eclipse and is trying to access a remote MySQL database. I made sure that all the information is correct. However I can't seem to connect to it. Here's my getConnection method:
public static Connection getConnection() throws SQLException {
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://50.56.81.42:3306/GUEST_BOOK";
String user = "username";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
System.out.println("CONNECTED");
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(InstantiationException e){
e.printStackTrace();
}catch(IllegalAccessException e){
e.printStackTrace();
}
return conn;
}
I am trying to see what the error is but because this is a web app, I can't see that system.out.println anywhere, so it's kind of hard for me to debug with this. Any suggestions on how to debug?
Is your MySQL server accessible from out of the server? I am asking because it is possible to disable external connection for MySQL server, more info is here.
Your credentials are OK (at least its format).
Otherwise, you create Class.forName("com.mysql.jdbc.Driver").newInstance(); but you don't assign it to conn variable.
In web applications, System.out prints to the server's logs file. If you are using tomcat, see logs directory inside tomcat's base directory.
If you are still struggling to see the System out in logs, try to test the class from standalone java class, you will clearly see what the problem is.

Categories

Resources