Writing to access database in Java? - java

I'm working on a database project about adding, editing and deleting registries to a Students table which has fields:
Last_names, Names, IcNumber, Average, Entry_mode, Career and Change
In the editing frame i have a field where user types the icnumber of the student to edit its data, asks for the new data and saves it to a "Students" data structure, and then reupdates the registry with the new data:
String stmnt = "Insert Into Students (Last_names, Names, IcNumber, Average, " +
"Entry_mode, Career, Change) Values ('" + student.getLastNames() +
"', '" + student.getNames() + "', '" + student.getIcNumber() + "', " +
student.getAverage() + ", '" + student.getEntry() + "', '" +
student.getCareer() + "', '" + student.getChange() + "') " +
"Where IcNumber = '" + field.getText() + "'";
statement.execute(stmnt);
And i get this Error message:
[Microsoft][Microsoft Access ODBC Driver] "Query input must contain at least one table or query."
I have tried a similar SQL Instruction in the adding registry area of my program without the "Where" condition and works good, anyone knows about that error?

You should use a subquery, first the SELECT part with WHERE and then the INSERT part
Something like:
if (cond){
(SELECT.....)
(INSERT INTO...)}

Why are you using where in a insert statement? Where clause is applicable in select, update and delete statements but not in insert. Also I don't see any need of the where clause in your query.
Simply use the insert statement without where clause.

Use an INSERT statement to add a new record. A WHERE clause does not belong in an INSERT statement.
If you're editing an existing record, then you should use an UPDATE statement, and a WHERE clause makes sense to identify which record to change.

Related

JDBC Java, row column count mismatch

