Currently have a simple Java Program that creates an H2 Database like so:
public static void main(String[] args) {
try {
Connection conn = null;
Statement stm = null;
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:D:/H2db/test", "sa", "sa");
stm = conn.createStatement();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
I see the files created within the directory. Yet, when attempting to access this same Database from the H2 Console (localhost:8082) and input both
jdbc:h2:D:/H2db/test and jdbc:h2:D:\H2db\test, I get an error saying:
Database `D:/H2db/test` not found, either pre-create it or
allow remote database creation (not recommended in secure environments)
Anyone know why I cant access the Database through the console?
That piece of code is just for connection to a previously created database. To successfully connect to it you should create it first.
$ java -cp bin/h2-1.4.199.jar org.h2.tools.Shell
Welcome to H2 Shell 1.4.199 (2019-03-13)
Exit with Ctrl+C
[Enter] jdbc:h2:mem:test
URL jdbc:h2:D:/h2db/test
[Enter] org.h2.Driver
Driver
[Enter] sa
User
Password
Then and only then you'll be able to connect to it through your java application.
Related
I am trying to connect to one of my MySql Databases through a System DSN I set up. The DSN is set up correctly with my SSL certs, username, password, port, and the databases populate the DSN database drop down and the "Test" connection passes. I can't seem to get a connection in Java. I have spent 2 days looking through some examples on Stack but they all refer to an Access database and using JDBC-ODBC bridge which is no longer available in Java 8. I tried using UCanAccess with Jackcess but I have gotten no where. The code below is what I have been tinkering with the last few hours. I normally connect to MySql databases with PHP and receive result in JSON or directly with JDBC driver but for this project neither are really an option. Any ideas. I appreciate the help.
//String username = "<username>";
//String password = "<password>";
//String database = "<database_name>";
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
//Connect to cllients MySql Database
Connection conn = DriverManager.getConnection("jdbc:ucanaccess:" + database);
//Call VerifyLabel(<MAC>,<MODEL>); Call provided client
CallableStatement cStmt = conn.prepareCall("{CALL verify(?, ?)}");
//MAC
cStmt.setString(1, "mac address");
//model
cStmt.setString(2, "model");
cStmt.execute();
//Getting results from "Status" column
ResultSet rs1 = cStmt.getResultSet();
//Iterate results and print.
while (rs1.next()) {
System.out.println(rs1.getString("Status"));
}
//Close connection conn
rs1.close();
} catch (SQLException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(CambiumStoredTest.class.getName()).log(Level.SEVERE, null, ex);
}
Using MySql Driver:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:"+ database);
also tried:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ database);
Error for MySql Driver:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
1) DSN is most commonly assocatiated with ODBC (and often with MS-Access). Hence all the links. ODBC is NOT required for a DSN.
2) Do NOT use Ucanaccess. Use J/Connector for mySQL.
3) Make sure you can communicate with mySQL from the command line. Then focus on getting a small "hello world" JDBC app to connect. Your second and third examples look OK. Be sure to check the mySQL logs for any warnings/errors.
Well, after an entire day of trying to get this to work and sleeping on it for a couple hours I finally got it to work. UCanAccess and mysql-connector did not work. The easiest thing since no other method of connecting to this clients database was acceptable was to push this application in Java 7 rather than 8. This allowed me to Coo=nnect to my DSN with no problems. I understand that this method is not the best solution but it is what is working flawlessly and efficiently. Also, instead of using some rigged up 3rd party libs and jars, I am able to use Connector/J. Thanks everyone for trying to help me. Just incase anyone else runs into this issue, this is how I made it work.
Develope app in Java 7 - not 8.
Set Up System DSN
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//You do not need to provide username or password if it is setup in DSN
Connection conn = DriverManager.getConnection("jdbc:odbc:"+ database);
Here's my code:
import java.sql.*;
public class DBConnector {
private static Connection conn;
public static void connectToDB()
{
//load the driver
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("Driver successfully loaded");
}
catch (ClassNotFoundException c)
{
System.out.println ("Unable to load database driver");
}
//connect to the database
try
{
String filename = "TopYouTubeVideos.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database += filename.trim () + ";DriverID=22;READONLY=true}";
conn = DriverManager.getConnection (database, "", "");
System.out.println ("Connection database successfully established");
}
catch (Exception e)
{
System.out.println ("Unable to connect to the database");
}
}
The output is:
Driver successfully loaded
Unable to connect to the database
This has worked on a different computer than mine, connecting to the database through exactly the same code... does anyone have any idea why?
Thanks in advance :)
EDIT: I'm running Access 2007, Windows 7 64bit
By checking for the error, I get: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
From a little bit of research it seems this is a problem with my 'data source name'. I put my database file in the project folder, and the name is correct. Why is it not finding it?
EDIT: No, the database was the same on both computers. In the same folder as well.
EDIT: I think I may need to create a system dsm. Following the instructions on the internet dosent work though, because I dont have the same files as them..
EDIT: I've tried to install that but it hasn't made a difference. My version of access is 64 bit alongside my version of netbeans..
Try installing a database engine + JVM that are both running in the same archeticture (i.e. 32bit), otherwise, you would receive a mismatch exception. I assume your JVM is 64bit but your database engine is not, so try installing a 64bit engine from the following link:
http://www.microsoft.com/en-us/download/details.aspx?id=13255
Background: Working on an application to be run on an Apache server hosted by Network Solutions. Friend/Customer insisted on using an Access Database instead of SQL database.
Current Problem: Wrote a Java test program to make sure I can connect to the database before I dive head first into writing the whole backend. When I run this code on the JVM of the apache server the final product will be hosted:
import java.sql.*;
import java.io.*;
public class test {
public static void main(String[] args) {
try {
Class driverClass = Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
DriverManager.registerDriver((Driver) driverClass.newInstance());
// set this to a MS Access DB you have on your machine
String filename = new File(".").getCanonicalPath() + "/ITEMS.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim(); // add on to the end
// now we can get the connection from the DriverManager
System.out.println(database);
Connection conn = DriverManager.getConnection( database );
} catch (Exception e) {
System.out.println("Error: " + e.getMessage() + " " + e.getLocalizedMessage());
e.printStackTrace();
}
}
}
I get a null pointer exception on the line Connection conn= DriverManager.getConnection( database)
Here is the stacktrace:
java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.initialize(JdbcOdbcDriver.java:436)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:153)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at test.main(test.java:20)
To write this test I used this as my primary source: http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=2691&lngWId=2
String strconnect="jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ="
Sring filename="some path";
StringBuilder a =new StringBuilder();
a.append(strconnect);
a.append(filename);
String db = a.toString();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c= DriverManager.getrConnection(db,"","")
Statement stmt = c.createStament();
String query = "some query";
stmt.executeQuery(query);
c.close();
Never get canonical Path, Either Specify the path of the access file or use JFile Explore and get path
also don't forget to close connection
Since you mention apache, I will presume that the server is running Linux or BSD.
In that case, please have a look at the following:
Connecting to access database from linux
Good Linux ODBC drivers for Access are expensive! (US$850 for a single machine!)
There is no default drivers for Access provided on linux, and the JDBC ODBC won't work unless you install one.
Unless there is a very special and overwhelming good reason for using an Access database as the backend to a website on a linux server, tell your friend that this is not technically or even economically coherent.
If you need a lightweight database on the server, use SQLite: it's free, there is good support for connecting to it from Java in linux, there is good tooling (even browser plugins), and you can always convert that database to Access if your friend want to get an Access backup once in a while.
Otherwise, go for PostgreSQL or MySQL like everyone does (generally for a good reason).
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.
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