How to connect java to Ms access Database [duplicate] - java

This question already has an answer here:
Manipulating an Access database from Java without ODBC
(1 answer)
Closed 5 years ago.
i'm trying to connect the java to ms access database but it didn't work really well
and i got an error message like this
sun.jdbc.odbc.JdbcOdbcDriver
this is my code :
import java.sql.*;
public class main{
public static void main(String[] args) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver(*.accdb)};DBQ=D:\\Andries\\testdatabase.accdb");
Statement st = con.createStatement();
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

you can use ucanacess.jar for connect Ms Aceess database
show some example here http://www.benchresources.net/jdbc-msaccess-database-connection-steps-in-java-8/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MsAccessDatabaseConnectionInJava8 {
public static void main(String[] args) {
// variables
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
// Step 1: Loading or registering Oracle JDBC driver class
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
}
catch(ClassNotFoundException cnfex) {
System.out.println("Problem in loading or "
+ "registering MS Access JDBC driver");
cnfex.printStackTrace();
}
// Step 2: Opening database connection
try {
String msAccDB = "D:/WORKSPACE/TEST_WORKSPACE/Java-JDBC/Player.accdb";
String dbURL = "jdbc:ucanaccess://" + msAccDB;
// Step 2.A: Create and get connection using DriverManager class
connection = DriverManager.getConnection(dbURL);
// Step 2.B: Creating JDBC Statement
statement = connection.createStatement();
// Step 2.C: Executing SQL & retrieve data into ResultSet
resultSet = statement.executeQuery("SELECT * FROM PLAYER");
System.out.println("ID\tName\t\t\tAge\tMatches");
System.out.println("==\t================\t===\t=======");
// processing returned data and printing into console
while(resultSet.next()) {
System.out.println(resultSet.getInt(1) + "\t" +
resultSet.getString(2) + "\t" +
resultSet.getString(3) + "\t" +
resultSet.getString(4));
}
}
catch(SQLException sqlex){
sqlex.printStackTrace();
}
finally {
// Step 3: Closing database connection
try {
if(null != connection) {
// cleanup resources, once after processing
resultSet.close();
statement.close();
// and then finally close connection
connection.close();
}
}
catch (SQLException sqlex) {
sqlex.printStackTrace();
}
}
}
}

Related

Why does executeUpdate() function not work? Give steps to solve in a normal project rather than a maven based project [duplicate]