I keep getting this error
Caused by: org.hsqldb.HsqlException: row column count mismatch
I don't have idea why Im getting this error Im trying to resolve this problem from about 1 hour.
Im getting this error while Im trying to add new record to database with one user gonna make.
if(ae.getActionCommand()=="Save")
{
stmt.executeUpdate("INSERT INTO Table2 VALUES('" + t.getText() + "','" + t10.getText() + "','" + t2.getText() + "','" + t3.getText() + "','" + t8.getText() + "','" + t12.getText() + "','" + t11.getText()+"')" );
dbClose();
dbOpen();
Do not use insert in this form:
INSERT INTO TAB VALUES(1,2,'x')
but use explicit column list and bind variables:
INSERT INTO TAB (COL1, COL2, COL3) VALUES(?,?,?)
The problem you have is that the table has a different number of columns than defined in your VALUES clause.
The latter form of insert disables this problem as you explicitly defines what columns are inserted. The insert remains valid event if the table structure is compatible upgraded (add column).

Pass email as a parameter for SQL query, PostreSQL, JAVA

I'm trying to pass the email as a parameter for the SELECT SQL query in my JAVA back-end.
As i understood, for some reason it pass only "email_name" from the "email_name#email.com". (Getting this error):
Threw a SQLException creating the list of blogs.
ERROR: column "email_name" does not exist
Position: 174
There is an existed rows, which contains "email_name#email.com".
(Why "ERROR: column"? according to query it should look for a value, no?)
Here is My query:
String active_user = "email_name#email.com"; //email_name#email.com - example, active_user receive some path variable and on this particular moment(before query execution) contains exactly "email_name#email.com".
ResultSet rs = st.executeQuery("SELECT \n" +
" goods.item_title, \n" +
" goods.item_descr, \n" +
" goods.item_email,\n" +
" goods.item_images,\n" +
" goods.item_phone, \n" +
" goods.item_price \n" +
"FROM \n" +
" public.goods\n" +
"WHERE goods.owner = "+active_user+"\n" +
"ORDER BY\n" +
" goods.item_id ASC;");
So the question is - how to pass full email to query?
Try using String active_user = "'email_name#email.com'";. with single quotes. Since postgre recognized as column when you use double quotes.
You should use PreparedStatement. this is a example
Very unsafe approach, you should use PreparedStatement to avoid SQL injection. Here is existing answer

How do I form this complex query in Hibernate?

I'm building a REST service using Hibernate, Spring HATEOAS and Jackson. I am adding a method which returns a JSON representation of the results of a query like the one below;
SELECT ERRORS.DMN_NAM, CODES.MSG_TXT,
FROM SERV_ERR ERRORS, EVENT_CD CODES
WHERE ERRORS.SERV_RESP_CD_TXT = CODES.CD_TXT
GROUP BY ERRORS.DMN_NAM, ERRORS.SERV_NAM, CODES.MSG_TXT,
ERRORS.SERV_ERR_CNT, ERRORS.ERR_TS_NUM
ORDER BY ERRORS.DMN_NAM, CODES.MSG_TXT
I currently have two objects defined (ErrorsEntity and EventCodeEntity) which map to the tables SERV_ERR and EVENT_CD.
So the results of this query will be a list, but not of ErrorsEntity or EventCodeEntity but rather an amalgamation of the two entities.
Up to now, my queries have all returned objects that map directly to one table like so:
public List<ErrorsEntity> getErrors(double daysPrevious, double hoursToShow);
What's the best way to handle this in Hibernate where the results of a query aren't objects that are mapped to a single table and how can I write this query in HQL?
It's better to stick to an SQL query then, since HQL makes sense only when you plan on changing states from the resulted entities. In your case, the SQL is a better alternative, since it doesn't really follow the standard and you only want a projection anyway. You could remove the group by with distinct but it will require a derived table, which can be done in plain SQL anyway.
List dtos = s.createSQLQuery(
"SELECT " +
" ERRORS.DMN_NAM AS dmnNam, " +
" CODES.MSG_TXT AS msgTxt " +
"FROM SERV_ERR ERRORS, EVENT_CD CODES " +
"WHERE ERRORS.SERV_RESP_CD_TXT = CODES.CD_TXT " +
"GROUP BY " +
" ERRORS.DMN_NAM, " +
" ERRORS.SERV_NAM, " +
" CODES.MSG_TXT, " +
" ERRORS.SERV_ERR_CNT, " +
" ERRORS.ERR_TS_NUM " +
"ORDER BY " +
" ERRORS.DMN_NAM, " +
" CODES.MSG_TXT "
.addScalar("dmnNam")
.addScalar("msgTxt")
.setResultTransformer( Transformers.aliasToBean(MyDTO.class))
.list();
Make sure YourDTO has a matching constructor, and the types are the exactly like ee.dmn.nam and ece msgTxt.
Instead of group by I'd choose:
SELECT dmnNam, msgTxt
FROM (
SELECT DISTINCT
ERRORS.DMN_NAM AS dmnNam,
ERRORS.SERV_NAM,
CODES.MSG_TXT AS msgTxt,
ERRORS.SERV_ERR_CNT,
ERRORS.ERR_TS_NUM
FROM SERV_ERR ERRORS, EVENT_CD CODES
WHERE ERRORS.SERV_RESP_CD_TXT = CODES.CD_TXT
ORDER BY
dmnNam,
msgTxt
) as DATA

Exception while input a date into a MySQL database

I have a MySQL database and want to write a row into it. The problem is that MySQL do not like my query, why? This is my code:
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
for (Integer articlevalue : articlesendlist) {
for (Integer suppliervalue : suppliersendlist) {
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES (" + maxorder + ", " + articlevalue + ", " + suppliervalue + ", " + date + ", NULL)");
}
}
A small description for my code. The articlesendlist contains IDs from selected values from a JTabel. The same applies to the suppliersendlist. I want to write the IDs into the table "Bestellung". The variable maxorder is the current ID for the table "Bestellung".
If you need it, the exception is:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '12:45:06.164, NULL)' at line 1
Please do not comment/answer with other links, I already searched for the problem and read several sites. They do not help me or are not suitable for my problem.
Thank you for help
Exception is obvious isn't it.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '12:45:06.164, NULL)' at line 1
You are not using quotes around date field.
However you should really avoid executing your SQL queries like this and use PreparedStatemens for this purpose.
PreparedStatemens has specific methods like setDate, setTime, setLong, setString etc and you don't need to worry about putting right quotes in your code.
Try changing this line:
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES (" + maxorder + ", " + articlevalue + ", " + suppliervalue + ", " + date + ", NULL)");
to this:
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES ('" + maxorder + "','" + articlevalue + "','" + suppliervalue + "','" + date + "','NULL')");

Multiselect month from table - sqlite

I get 1-n selected months from a JList.
Now I'd like to select rows from a sqlite DB with the selected months.
Is there a way to do it the easy way to build the select string, e.g. with a loop and a LIKE statement?
resultSet = statement
.executeQuery("SELECT sum(Betrag) FROM record WHERE strftime('%Y',Datum)='"
+ options.getList_years().get(options.getCurrent_year_index())
+ "' AND strftime('%m',Datum) LIKE '"
+ "02 || 04 || 12" //Here are the months,
+ "' AND Sektion LIKE '"
+ "%"
+ "' AND Inhaber LIKE '"
+ list_accounts.getSelectedValue()
+ "' AND Ausgabe='"
+ "true';");
Or has it to look that way?
strftime('%m',Datum)='02' OR strftime('%m',Datum)='04' OR trftime('%m',Datum)='12'
You should use an IN clause:
... AND strftime('%m',Datum) IN ('02', '04', '12')
But you should definitely not use string concatenation to set parameters dynamically in your query. This is the best way to suffer from SQL injection attacks. Use prepared statements, with a ? placeholder for each of your parameter:
SELECT sum(Betrag) FROM record WHERE strftime('%Y',Datum) = ? ...
Learn more about prepared statements in the JDBC tutorial.
You will indeed have to use some loop or utility to build the IN clause. StringUtils from commons-lang is useful here:
"... AND strftime('%m',Datum) IN (" + StringUtils.repeat("?", ", ", months.size())

Categories