I'm currently working on a small project which involves writing information from a CSV file to a MySQL database.
I'm using netbeans and have added the MySql JDBC JAR file to the project which is needed for the connection. When running the code below the program does not move on past the driver manager.getConnection statement. I am lost for ideas at this stage. My username and password is definitely correct and I am certain I have the URL right. No errors are returned, the project seems to just get stuck.
I am using a database that is hosted by blacknight hosting services, would this make a difference?
public static void writeToDatabase()
{
try {
String url = "jdbc:mysql://172.16.2.10:57983/db1320939_sa63898_main";
Connection conn = DriverManager.getConnection(url,"u1320939_kd","svpgalway21");
conn.close();
System.out.println("It worked!");
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
Try catching Throwable instead of Exception. Maybe you're getting an Error while you connect to the DB and you wouldn't notice it. Also include a finally clause with a trace.
Related
I have an instance of MySQL deployed on an Amazon EC2 server, along with a Java .Jar file that connects to the local database to archive metadata retrieved from an API. I have the Java file automatically executed 4 times daily via a Linux Crontab Task.
My code will always run and connect to MySQL fine initially but then it will experience a JDBC Communications link failure around a minute into its execution (the timeframe that this occurs can vary, however). This is the following error message that is displayed to the terminal:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet successfully received from the server was 4,278 milliseconds ago.
Prior to the above error message being displayed, my program appears to freeze. The freezing of my program is evident because it will stop outputting: "A metadata point was archived". I have my program output that everytime a metadata point from an API is archived accordingly into my database's tables.
I've attempted many solutions in order to fix this problem and I'm at a complete loss as to what is causing it. I've added multiple parameters to my url string:
jdbc:mysql://localhost/MYDBNAME?serverTimezone=EST5EDT&useSSL=false&autoReconnect=true&maxReconnects=10&failOverReadOnly=false&allowPublicKeyRetrieval=true&useUnicode=true&tcpKeepAlive=true&interactiveClient=true
The autoReconnect parameter will sometimes allow my program to reconnect to the database after the communications link failure and to re-execute, but sometimes it won't help at all.
I've ensured that my program is not closing the JDBC connection until after the program's completion.
I've ensured that all of my preparedstatements and resultsets are being closed within a finally block after executing or retrieving the values from them.
I've ensured that the version of MySQL connector java driver.jar that my program is using matches the version of the installed MySQL database.
I've tried increasing MySQL's built-in timeout variables.
The following is the method that i use to initialize the connection global variable that is used exclusively by methods within this class for queries.
private void setUpConnectionToDatabase() {
try {
connection = DriverManager.getConnection(
url, username, password); // connects to server using url, username, password.
} catch (Exception e) {
System.out.println(e);
connection=null;
}
}
The following is one of my methods that queries the database, let me know if you see any errors. Other methods within the class essentially follow the same format. Notice that the connection variable itself does not get closed within the method.
public Coordinates getCoordsFromArchivedLocationData(String bioLocation) {
Coordinates coords= new Coordinates();
double lat=0;
double longit=0;
String queryStatement= "SELECT latitude, longitude FROM archived_location_data WHERE LocationName=?;";
PreparedStatement query=null;
ResultSet result=null;
try {
query = connection.prepareStatement(queryStatement);
query.setString(1, bioLocation);
result = query.executeQuery();
if(result.next()) {
lat= result.getDouble(1);
longit= result.getDouble(2);
}
coords.setLatitude(lat);
coords.setLongitude(longit);
}
catch(Exception e) {
System.out.println(e);
return coords;
}
finally {
try {
if(query != null) {
query.close();
}
if(result != null) {
result.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return coords;
}
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());
}
}
}
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?
I tried many ways to solve my issue, none of them worked, so here i am with the question. I created a local database with SQL Server Management Studio. It's name is CallCenter, i created a user account for it, granted every privileges and i can log into the DB with it, in the Managemenet Studio, everything works just fine here.
Now i use NetBeans, to create the connection. I downloaded the Microsoft JDBC driver, set up everything, the JDBC seems to be working fine. The problem is, it cannot connect to the Database. I set the log in options to both Windows & SQL. I tried to log in, with integrated sequrity ( windows account ) aswell as the created ( and working ) SQL user account.
None of them worked, i keep getting this exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user
'admin'. ClientConnectionId:1ce0b951-5ecb-49b4-a4d0-ff4a96af4ed2 at
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)......
Here is the code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Try {
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1434;databaseName=CallCenter;integratedSecurity=true;";
Connection conn = DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
System.err.println("SQL Driver class does not exist!");
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
I've been browsing the internet for hours, tried many solutions, but none of solved this problem for me. Please help me out here!
The Exception pretty much says it all - check your credentials (which you obviously have not given) with the database.
The Login failed for user 'admin' error which you get is a clear indication
that your login request reaches the SQL server but your credentials are wrong.
So either your username or your password is wrong, or maybe this login is not
configured for remote logins to the SQL server. Check your configuration on the server.
Use the other method of the DriverManager to get the connection using the Credentials.
When you have integratedSecurity=True, read this to get more idea on what it actually mean. It uses your windows credentials for login(With SQL Server).
So, make that false and provide credentials for the DB.
For your reference read this
[EDIT]
Try using this instead of integratedSecurity.
jdbc:sqlserver://HOSP_SQL1.company.com;user=name;password=abcdefg;database=Test
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