Select a specific value in Access using SQL - java

I am working on a project that links Access to a Java GUI. I am currently looking for a way to select a record, in a query, that contains a specific value.
If my fields are:
Name | Job | Hours Worked
Tom | Sales Support | 6
Bill | Manager | 8
Tom | Sales Floor | 5
and I enter Tom in a search field in the GUI, I would like it to return the following to the GUI:
Name | Job | Hours Worked
Tom | Sales Support | 6
Tom | Sales Floor | 5
I tried using this code:
ArrayList<String> list = new ArrayList<>();
String filePath = "C:\\Users\\Bob\\Schedule.accdb";
Connection con=DriverManager.getConnection("jdbc:ucanaccess://"+filePath);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM [Double Booking] WHERE [Name] = Tom");
while(rs.next()) list.add(rs.getString(1));
con.close();
return list.toArray();
but I get the error:
net.ucanaccess.jdbc.UcanaccessSQLException: user lacks privilege or object not found: TOM
When I enter st.executeQuery("SELECT [Name] FROM [Double Booking]") I get a similar error:
net.ucanaccess.jdbc.UcanaccessSQLException: user lacks privilege or object not found: DOUBLE BOOKING

Since Tom is intended to be a string literal, you need to add quote characters:
"SELECT * FROM [Double Booking] WHERE [Name] = 'Tom'"
That said, if 'Tom' is just an example, it would be better to use a parameterised query if possible.

Related

HQL How to query Table with List of Objects as a set of conditions?

I have a class called form
Class Form {
String id;
String version;
String minVersion;
}
Now I have a List<Form> with me.
I have to query a table which satisfies the condition such that the id, version, type all as a set satisfies ie. I want to find all the {id, version, minVersion} which is the exact same in the table from my list. For example
I have a table like this
+----+---------+------------+---------+
| id | version | minVersion | passage |
+----+---------+------------+---------+
| 1 | 2 | 2 | Hi |
| 1 | 3 | 1 | Hello |
| 2 | 2 | 2 | Hi |
| 3 | 3 | 3 | Hi |
+----+---------+------------+---------+
I want to select 2 rows from it given as a List: {id: 1, version: 3, minVersion: 1} and {id: 2, version: 2, minVersion: 2}
I wrote a query like this,
SELECT id, version, type, passage FROM Content WHERE (id, version, type) IN (:id, :version, :minVersion);
But how do to convert into HSQL and setParameter for it?
Suggestion if your table size is small get all the elements specific to ids and filter in java layer
Please use the IN syntax in your query and setParameterList API.
For Example:
String hql = " SELECT id, version, type, passage FROM Content WHERE id in (:ids) "
And while forming query use
Query query = session.createQuery(hql);
query.setParameterList("ids", idList);
Refer this
Try this:
List<Form> findByIdInAndVersionInAndMinVersionIn(List<String> ids, List<String> versions, List<String> minVersions);

Showing parameter number 2 is not an OUT parameter while calling a procedure using java

