Java With Microsoft Access Database - java

I'm trying to use Ucanaccess library with java to connect to Microsoft Access ...
So i tried executing this code and it worked ....
String url = "jdbc:ucanaccess:\\C:/Access.ACCDB";
String query = "select * from [Donations]";
try
{
java.sql.Connection con =DriverManager.getConnection(url, "","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println("Account No: " + rs.getString(1));
System.out.println("Surname: " + rs.getString(2));
System.out.println("First Name: " + rs.getString(3));
}
}
catch(SQLException ex)
{
while (ex!=null)
{
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException();
}
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
let me explain what i'm trying to do
I have a Asp.Net website that uses Microsoft Access Database and in the same time i need a server (Java Application) to access the same Database (Microsoft Access) but when i uploaded the Database online to test if the server can get to the Database and modified the String for the connection ....
here is what it looked like
String url = "jdbc:ucanaccess://www.filetolink.com/download/?h=eaa4aab688d25e270539868d712961ab&t=1467140283&f=3ca9ad1869;";
String query = "select * from [Donations]";
try
{
java.sql.Connection con =DriverManager.getConnection(url, "","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println("Account No: " + rs.getString(1));
System.out.println("Surname: " + rs.getString(2));
System.out.println("First Name: " + rs.getString(3));
}
}
catch(SQLException ex)
{
while (ex!=null)
{
System.out.println ("SQL Exception: " + ex.getMessage ());
ex = ex.getNextException();
}
}
catch(java.lang.Exception ex)
{
ex.printStackTrace();
}
I tried running the code but I had an error message ... Here it is :
SQL Exception: UCAExc:::3.0.6 given file does not exist:
http:\www.filetolink.com\download\?h=e6dc57e3485defa7c53e1c968a87fb1f&t=1467139906&f=3ca9ad1869
So What i'm asking for is :
1.How can I publish the website with the access database and let both of the Server and the website access the Database ?? (The server and the website aren't on the same Machine or computer .... )
2.if the answer to my question is that i can't ... then what can i do ?? other suggestions ? for having Database that can be accessed by a Remote Server (Java Application ) and A website (Asp.Net)

MS Access is a desktop database not a server database management system. If a program wants to access to such a database, the database file has to be on a local or network filesystem. So if your two applications are running on different machines in the same intranet, putting the database file on network filesystem would be a solution.
BUT: MS Access was never meant to be used as a web application's backend database. You should use a real server database like MS SQL Server, PostgreSQL or MySQL instead. Then your applications can access the database via network protocol. Theoretically it is possible to open the database port to the internet so that you can connect from everywhere. But this is not recommended due to security reasons.
So if your two applications aren't running in the same intranet it is better to create some webservices and let your other program call these webservices to get the needed information.

Related

AWS Lambda connecting to publicly accessible AWS RDS

I created a publicly accessible PostgreSQL RDS in AWS and have the following code to connect to it:
try {
DriverManager.registerDriver(new org.postgresql.Driver());
String url = "jdbc:postgresql://" + DATABASE_SERVER_NAME + ":" + DATABASE_PORT_NUMBER + "/" + DATABASE_NAME + "?user=" + DATABASE_USER + "&password=" + DATABASE_PASSWORD;
try (Connection connection = DriverManager.getConnection(url)) {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM \"" + PHANTOM_LOAD_STORE_DATABASE_TABLE_NAME + "\"")) {
try (ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
System.out.println(resultSet.getString("userid"));
}
}
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
When this is run locally it connects to the database server successfully.
When this is run in an AWS Lambda it fails to connect with the following error:
org.postgresql.util.PSQLException: The connection attempt failed.
...
Caused by: java.net.SocketTimeoutException: connect timed out
The lambda is not in a VPC and has the role policy arn:aws:iam::aws:policy/AmazonRDSDataFullAccess.
Can someone tell me what I'm doing wrong?
Despite creating the RDS database to be publicly accessible it had a security group rule that only allowed incoming requests from my IP (the one that created the database). Editing its security group's incoming rules to allow requests from anywhere has allowed the lambda to connect to the database.
The policy arn:aws:iam::aws:policy/AmazonRDSDataFullAccess seems unnecessary.
Thanks to this answer for helping me work it out.

"Could not create connection to database server" netbeans google cloud sql error

I am trying to create my first API using java httpServlet and netbeans which will be connected to a database on google cloud based its examples and documentations. I have not created the database, but I was given the necessary credentials and vars to create the connection. So I have downloaded the project from github, and when I tried to open it from netbeans there was some issues concerning dependencies ... So I resolved them, I replaced the credentials with their values and run the project; Unfortunately an error was thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. I made some searches but did not get any result... Could it be an error from this code ? an error from database security if it was invisible on cloud? Any help is more than appreciated.
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
String instanceConnectionName = "<foo:foo:bar>";
String databaseName = "myDatabaseName ";
String username = "myUsername ";
String password = "<myPass>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
databaseName,
instanceConnectionName);
try{
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
/* try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("select * from wf_accounts;");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}*/
}catch(Exception ex){
System.out.println("Error: " + ex.toString());
}
Update
Same error was thrown when I did this:
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
"",
"");
Any hints?
First you have to check whether the mysql server is running on.If you are Windows user you can simply
Go to Task Manager
Go to Services
then search for your Mysql server(eg:for my case its MYSQL56)
then you will see under the status column it says its not running
by right clicking and select start
If it's already running then you have to do as in mysql Documentation,
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem

Unable to figure out JDBC ClassNotFoundException (JTDS driver)

