problems in connecting java with ms access - java

hye all..
i am currently doing my final year project in java.i want to connect a ms access database using java.But sadly i'm using windows 7 starter that cannot support odbc.do you have any idea i can solve this problem?thank for all your coming idea and help =)

Simply try to have another OS get installed or try to have some of the drivers that support JDBC and you will surely able to work in connecting dtabase with java.

You could try JDBC drivers like these:
http://www.csv-jdbc.com/stels_mdb_jdbc.htm
http://www.hxtt.com/access.html
Both are commercial products.
A free option would be to migrate the database to SQL Server Express and then use the SQL Server JDBC drivers to connect to that.

I used the sun.jdbc.odbc.JdbcOdbcDriver to connect to a MS Access database. Have that in the same directory as the class file and it should work. Although it should come already installed in the Java SDK.
This is a sample of a practice program I made a while ago.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
Connection connection = DriverManager.getConnection
("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=(MS ACCESS DATABASE DIRECTORY)");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
ResultSet resultSet = statement.executeQuery
("select f_name, l_name from Test where f_name = 'Luke'"); // For example
// Iterate through the result and print the results
while (resultSet.next())
System.out.println(resultSet.getString(1) + "\t" + resultSet.getString(2) );

Related

Why is this mySQL database not connecting to Netbeans?

The mysql database will not connect to the netbeans code. I am using a Mac Device and have installed mySQL on my device (it is running fine on localhost:8080). However, the connection through Java is not working. I believe there may be an error in the following line "conn = Driver Manager..." since it is not executing. I am unsure of how to change the password / what the password is.
Restarting Xampp
Screenshot of connection code
Expected result: user input is sent to mySQL database
Actual result (error): seen in this screenshot
This is the general database connectivity code .
try
{
Class.forName("java.sql.DriverManager");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","MysqlUsername","MysqlPassword");
Statement stmt = (Statement) con.createStatement();
String query = "YourMysqlQuery";
stmt.executeUpdate(query);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}
// You also have to add 'jdbc driver' in lib folder of your project.
If want us to solve the problem in your code then please provide the actual code you have done , Not the image .

Establish connection between app server and oracle database using java

I have been given a task to write a script in java, to connect oracle database from an app server. Scheduling tool will be used to schedule the job every 10 minutes.
If connection exists, the script will do nothing and just disconnect it. (and will be run again after 10 minutes).
If cannot connect after 10 secs, the program will send an email notification.
The whole thing is to ensure connection can be established between the app server and the oracle db.
Really have no clue on this. Could you please advise what are the steps to do this and what Java APIs I'll need??
Many many thanks in advance!
You will need classes out of the java.sql package. Assuming Java 7+.
import java.sql.*;
public class Test {
public static void main(String[] args) {
String url = "..."; // Specify according to JDBC driver in use
String sql = "SELECT 1 FROM DUAL"; // Test statement. Change depending on SQL vendor
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {/*Nothing to do*/}
} catch (SQLException e) {
// Send email here
}
}
}
If you are using J2EE App Server, create a database connection pool there which your application is also going to use.
One of the parameters of the database pool can be to verify the connection at regular intervals by sending simple SQL. Then your task boils down just to monitor the logs to see if database connection pool throws any errors when polling.

Oracle 12c database connection using thin driver throws IO error

I'm following the JDBC Developer's Guide and trying to test the JDBC thin driver connection using a short java program.
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class JDBCVersion
{
public static void main (String args[]) throws SQLException
{
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:hr/hr#localhost:1522:orcl");
Connection conn = ods.getConnection();
// Create Oracle DatabaseMetaData object
DatabaseMetaData meta = conn.getMetaData();
// gets driver info:
System.out.println("JDBC driver version is " + meta.getDriverVersion());
}
} //<host>:<port>:<service>
I've tried every possible <host>:<port>:<service> combination but still get a java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
I've successfully tested the OCI driver using another program included in the tutorial....but can't get this one to work. My application will be using the thin driver to connect to the database so my frustration level is....climbing.
Any help is appreciated.
Maybe following comments could explain why you need the sevice name instead of the SID in the URL.
the Oracle JDBC FAQ mention that SIDs will be cease to be supported in one of the next few releases of the database
the Oracle JDBC devolopers guide mention Always connect to a service. Never use instance_name or SID because these do not direct to known good instances and SID is deprecated
the Oracle 2 day + Java developer tutorial mention the syntax jdbc:oracle:driver_type:[username/password]#//host_name:port_number:SID which seems to be a mixture of SID and service name URL (following the other documents and your working example)
in contrast the javadoc for OracleDriver mention only the SID syntax
the Oracle FAQ wiki mention both syntax
.
jdbc:oracle:thin:[USER/PASSWORD]#[HOST][:PORT]:SID
jdbc:oracle:thin:[USER/PASSWORD]#//[HOST][:PORT]/SERVICE
I'm able to connect to my container DB (containing my tables, packages, etc.) using the username/password.
Returns:
JDBC driver version is 12.1.0.2.0
Still can't connect to the tutorial "HR" PDB that comes with the oracle 12c install and which the JDBC tutorial uses.
Edit:
Got it to work using the following:
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class JDBCVersion
{
public static void main (String args[]) throws SQLException
{
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:#//localhost:1522/pdborcl.global.XXXXXXXX.com");
ods.setUser("hr");
ods.setPassword("hr");
Connection conn = ods.getConnection();
// Create Oracle DatabaseMetaData object
DatabaseMetaData meta = conn.getMetaData();
// gets driver info:
System.out.println("JDBC driver version is " + meta.getDriverVersion());
}
}
Still don't understand why I need the full global name instead of the instance name.
When connecting to a PDB you should always use the PDB's service name in the connection string. It looks like your PDB's service is "pdborcl.global.XXXXXXXX.com" so that's what you need to use to connect the PDB directly.
Personally I find it easier to use the long URL format:
"jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=pdborcl.global.XXXXXXXX.com)))"
It makes it obvious that you're using a Service name instead of an SID.
The beauty of it is that you can also easily test your connection string with sqlplus:
sqlplus "hr/hr#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=pdborcl.global.XXXXXXXX.com)))"
If sqlplus works there is not reason why the JDBC Thin driver wouldn't.
Finally you can also connect the root database using a privilege user and then execute "ALTER SESSION SET CONTAINER=pdb" to switch to the PDB. Should you decide to do so you would have to modify your connection string to connect to the root container first. It should have its own service name.