I am trying to call a stored procedure using java.
I am a beginner in stored procedure.
So tried the same first in mysql terminal
mysql> delimiter //
mysql> create procedure get_EmployeeName(IN cust_id INT,OUT cust_name varchar(20))
-> begin
-> select name into cust_name from CUSTOMERS where id = cust_id;
-> end //
Query OK, 0 rows affected (0.11 sec)
mysql> delimiter ;
mysql> call get_EmployeeName(1,#cust_name);
Query OK, 1 row affected (0.08 sec)
mysql> select #cust_name;
+------------+
| #cust_name |
+------------+
| A |
+------------+
1 row in set (0.01 sec)
I am able to get the output.
Now tried using Java.
Create procedure statement
stmt.execute("create procedure mydb.WhoAreThey(IN id INT, OUT name VARCHAR(20)) begin select Name into name from employees where EmployeeID = id; end");
Procedure Call
Not sure if my procedure call is right or wrong
String IN = "1000";
cs = con.prepareCall("{call WhoAreThey(?,?)}");
cs.setString(1, IN);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
Above call gives an sqlexception
"SQLException: Parameter number 2 is not an OUT parameter"
UPDATE
worked by calling " cs = con.prepareCall("{call mydb.WhoAreThey(?,?)}");"
But When I did select #name..it is showing "Null".
I expected my out as "David Walker" from employees table as EmployeeID is 1000.
mysql> select * from employees;
+------------+--------------+--------+---------------------+
| EmployeeID | Name | Office | CreateTime |
+------------+--------------+--------+---------------------+
| 1000 | David Walker | HQ101 | 2016-12-21 13:00:37 |
| 1001 | Paul Martin | HQ101 | 2016-12-21 13:00:37 |
+------------+--------------+--------+---------------------+
2 rows in set (0.00 sec)
Am I checking in a wrong way(select #name)
Instead of calling WhoAreThey call mydb.WhoAreThey
String IN = "1000";
cs = con.prepareCall("{call mydb.WhoAreThey(?,?)}");
cs.setString(1, IN);
cs.registerOutParameter(2, Types.VARCHAR);
cs.execute();
To fetch the value of OUT param USE:
String name = cs.getString(2);

Caused by: java.sql.SQLException: Subquery returns more than 1 row on all rows where emailAccess is thesame

I am trying to retrieve all rows where emailAccess is equal to john#yahoo.com
user table is structured this way
id | name | email | emailAccess
1 | john |john#yahoo.com | john#yahoo.com
2 | jeff |jeff#yahoo.com | john#yahoo.com
I have a log table like this
id | userId | message
1 | 1 | bla bla
2 | 2 | 1234
now I am using the following hql query to retrieve the log based on the userId where emailAccesss from sesssion is john#yahoo.com
String hql = "FROM Chat c WHERE c.user = (FROM User u WHERE u.emailAccess = :emailAccess)";
return _sessionFactory.getCurrentSession().createQuery(hql).setParameter("emailAccess", emailAccess).list();
trying to use the above hql query gives me this error
Caused by: org.hibernate.exception.DataException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:135)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
second stacktrace
Caused by: java.sql.SQLException: Subquery returns more than 1 row
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
Where am I failing.
Kindly assist!
using hql allows you to access objects and their attributes, try this query :
String hql = "FROM Chat c WHERE c.user.emailAccess = :emailAccess"
(FROM User u WHERE u.emailAccess = :emailAccess)
This returns more than one row and you have:
WHERE c.user =
You can't have an equals with multiple results on the right. Either change your query to return a single row or change to be something like:
WHERE c.user in

Testing a method to return unique values from a result set of a db query

Let's say there is a database table named "Students".
Students Table
|---------------|---------------|
| Name | Age |
|---------------|---------------|
| John | 9 |
|---------------|---------------|
| Jane | 7 |
|---------------|---------------|
| Dana | 8 |
|---------------|---------------|
| John | 6 |
|---------------|---------------|
I make a request to the database to return all names using:
SELECT Name FROM Students
So the result set would be:
ResultSet rs = {"John" "Jane" "Dana" "John"}
I then want to return all unique values so I write a method called populateSet() to populate a HashSet setOfNames with rs.
After executing populateSet(ResultSet rs), only unique names appear:
"John" "Jane" "Dana"
Here is the validation test:
public void testValidation() {
// Skipping the test data / db connection / query part
ResultSet rs = ResultSet received back from DB
Set<String> expected = {"John", "Jane", "Dana"};
Set<String> actual = WhateverClass.populateSet(rs);
assertEquals(expected, actual);
}
What are some of the possible unit tests that I could write?
I know I should write a null, empty, and negative tests. What are some corner cases?
Potential corner cases:
Very large table (millions of rows)
Transactionality - e.g, what happens if a name is inserted/deleted/updated after you start the table scan?
Data ordering
Case sensitivity/insensitivity of names
non-ASCII characters in names

java.sql.SQLException: Column count doesn't match value count at row 1 [duplicate]

This question already has answers here:
java.sql.SQLException: Column count doesn't match value count at row 1
(3 answers)
Closed 6 years ago.
I'm trying to update values using JDBC and I continue to get the same error for different tables and with different schemas.
Let's say that I have a table like this
+----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+-------+
| field1 | varchar(50) | YES | | NULL | |
| field2 | varchar(50) | YES | | NULL | |
+----------------+-------------+------+-----+---------+-------+
then, I try to add a row:
String Text1 = text1;
String Text2 = text2;
String Query_String = "INSERT INTO tablename(field1,field2) VALUES ('"+Text1+","+Text2+"')";
Query_Statement.executeUpdate(Query_String);
the number of columns is the same, and also in the text there are not other commas, but I continue to get the error "java.sql.SQLException: Column count doesn't match value count at row 1"
I'm sure it's something simple, probably on the syntax since I managed to make it to work with a single column...
Thanks in advance
There is something wrong with:
String Query_String = "INSERT INTO tablename(field1,field2) VALUES ('"+Text1+","+Text2+"')";
You've missed some quotes between Text1 and Text2:
String Query_String = "INSERT INTO tablename(field1,field2) VALUES ('"+Text1+"','"+Text2+"')";
String Query_String = "INSERT INTO tablename(field1,field2) VALUES ("'"+Text1+"' , '"+Text2+"');";
It should like this note ' this
PreparedStatement would be better choice.
you have got a mistake with your quotes...
the following will be executed:
INSERT INTO tablename(field1,field2) VALUES ('Text1,Text2');
you have to write:
String Query_String = "INSERT INTO tablename(field1,field2)
VALUES ('"+Text1+"','"+Text2+"')"

Categories

Resources