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?
Related
Hello,
I'm doing a project with the database, where the database is located on Google Cloud. The problem is with multiple connections, where the project should be able to access the database from multiple sources and the cloud enables this originally by manually whitelisting all the IPs, what is unacceptable for my scenario.
I've tried to use SSL, but unfortunately, I'm not able to connect no matter what I do. When I go without SSL, and I whitelist my IP, the connection is successful.
I'm kinda new to databases and on possible ways how to connect to them. Therefore, I need some basic explanation on what should I do or what am I doing wrong, since I'm getting kinda lost.
Things I did following the tutorials from Postgre, Google, websites and already opened threads:
1) Received 3 files from Cloud - server-ca.pem, client-key.pem, client-cert.pem, where I imported server-ca.pem and client-cert.pem into the Java Keystore
2) Tried both ways of naming the properties to connect to the database ( naming them all in URL and setting them as property) where the items are listed from PSQL generated by google cloud
PSQL :
psql "sslmode=verify-ca sslrootcert=server-ca.pem \
sslcert=client-cert.pem sslkey=client-key.pem \
hostaddr=MYIP \
port=5432 \
user=postgres dbname=postgres"
The code:
(.pam files are included in the project directory)
public static Connection connectDb(){
Connection conn = null;
String url = "jdbc:postgresql://MYIP:5432/";
Properties props = new Properties();
props.setProperty("user","postgres");
props.setProperty("password","admin");
props.setProperty("ssl","true");
props.setProperty("sslmode","verify-ca");
props.setProperty("sslrootcert","server-ca.pem");
props.setProperty("sslcert","client-cert.pem");
props.setProperty("sslkey","client-key.pem");
String name = "postgres";
String password = "postgres";
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException classNotFoundException) {
classNotFoundException.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, props);
} catch (SQLException sqlException){
sqlException.printStackTrace();
}
return conn;
}
Error log:
org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:292)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:195)
at org.postgresql.Driver.makeConnection(Driver.java:454)
at org.postgresql.Driver.connect(Driver.java:256)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:678)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:190)
Any tips, help, tutorials, explanation on what should I do, what I did wrong, what kind of approach to choose will help a lot since I've tried all the things and possible ways to solve this problem I've found.
PS: Please, try to use basic and explanatory words and names for stuff, since I worry I might get lost and confused pretty easily. :)
Thanks, Lukas.
Dear StackOverFlowers,
I was trying event-driven LISTENER/NOTIFY on Postgres 9.6 (Windows 10).
I followed PGJDBC example given by Steve Taylor at https://www.openmakesoftware.com/postgresql-listen-notify-events-example/.
I started by downloading pgjdbc-ng-0.7-complete.jar and have put that in my CLASSPATH replacing standard JDBC driver.
When I am trying to connect to Postgres database using pgjdbc driver, I am getting an error:
connection received: host=127.0.0.1 port=50325
connection authorized: user=postgres database=scott
could not receive data from client: An existing connection was forcibly closed by the remote host.
Here are my system variables:
DBHost: localhost
DBName: scott
DBPort: 5432
DBUserName: postgres
DBPassword: postgres
I am not getting past the first hurdle, rest looks like Mount Everest. Please help me. Should you be needing the code, I am following Steve's code ditto.
Further to Joseph Larson's answer, the database is always running. I have connected to Postgres database from PGADMIN and Java successfully. I think issue is with the connect string. From Java when I am using standard JDBC which is provided by Postgres I am using URL like jdbc:postgresql://localhost:5432/dbname but PGJDBC suggests a different connect string like JDBC:PGSQL://localhost:5432/dbname. I tried to connect with that string (forcibly), it did not work. There is no method in PGJDBC PGDataSource for providing URL directly. I had to go through:
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabase(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
And what URL it is sending to Database I am not able to figure out. Please suggest me a connect string and this problem is solved.
thanks
Thanks very much for asking me to post error messages:
Exception in thread "main" java.lang.NullPointerException
at com.impossibl.postgres.system.BasicContext.loadLocale(BasicContext.java:294)
at com.impossibl.postgres.system.BasicContext.init(BasicContext.java:273)
at com.impossibl.postgres.jdbc.PGConnectionImpl.init(PGConnectionImpl.java:251)
at com.impossibl.postgres.jdbc.ConnectionUtil.createConnection(ConnectionUtil.java:182)
at com.impossibl.postgres.jdbc.AbstractDataSource.createConnection(AbstractDataSource.java:723)
at com.impossibl.postgres.jdbc.PGDataSource.getConnection(PGDataSource.java:66)
at com.impossibl.postgres.jdbc.PGDataSource.getConnection(PGDataSource.java:58)
at PGListenNotify.<init>(PGListenNotify.java:26)
at PGListenNotify.main(PGListenNotify.java:37)
Here is source code:
import java.sql.SQLException;
import java.sql.Statement;
import com.impossibl.postgres.api.jdbc.PGConnection;
import com.impossibl.postgres.jdbc.PGDataSource;
public class PGListenNotify
{
PGConnection connection;
public PGListenNotify()
{
String DBHost = System.getenv("DBHost");
String DBName = System.getenv("DBName");
String DBUserName = System.getenv("DBUserName");
String DBPassword = System.getenv("DBPassword");
try
{
PGDataSource dataSource = new PGDataSource();
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabase(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
connection = (PGConnection) dataSource.getConnection();
Statement statement = connection.createStatement();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
PGListenNotify ln = new PGListenNotify();
}
}
This looks like the Windows locale bug in pgjbdc-ng. It has been addressed, try the latest version 0.8.1.
The latest releases have detailed documentation related to asynchronous notifications here.
If it still fails to execute on your Windows system, please create an issue here.
Did you actually start a database server? I didn't know PostgreSQL server could run on Windows, but I've never tried.
I would simplify your problem a little. I know nothing about psql on Windows, but on Mac, I would start the server and then use the psql command (it's part of PostgreSQL) to ensure the server was up and running.
If you're to connecting, then the problems can be:
-There is no server at all
-The server isn't running on the port you're attempting
-The server isn't listening for connections on host 127.0.0.1 but could be listening on the actual IP address of your machine
-I'm not sure about that particular error, but username, password, or database may not exist.
I'd use psql to figure out which of those possible reasons is the real problem. That isolates out your program as being part of the problem, and it becomes entirely one of managing your database server.
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
Here's how I'm trying to connect:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception e) {
throw new DbConnectionException();
}
try {
connection = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
throw new DbConnectionException();
}
I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:
com.mysql.jdbc.CommunicationsException:
Communications link failure due to
underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException MESSAGE:
java.net.ConnectException: Connection
refused
...
Possibly a url issue. If your code is pointing to MySQL localhost, try changing localhost to 127.0.0.1 on your url.
E.g.:
jdbc:mysql://localhost:3306/MY_DB
to
jdbc:mysql://127.0.0.1:3306/MY_DB
And see if this works.
did you run the mysql browser from the same machine where the code is running? What I am getting at is the permissions in mysql can be host-specific, and depending on how you set them up you might not be able to connect from the machine where the code is running.
Also, you might want to double check the url, name, pword again, perhaps with log statements or a debugger to make sure there are no typos, trailing whitespaces, etc...
Double check the format of your url. It should start with "jdbc:mysql:". Make sure you are using a current version for the driver as well.
Check that you can connect to the database from the mysql admin tool, that will drive out whether your mysql is running and that the port is open.
In my case the problem was that I was using a connection from emulator to localhost.
If you use emulator to localhost don't use localhost value in connection String but use 10.0.2.2 instead:
jdbc:mysql://10.0.2.2:3306/MY_DB
Hope this helps.