This question already has an answer here:
Caused by: java.lang.NoSuchMethodError: org.postgresql.core.BaseConnection.getEncoding()Lorg/postgresql/core/Encoding;
(1 answer)
Closed 4 years ago.
CODE:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aaa;
import static aaa.DB.geom;
import static aaa.DB.getConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] argv) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
// Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres", "postgres",
"abc");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
//Connection conn = getConnection();
connection.setAutoCommit(false);
Statement s = null;
try {
s = connection.createStatement();
} catch (Exception e) {
System.out.println("statmnt connection not works");
}
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ss.executeUpdate();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
String query = "CREATE TABLE COMPANY(ID INT );";
ResultSet r = s.executeQuery(query);
connection.commit();
} else {
System.out.println("Failed to make connection!");
}
}
}
RUN:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
You made it, take control your database now!
Exception in thread "main" java.lang.NoSuchMethodError:
org.postgresql.core.BaseConnection.getPreferQueryMode()Lorg/postgresql/jdbc/PreferQueryMode;
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:151)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
at aaa.JDBCExample.main(JDBCExample.java:69)
C:\Users\Dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
QUESTION:Give me steps to solve it since database is connected already! What is the core of the problem?
The problem is that if database postgresql connected then why not insert into database. The tables are also available and seen from netbeans. There needs to be a way to solve this run time exception issue when there is a query execution... So I needed step by step details to make it correct.
A SELECT statements has to be executed using executeQuery(). executeUpdate() is for DML statements like UPDATE, INSERT, or DELETE that don't normally return a ResultSet. Also, a DDL statement like CREATE TABLE can not be executed using executeQuery() you need execute() or executeUpdate() for that.
So your code should be:
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ResultSet rs = ss.executeQuery();
while (rs.next() {
// do something
}
rs.close();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
And:
String query = "CREATE TABLE COMPANY(ID INT );";
s.execute(query);
connection.commit();
You have connection.setAutoCommit(false); and you didnt commit after performing update. You have to commit your transaction in order for changes to apply. You can also setAutoCommit(true);

Why do I get a java.sql.PreparedStatement that is closed from an opened connection to MySQL?

Why do I get a java.sql.PreparedStatement that is closed from an opened connection to MySQL?
This is my code:
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class MySqlTest1
{
Connection connection = null;
PreparedStatement stmt = null;
public MySqlTest1()
{
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
String url = "jdbc:mysql://localhost:3306/world?autoReconnect=true&useSSL=false";
String username = "jee";
String password = "????????";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password))
{
if (connection.isClosed())
{
System.out.println("Returned connection is closed");
return;
}
System.out.println("Database connected!");
System.out.println("create statement ...");
**stmt = connection.prepareStatement("select * from city");**
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
System.out.println("Selecting data ...");
ResultSet rs = null;
try {
System.out.println("execute query ...");
rs = stmt.executeQuery();
if (rs != null)
{
System.out.println("Data selected");
}
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
return;
}
The result from that code is
Loading driver...
Driver loaded!
Connecting database...
Database connected!
create statement ...
Selecting data ...
execute query ...
****SQLException: No operations allowed after statement closed.****
SQLState: S1009
VendorError: 0
I have tried with the Statement as well and looked into its values and and found that "isClosed" is true.
I have looked into the MySQL log but found nothing.
You are opening the connection in a try-with-resource block. Once the block is terminated, the connection is closed, and implicitly, all the statements created from it. Just extend this block to include the usage of the statement, and you should be OK.

How to get a String from a field

I've got a mysql question within java. I've got a mysql database with different tables. I currently got a database called 'litebans' and a table called 'litebans_mutes'.
Within that table there is a row called reason and under that reason (let's say what's within reason) there's a string called 'This is a test' and 'sorry'; how would I get the string 'This is a test' and 'sorry' associated with the same 'uuid' row in java? Here is a picture explaining more:
Here is an image explaining the sql format
Additionally, i've currently initialized all variables and such in java, i currently have this code:
http://hastebin.com/odumaqazok.java (Main class; using it for a minecraft plugin)
The below code is the MySQL class; api used to connect and execute stuff.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.octopusmc.punish.Core;
public class MySQL {
public static Connection openConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e1) {
System.err.println(e1);
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://" + Core.host + ":" + Core.port + "/" + Core.database, Core.user, Core.pass);
System.out.println("Currently connected to the database.");
return conn;
} catch (SQLException e) {
System.out.println("An error has occured while connecting to the database");
System.err.println(e);
e.printStackTrace();
}
return null;
}
public static void Update(String qry) {
try {
Statement stmt = Core.SQLConn.createStatement();
stmt.executeUpdate(qry);
stmt.close();
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
}
public static Connection getConnection() {
return Core.SQLConn;
}
public static ResultSet Query(String qry) {
ResultSet rs = null;
try {
Statement stmt = Core.SQLConn.createStatement();
rs = stmt.executeQuery(qry);
} catch (Exception ex) {
openConnection();
System.err.println(ex);
}
return rs;
}
}
An example using that api above is shown below:
try {
ResultSet rs = MySQL.Query("QUERY GOES HERE");
while (rs.next()) {
//do stuff
}
} catch (Exception err) {
System.err.println(err);
err.printStackTrace();
}
tl;dr: I want to get the two fields called 'reason' with the give 'uuid' string field.
First , make sure that your using the jdbc mysql driver to connect to the database
Defile a class where you could write the required connection and create statement code.
For example
class ConnectorAndSQLStatement {
ResultSet rs = null;
public Statement st = null;
public Connection conn = null;
public connect() {
try {
final String driver = "com.mysql.jdbc.Driver";
final String db_url = "jdbc:mysql://localhost:3306/your_db_name";
Class.forName(driver);//Loading jdbc Driver
conn = DriverManager.getConnection(db_url, "username", "password");
st = conn.createStatement();
rs = st.executeQuery("Select what_you_want from your_table_name");
while (rs.next()) {
String whatever = rs.getInt("whatever ");
System.out.print(whatever);
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Just call this function and the magic :D
Hope it is helpful

The service class "WBSer_RwCnt.Rw_Count" does not comply to one or more requirements of the JAX-RPC 1.1 specification

package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
Class.forName(driver); // load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static int countRows(Connection conn, String tableName) throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName);
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
} finally {
rs.close();
stmt.close();
}
return rowCount;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = getConnection();
String tableName = "hospital_status";
System.out.println("tableName=" + tableName);
System.out.println("conn=" + conn);
System.out.println("rowCount=" + countRows(conn, tableName));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
// release database resources
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Error --->
The method "getConnection" on the service class "WBSer_RwCnt.Rw_Count" uses a data type, "java.sql.Connection", that is not supported
When i compile it without creating it as webservice it works correctly
but when i make it as web service it gives output as
Output --->
WBSer_RwCnt.Rw_CountSoapBindingStub#121a412b
Please Help !
Next Try
So this is what i have done after what you have said even then it gives following errors
Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
Message:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/hospital_data
package WBSer_RwCnt;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Rw_Count {
public static int countRows() throws SQLException {
// select the number of rows in the table
Statement stmt = null;
ResultSet rs = null;
System.out.println("ram");
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/hospital_data";
String username = "root";
String password = "mysql";
try {
Class.forName(driver);
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
// load MySQL driver
Connection conn = DriverManager.getConnection(url, username, password);
int rowCount = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT COUNT(*) FROM hospital_status");
// get the number of rows from the result set
rs.next();
rowCount = rs.getInt(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
finally {
rs.close();
stmt.close();
conn.close();
}
return rowCount;
}
}
i have the added all jar files including the java mysql connectors
This is not going to be a full answer as I'm not exactly sure about the tools you are using to compile the web service, but anyway, here goes:
Basically, a connection is something that is only valid on a particular machine. If it's a TCP/IP connection, it consists of two pairs: source host and port, and target host and port. If it's a Linux socket, then it is an entry in that particular machine's directory tree.
A database connection is usually built on one of those constructs, so it, too, is particular to a machine.
Therefore, it doesn't make sense to pass a Connection object to the user who calls your method from some remote machine. And since it doesn't make sense, the JAX-RPC standard does not include a serialization for Connection, and that's why it fails.
Your problem is that you have designed your method such that it accepts a connection as a parameter, and uses that connection to access the database. This works OK locally, but is not a good design for a remote service.
Instead, your method should acquire the connection internally. The remote user should access just the countRows method, with the name of the table, and countRows should call getConnection, use the connection, and the close it.
You shouldn't have a main method in a web service. And the getConnection method should be changed from public to private, so that countRows can access it. When it is private, I believe the web service compiler will not complain about it because it doesn't have to create a serialization for it.

java.sql.SQLException: Invalid handle

I'm trying to teach myself how to connect to a msaccess database in java.
I have set up a class to access the database as follows
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public abstract class AccessDBConnect2 {
public static Connection connect(){
String fileName = "C:/Users/Bridget/Documents/EmployeeSys.accdb";
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+fileName;
con = DriverManager.getConnection(url,"","");
} catch (Exception e) {
// Handle exceptions ...
System.out.println(e.toString());
System.out.println("A problem accessing the database");
e.printStackTrace();
} finally {
try { if(con!=null) {con.close();} } catch (Exception e) {}
}
return con;
}
public static void closeConnection(Connection conn){
try{
conn.close();
}catch (Exception e){
}
}
Then I have my code which is just trying to select everything from the table.
I have created the table in msAccess and the code seems to get through the connect method in the above code without any problems, indicating it is finding the database and accessing it somewhat. The problem happens when I call the prepareStatement using the connection, i.e. code line:
stm = conn.prepareStatement(sql);
The full code is:
import java.sql.*;
public class Program2{
public static void main(String[] args) {
try{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
// Establishing db connection
Connection conn = AccessDBConnect.connect();
// Displaying all records from employee file
System.out.println("Display records of all employees");
display(conn);
// Closing the connection
AccessDBConnect.closeConnection(conn);
}catch (Exception e){
System.out.println("Error");
}
}
// Display details of all employees
public static void display(Connection conn){
PreparedStatement stm = null;
// SQL statement
String sql = "SELECT * FROM Employee";
ResultSet rs;
try {
stm = conn.prepareStatement(sql); // Prepare the SQL statement
rs = stm.executeQuery(); // Execture the SQL statement
// Navigate through the ResultSet and print
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String address = rs.getString("address");
System.out.println("ID: \t \t" + id);
System.out.println("Name: \t \t" + name);
System.out.println("Gender: \t" + gender);
System.out.println("Address: \t" + address);
System.out.println(" ");
}
// Closing the resultSet
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void test(){
int a = "hello";
}
}
You are receiving the error because when you try to call .prepareStatement the connection is closed. Your AccessDBConnect2 class contains a finally block that closes the connection before it returns. Fix that class so it leaves the connection open.
By the way, the JDBC-ODBC Bridge has been removed from Java 8 and is effectively obsolete. You might be interested in this alternative:
Manipulating an Access database from Java without ODBC
I've removed the obviously incorrect answer :) another possibility:
I would think the issue is in your connection to the database, try changing 'C:/Users/Bridget/Documents/EmployeeSys.accdb' to 'C:\\Users\Bridget\Documents\EmployeeSys.accdb'

Categories