So a little background on my problem: I am trying to copy over a table on an Microsoft SQL system from an Oracle database. Besides giving password and user access to the table I cannot edit or do anything to the MSSQL database.
I successfully used the Oracle SQL Developer to connect and view the tables I want (using a third party JDBC driver), but I want to set up an automated copy-over into my Oracle database so I am attempting to use the same driver in some stored java code.
I have a java function that all it should do is go and count the number of entries in the table. So far my code looks like:
public static String getCount() {
Statement stmt = null;
Connection conn = null;
int rowCount = 0;
String message = "";
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println("Error loading driver: " + e);
message = message + e + " -ER1 \n";
}
try {
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://site.school.edu:2000/ACCESS", "user", "password");
stmt = conn.createStatement();
String strSelect = "select 1 as field;";
ResultSet rset = stmt.executeQuery(strSelect);
while (rset.next()) {
++rowCount;
}
}
catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + " -ER2";
}
finally {
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch(SQLException ex) {
ex.printStackTrace();
message = message + ex.getSQLState() + "-ER3";
}
}
return message;
}
Which is being calling from a stored function :
CREATE OR REPLACE function Schema.java_testMessage return varchar2
as language java
name 'ConnectAndQuery.getCount() return java.lang.String';
Which I am calling from a script in TOAD:
set serveroutput on;
declare
words varchar2(400);
begin
words := KSL_ADMIN.java_testMessage;
dbms_output.put_line(words);
end;
However the result is that I'm getting:
java.lang.ClassNotFoundException: net/sourceforge/jtds/jdbc/Driver -ER1
08001 -ER2
PL/SQL procedure successfully completed.
I have the jar file within the class path, I can't think of any reason it shouldn't have the nessecary permissions to see the jar, and as far as I can tell I have everything spelled correctly.
Please help me figure out what I am doing wrong. Or if there is perhaps an easier way to go about connecting an Oracle DB to an MSSQL DB without really installing anything. Any knowledge on this is welcome as I am pretty new to a lot of this.
Oracle has its own internal java virtual machine and it does not use the system classpath. If you need external libraries you must “load” them into the internal JVM. You can do this using Oracle's loadjava tool.
See the Oracle's loadjava documentation (http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheleven.htm#JJDEV10060)

Why am I receiving this SQLException error stating that no suitable driver can be found?

I'm on a mac, running a MAMP instance of MySQL. I'm trying to use a jdbc driver to connect my java code to a database called 'test', working with a table called 'customer.' I keep getting an error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8889/test
I'm not sure if the problem is with my code, or if it's a configuration problem with the MAMP instance of MySQL, or if it's something else entirely.
I have an initialize driver method:
public void initializeDriver(){
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println(e.toString());
}
}
And I have a connection created in the following way:
public void insertCustomer(String connectionUrl, String connectionUser, String connectionPassword, Customer customer) {
try{
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
Statement constat = conn.createStatement();
String query = "INSERT INTO customers (customer_id, email, deliverable, create_date) VALUES (" + customer.id + ", " + customer.emailAddress + ", " + customer.deliverable + ", " + customer.createDate + ")" ;
constat.executeQuery(query);
conn.close();
}
catch(SQLException e){
System.out.println(e.toString());
}
}
And I have downloaded mysql-connector-java-5.1.20 and set it in my classpath.
If anyone has any suggestions for how I could correct this error, I would be really grateful!
You have to put MySQL jdbc connector jar library into the classpath.
Then initialize the driver before opening the connection with code like the following :
Class.forName("com.mysql.jdbc.Driver").newInstance();
You will need the corresponding mysql JDBC driver jar in your classpath or loadable by your container. See the doc for ConnectorJ and note the installation instructions.
Try to add mysql-connector-java-5.1.20.jar to Glassfish (or Tomcat) lib folder.
you have also a error in this row
constat.executeQuery(query);
if you want insert some data in data base you have to use this code
constat.executeUpdate(query);

Java web application DAO writing authenticated UserID and IP Address to DB

I'd like to write to my Oracle DB the user ID and IP address of the logged in user (web app) whenever I perform SQL UPDATEs and INSERTs. Such as
public static int updateUser(STKUser user, STKUser loggedIn) throws DAOException {
Connection connection = null;
connection = DB.getConnFromCache();
PreparedStatement ps = null;
String query = "INSERT INTO xtblPersonnel (pID, pPssWrd, pAdminDate, pAdminIP, pAdminBy) VALUES (?,?,SYSDATE,?,?)";
try {
ps = connection.prepareStatement(query);
ps.setString(1, user.getBadge());
ps.setString(2, user.getPassword());
ps.setString(3, loggedIn.getIpAddress());
ps.setString(4, loggedIn.getBadge());
return ps.executeUpdate();
}
catch (Exception e) {
System.out.println("SQL Exception inserting new user with badge: " + user.getBadge() + ". Error Message: " + e.getMessage());
LOGGER.log(Level.INFO, "SQL Exception inserting new user with badge: " + user.getBadge() + ". Error Message: " + e.getMessage(), user);
throw new DAOException("SQL Exception inserting new user!");
// return 0;
}
finally {
DB.closePreparedStatement(ps);
DB.releaseConnToCache(connection);
}
}
STKuser is a Javabean
My application uses a general Oracle db username and password so that is the reason why I want to record who did the update or insert and from which machine.
Is this an acceptable approach. I used to pass in the session but have realized this is a no no.
Assuming that you're properly closing all DB resources as Connection, Statement and ResultSet in the finally block of the try block where you acquired them and the code is doing what it should do, I don't forsee problems with the approach in question. There is no risk for SQL injections since you're using PreparedStatement, if that was your actual concern. Declaring the method static is however a bit a smell, but then we need to know more about the context the code is running in.

Categories

Resources