How do I connect to the database MS Access? - java

I have a Maven Project and I am trying to create a connection to my MS Access db. The problem is that it does not open.
I do not receive any type of error, but the program remains active without returning the connection. I tried to stay on hold two hours but nothing. The databaseProduction WellSys is linked to ProdWheelTableMasterSys and WhellDemand.
My code is:
package com.sealed.air.SealedAir;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class App {
public static void main(String[] args) {
String conex = "jdbc:ucanaccess://";
String url = "C:/DB/ProductionWhellSys.accdb";
try {
System.out.println("Connecting");
Connection con = DriverManager.getConnection(conex+url);
System.out.println("Connected");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And the result in the console is:
Connecting
My DB MS access properties:
console.bat output:
saved query in Access:
I have tried changing the "" in '' but I do not understand because it gives me the same error. Another mistake I found was:
Error message was: unexpected token: , required: )

It looks like you reported two different issues:
the first one is that the "the program remains active without
returning the connection" but seeing your App test, this doesn't seem due to ucanaccess... did you set Openexclusive=true?

Related

Snowflake JDBC Fail to retrieve row count for first arrow chunk: sun.misc.Unsafe or java.nio.DirectByteBuffer.<init>(long, int) not available

While my issue sounds same to this one Snowflake JDBC driver internal error: Fail to retrieve row count for first arrow chunk: null -- only occurs on SELECT statements, but actually it is not.
I am able to connect to Snowflake data warehouse from java:
public static Connection getConnection()
throws SQLException
{
String user = Optional.ofNullable(System.getenv("USER"))
.or(() -> Optional.ofNullable(System.getenv("USERNAME")))
.orElseThrow();
try
{
Class.forName("net.snowflake.client.jdbc.SnowflakeDriver");
}
catch (ClassNotFoundException ex)
{
System.err.println("Driver not found");
}
// build connection properties
Properties properties = new Properties();
properties.put("authenticator", "xxx");
properties.put("user", user);
String connStr = Optional.ofNullable(System.getenv("SF_JDBC_CONNECT_STRING")).orElse("jdbc:snowflake://xxx.xxx.com");
return DriverManager.getConnection(connStr, properties);
}
but when I try to run a very simple select statement from below code:
try {
Connection conn = Helper.getConnection();
Statement sqlStm = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
ResultSet sqlOutput = sqlStm.executeQuery("select getdate();");
while (sqlOutput.next()) {
System.out.println(sqlOutput.getInt(1));
}
}
catch (SQLException e){
e.printStackTrace();
}
I am getting below error:
net.snowflake.client.jdbc.SnowflakeSQLLoggedException: JDBC driver internal error: Fail to retrieve row count for first arrow chunk: sun.misc.Unsafe or java.nio.DirectByteBuffer.<init>(long, int) not available.
at net.snowflake.client.jdbc.SnowflakeResultSetSerializableV1.setFirstChunkRowCountForArrow(SnowflakeResultSetSerializableV1.java:1066)
at net.snowflake.client.jdbc.SnowflakeResultSetSerializableV1.create(SnowflakeResultSetSerializableV1.java:550)
at net.snowflake.client.jdbc.SnowflakeResultSetSerializableV1.create(SnowflakeResultSetSerializableV1.java:467)
at net.snowflake.client.core.SFResultSetFactory.getResultSet(SFResultSetFactory.java:29)
at net.snowflake.client.core.SFStatement.executeQueryInternal(SFStatement.java:220)
at net.snowflake.client.core.SFStatement.executeQuery(SFStatement.java:135)
at net.snowflake.client.core.SFStatement.execute(SFStatement.java:781)
at net.snowflake.client.core.SFStatement.execute(SFStatement.java:677)
at net.snowflake.client.jdbc.SnowflakeStatementV1.executeQueryInternal(SnowflakeStatementV1.java:238)
at net.snowflake.client.jdbc.SnowflakeStatementV1.executeQuery(SnowflakeStatementV1.java:133)
at com.marqeta.Main.main(Main.java:42)
I found on github that people had the same issue on this thread: https://github.com/snowflakedb/snowflake-jdbc/issues/484. I had set the VM options as per below, but still have the same error, did I set the VM options wrongly or what could be the issues please.
I added --add-opens java.base/java.nio=ALL-UNNAMED as VM argument for the tests and they are passing.
Please refer to this comment. Also, there is a good explanation of why this is happening. Passing the VM argument should be considered as a temporary solution.

Update query not working in preparedStatements Java

I am writing this program in which I am using preparedStatements to make changes to an SQL Database. However, the UPDATE query is not working.
Here is the code:
package financials;
import java.net.URL;
import java.util.ResourceBundle;
import java.sql.*;
public void initialize(URL url, ResourceBundle rb) {
try{
Class.forName("com.mysql.cj.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/finances","root","P#ssword");
con.setAutoCommit(true);// TODO
}
catch(Exception ae)
{
System.out.println("Error in connection !");
}
#FXML
private void SaveOrAdd(ActionEvent event) { //This is button which on click executes the following code
String Action=save.getText();
if(Action.equals("Add Account"))
{
String SBNumber=LinkedSB.getText();
String newAccountType=AccountTypeF.getText();
String newFHolder=FHolderF.getText();
String newSHolder=SHolderF.getText();
String newTHolder=THolderF.getText();
String Bankcode=BankCodeF.getText();
if(newAccountType.equals("")||newFHolder.equals("")||newSHolder.equals("")||newTHolder.equals(""))
{
update.setText("Please fill in all the fields !");
}
else
{
try
{
PreparedStatement pst=con.prepareStatement("INSERT INTO banklines (Bank_Code,Linked_SB_Account,Sb_Account_Type,First_Holder,Second_Holder,Third_Holder) VALUES (?,?,?,?,?,?)");
pst.setString(1,Bankcode);
pst.setString(2,SBNumber);
pst.setString(3,newAccountType);
pst.setString(4,newFHolder);
pst.setString(5,newSHolder);
pst.setString(6,newTHolder);
int a=pst.executeUpdate();
System.out.println(a); //This returns a 1
}
catch(Exception ae)
{
update.setText("Update Failed !");
}
}}
else
{
String SBNumber=LinkedSB.getText();
String newAccountType=AccountTypeF.getText();
String newFHolder=FHolderF.getText();
String newSHolder=SHolderF.getText();
String newTHolder=THolderF.getText();
String Bankcode=BankCodeF.getText();
if(newAccountType.equals("")||newFHolder.equals("")||newSHolder.equals("")||newTHolder.equals(""))
{
update.setText("Please fill in all the fields !");
}
else //This is the block in concern
{
try
{
//Here is where the issue starts !
PreparedStatement pst2=con.prepareStatement("UPDATE banklines SET Sb_Account_Type=?,First_Holder=?,Second_Holder=?,Third_Holder=? WHERE Linked_SB_Account=? AND Bank_Code=?");
pst2.setString(1,newAccountType);
pst2.setString(2,newFHolder);
pst2.setString(3,newSHolder);
pst2.setString(4,newTHolder);
pst2.setString(5,SBNumber);
pst2.setString(6,Bankcode);
pst2.executeUpdate();
int a=pst2.executeUpdate();
System.out.println(a); //This returns a 0
update.setText("Successfully Updated !");
}
catch(Exception ae)
{
update.setText("Update Failed !");
}
}
}
}
The problem is that no error is being thrown, that is, the output is always Successfully Updated. However, the changes are not being reflected on the database. I have tried executing the query UPDATE banklines SET Sb_Account_Type=?,First_Holder=?,Second_Holder=?,Third_Holder=? WHERE Linked_SB_Account=? AND Bank_Code=? separately as a query in mySQL workbench, and it returns no error. I have also ensured that no variable is left blank. In-spite of all this, the update is not working. What confused me even more is that the previous query in the if-else block, that is the INSERT query works perfectly, and the results are updated in the database as well.
I am using NetBeans 8.2 with jdk 1.8 and mysql-connector-java-8.0.21.
P.S. I have stuck to java naming conventions to the best of my knowledge, ensuring that I follow CamelCase notation wherever I could. Please edit my code or suggest changes if you feel that anything is wrong.
The column names of your insert statement don't match the order of the bind variables which means that your inserted record has the wrong account id values.
For example you set SBNumber as index 6 when it should be:
pst.setString(2,SBNumber);
It is also good practice to check the number of rows changed by updates so that you can make further asserts / checks on your actions:
int rows = pst.executeUpdate();
if (rows != 1) throw new RuntimeException("Failed to update account: "+ SBNumber);
In your case rows is set to 0 as the row to update is never found - because Linked_SB_Account is not matched.

How to force renaming of variable names in eclipse mars

How can I force eclipse mars to rename variable names?
When I try, I get
This refactoring cannot be performed correctly due to syntax errors in
the compilation unit.
The dialog only offers "Cancel".
It was possible to do this in older versions of eclipse, and I used the feature extensively, for example after copy&paste of code snippets found on the net.
Note this is not a duplicate of Refactoring variable names in Eclipse .
Edit 3 (summary of what happened):
In the code (shown below) were not only those common errors like missing imports or undeclared variables, but also a missing ";", thus a true syntax error. This, at first hidden among several other compiling issues, caused eclipse to refuse the refactoring.
As it turned out, this is not a special feature of mars but also of older versions of eclipse.
Edit: here comes my example code. It is mainly based on the examples from tutorialspoint for mongodb but very probably doesn't have anything to do with mongo.
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC2 {
private static String myUserName;
private static String myPassword;
private static String myHost = "localhost";
private static String myDatabaseName = "mydb";
private static MongoDatabase db;
public MongoDBJDBC2() {
initDb();
// TODO Auto-generated constructor stub
}
public static void main(String args[]) {
MongoDBJDBC2 mo = new MongoDBJDBC2();
}
private static void initDb() {
MongoClientURI uri = new MongoClientURI(
"mongodb://" + myUserName + ":" + myPassword + "#" + myHost + "/?authSource=db1");
try (MongoClient mongoClient = new MongoClient(uri);) {
db = mongoClient.getDatabase(myDatabaseName);
System.out.println("Connect to database successfully");
// boolean auth = db.authenticate(myUserName, myPassword);
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
}
public static void main4( String args[] ) {
try{
// To connect to mongodb server
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
DBCursor cursor = coll.find();
while (cursor.hasNext()) {
DBObject updateDocument = cursor.next();
updateDocument.put("likes","200")
col1.update(updateDocument);
}
System.out.println("Document updated successfully");
cursor = coll.find();
int i = 1;
while (cursor.hasNext()) {
System.out.println("Updated Document: "+i);
System.out.println(cursor.next());
i++;
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
I try to rename db to myDb in
private static MongoDatabase db;
Previously I used eclipse Helios and never encountered this kind of "feature".
Edit2: I have located the fatal error. In method "main4" a semicolon is missing after
updateDocument.put("likes", "200")
Still don't understand why this upsets eclipse so much that it refuses to refactor, and I still would like to know if there is a way to force refactoring despite of errors.
Compilers issue two kinds of errors: syntax errors and all other kinds of errors, like "type mismatch" and "symbol not found". Eclipse complains about a syntax error. Are you sure that in previous occasions when Eclipse agreed to refactor your code despite the fact that it contained errors, it was syntax errors that your code contained? You see, there is a big difference.
Refactoring symbol names in java is far more involved than a simple text search and replace, the structure of your code has to be taken into account.
But in the case of a syntax error, the compiler has given up parsing your file, so it does not know the structure of your code: it does not know which tokens are variables, which tokens are types, which tokens are methods, etc. so it really cannot do the refactoring that you want.
So, if you must really proceed with your refactoring despite having syntax errors, then I am afraid that text search and replace is the way to go for you in this particular case.
But fixing the syntax errors before attempting to refactor would be the most prudent thing to do.
This happens when there is compilation issue in your code.
Fix the compilation issue than you can refactor your code.Yes this feature is recently introduced in newer version of eclipse.

classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver and mapping_data_source ::init error : file not found

//java program to insert a row into a table using Statement![the output of the program is shown in the image provided by the link given at the bottom
import java.io.*;
import java.lang.*;
import java.sql.*;
class stmtinserts
{
public static void main(String a[])throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:test");
String s = "insert into cricket values(10, 'name1', 10000)";
Statement st=con.createStatement();
int i = st.executeUpdate(s);
if(i > 0)
System.out.println("data inserted ");
else
System.out.println("data is not inserted");
st.close();
con.close();
}
}
Click this link to view the image
My operating system is windows 7 ,32 bit system.
java version is 1.8.0_05.
also give me suggestions about error "mapping_data_source ::init error : file not found".
when ever i type java or javac, i find this error.
Help from any one is appreciated.thanks in advance.

Retrieving value from objectdb database from program

I am facing some problems while I am trying to fetch data through the program. I am using objectDB as my database. Also, my database is already set up and I have dropped the laptop.odb file in the db folder of my objectDB installation. Also, when I go to the explorer and fire the query:
select this.modelName == "HP Pavillion"
correct results comes up. But, when I try to do the same thing with my code as in the following
public static void main(String argv[]) {
PersistenceManager pm = Utilities.getPersistenceManager("laptop.odb");
System.out.println("-- TEST --\n");
Query query = pm.newQuery(Laptop.class,"this.modelName == \"HP Pavillion\"");
Collection result = (Collection)query.execute();
System.out.println("Result is >> "+result);
Here no results are returned. My output is :
-- TEST find --
Result is >> []
My code for the class is the following.
package com.project;
import java.util.*;
import javax.annotation.processing.Processor;
import javax.jdo.*;
import com.objectdb.Utilities;
public class Laptop {
String modelName; // key
public static void main(String argv[]) {
PersistenceManager pm = Utilities.getPersistenceManager("laptop.odb");
System.out.println("-- TEST find --\n");
Query query = pm.newQuery(Laptop.class,"this.modelName == \"HP Pavillion\"");
Collection result = (Collection)query.execute();
System.out.println("Result is >> "+result);
}
Any suggestions ?
The reason could be that "laptop.odb" refers to a non existing ObjectDB database. In that case a new database is automatically created. Because the new database it is created empty, no results are returned from the query.
Try specifying an absolute path to the existing database.

Categories

Resources