How to connect to a database using a distributed API?

I'm having trouble with my distributed application in java netbeans the program is running perfectly on the original machine where i created it. but when i build it and make a distribute folder and follow the instructions and try to run it, I got an error that localhost on port 1527 has been refused.
here is my code on my do connect function
public void DoConnect()
{
String host = "jdbc:derby://localhost:1527/KempDB";
String uName = "main";
String uPass = "admin";
try
{
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select cv.checkvouchernumber, c.checknumber, paytoorder, bankcode, dateissued, amount from checkvoucher cv, checks c where cv.checkvouchernumber = c.checkvouchernumber and cv.checknumber = c.checknumber";
rs = stmt.executeQuery(sql);.....
..........
}
catch(SQLException err){
.......
}
so this is the code I used to connect with the database server, the database server I used is built-in with java. Its a apache derby...
like I said in the original machine where I created the program runs ok without errors but when I distribute the program to another machine there's an error refusing the connection.
How can I connect to the local machine where my database is? maybe you can help me on this.
Are the database Servers running on these machines?
Are u starting the database server programmatically?
If you try to connect a database Server with:
jdbc:derby://localhost:1527/KempDB
This Server needs to be up and running.
For your case you should use an embedded Database.
For the case your Database is already an embedded Database, then you can try using this URL:
jdbc:derby:KempDB
instead of:
jdbc:derby://localhost:1527/KempDB
Hav a look on this one

Problems logging into MSSQL server from Java

I am trying to connect to MSSQL server 2008 on my localhost, but I am getting Errors
WARNING: ConnectionID:2 Prelogin error: host 127.0.0.1 port 1434 Error reading prelogin response: Connection reset
this error repeats like 20 times very quickly, then i get
com.microsoft.sqlserver.jdbc.SQLServerException: Connection reset
I suspect this is some wrong configuration of server. I can connect to external servers with no issues. I can also connect via management studio with no problems.
Please help me, I am getting sick of this issue :|
1) TCP protocol for MSSQL 2008 is disabled by default. You need to enable it from SQL Configuration Manager (in the same [Start], Programs folder as MSSQL):
http://msdn.microsoft.com/en-us/library/ms190425%28v=sql.105%29.aspx
2) To use TCP connections (even on localhost!) you need to allow MSSQL in Windows Firewall:
http://technet.microsoft.com/en-us/library/cc646023.aspx
3) You don't necessarily need to use TCP/IP in order to access MSSQL:
http://msdn.microsoft.com/en-us/library/ms187892%28v=sql.105%29.aspx
'Hope that helps!
To connect to MSSQL Server from a Java application, you need to use the JDBC API. The JDBC API provides classes and methods that connect to the database, load the appropriate driver, send SQL queries, retrieve results etc.
HOW TO CONNECT TO THE DATABASE A ‘Connection’ object represents a connection with a database. To establish the connection, use the method ‘DriverManager.getConnection’. This method takes a string containing a URL which represents the database we are trying to connect to. Below is the sample code for establishing a connection:
private String DATABASE_URL = "jdbc:odbc:embedded_sql_app"; // establish connection to database
Connection connection = DriverManager.getConnection( DATABASE_URL,"sa","123" );
Detailed discussion about the Database URL and how to create it can be found in the resource provided at the end of this post.
QUERYING THE DATABASE The JDBC API provides three interfaces for sending SQL statements to the database, and corresponding methods in the ‘Connection’ interface create instances of them. 1. Statement - created by the ‘Connection.createStatement’ methods. A ‘Statement’ object is used for sending SQL statements with no parameters.
2. PreparedStatement - created by the ‘Connection.prepareStatement methods’. A ‘PreparedStatement’ object is used for precompiled SQL statements. These can take one or more parameters as input arguments (IN parameters).
3. CallableStatement - created by the ‘Connection.prepareCall’ methods. ‘CallableStatement’ objects are used to execute SQL stored procedures from Java database applications.
RETRIEVING THE RESULT A ‘ResultSet ‘is a Java object that contains the results of executing a SQL query. The data stored in a ‘ResultSet’ object is retrieved through a set of get methods that allows access to the various columns of the current row. The ‘ResultSet.next’ method is used to move to the next row of the ‘ResultSet’, making it the current row. The following code fragment executes a query that returns a collection of rows, with column ‘a’ as an ‘int’, column ‘b’ as a ‘String’, and column ‘c’ as a ‘float’:
java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) { // retrieve and print the values for the current row
int i = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f); }
This is just a brief introduction on how to interact with a database from Java. For more details on the items discussed above as well as information on passing parameters, executing stored procedures etc. please refer to the following resource: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html#Shahriar_N_Embedding_SQL_in_Java ) Here, you will also find information on how to interact with a database programmatically; i.e. without using SQL. Hope you find this useful.

Categories