Insert,Update,Retrive using stored procedures or functions in mysql - java

Check whether the primary key exists in the table.
If exists retrieve three column values and update the three column values with new values.
String sql = "SELECT brno, brdate, type1,type,flag,mcode,pamount,tax,pamount1,liab FROM rawdata WHERE mcode="+mcode;
ResultSet rs = statement.executeQuery(sql);
rs.first();
float oldPamount= rs.getFloat("pamount");
float tax= rs.getFloat("tax");
float oldPamount1= rs.getFloat("pamount1");
float newPamount= pamount;
float newTax= tax;
float newPamount1= pamount1;
rs.updateFloat("pamount", newPamount);
rs.updateFloat("tax", newTax);
rs.updateFloat("pamount1", newPamount1);
rs.updateRow();
If not exists insert the record and retrieve it.
I have tried this:
INSERT INTO rawdata (brno, brdate, type1,type,flag,mcode,pamount,tax,pamount1,liab)
SELECT * FROM (SELECT '1', '02.05.15', 'G','H','E','2222','789.00','0.00','789.00','L') AS tmp
WHERE NOT EXISTS (
SELECT mcode FROM rawdata WHERE mcode = '2222'
);
But it getting the following error duplicate value 789.00
I need to done these things at a time not separate queries.
This is my table(rawdata) with fields(brno, brdate, type1,type,flag,mcode,pamount,tax,pamount1,liab) where mcode is the primarykey
Here the pamount,tax,pamount1 need to be updated if the record exists.
For Ex:
These are the sample values 873.00,0.00,873.00 needed to be updated to 789.00,0.00,789.00 (or) 24000.00,240.00,23760.00
Other wise need to insert entire row for the new mcode
I have tried the above queries, but i need to be done at time.

Related

Java dynamically generate SQL query - ATHENA

I am trying to generate sql query based on user input. There are 4 search fields on the UI:
FIRST_NAME, LAST_NAME, SUBJECT, MARKS
Based on user input I am planning to generate SQL query. Input can be of any combination.
eg: select * from TABLE where FIRST_NAME="some_value";
This query needs to be generated when FIRST_NAME is given and other fields are null
select * from TABLE where FIRST_NAME="some_value" and LAST_NAME="some_value";
This query needs to be generated when FIRST_NAME and LAST_NAME are given and other fields are null
Since there are 4 input fields, number of possible queries that can be generated are 24 (factorial of 4).
One idea is to write if condition for all 24 cases.
Java pseudo code:
String QUERY = "select * from TABLE where ";
if (FIRST_NAME!=null) {
QUERY = QUERY + "FIRST_NAME='use_input_value';"
}
if (LAST_NAME!=null) {
QUERY = QUERY + "LAST_NAME='use_input_value';"
}
if (SUBJECT!=null) {
QUERY = QUERY + "SUBJECT='use_input_value';"
}
if (MARKS!=null) {
QUERY = QUERY + "MARKS='use_input_value';"
}
I am not able to figure out how to generate SQL queries with AND coditions for multiple Input values.
I have been through concepts on dynamically generate sql query but couldn't process further.
Can someone help me on this.
FYI: I have been through How to dynamically generate SQL query based on user's selections?, still not able to generate query string based on user input.
Let's think about what would happen if you just ran the code you wrote and both FIRST_NAME and LAST_NAME are provided. You'll wind up with this:
select * from TABLE where FIRST_NAME='use_input_value';LAST_NAME='use_input_value';
There are two problems here:
The query is syntactically incorrect.
It contains the literals 'use_input_value' instead of the values you want.
To fix the first problem, let's first add and to the start of each expression, and remove the semicolons, something like this:
String QUERY = "select * from TABLE where";
if (FIRST_NAME!=null) {
QUERY = QUERY + " and FIRST_NAME='use_input_value'";
}
Notice the space before the and. We can also remove the space after where.
Now the query with both FIRST_NAME and LAST_NAME will look like this:
select * from TABLE where and FIRST_NAME='use_input_value' and LAST_NAME='use_input_value'
Better but now there's an extra and. We can fix that by adding a dummy always-true condition at the start of the query:
String QUERY = "select * from TABLE where 1=1";
Then we append a semicolon after all the conditions have been evaluated, and we have a valid query:
select * from TABLE where 1=1 and FIRST_NAME='use_input_value' and LAST_NAME='use_input_value';
(It may not be necessary to append the semicolon. Most databases don't require semicolons at the end of a single query like this.)
On to the string literals. You should add a placeholder instead, and simultaneously add the value you want to use to a List.
String QUERY = "select * from TABLE where";
List<String> args = new ArrayList<>();
if (FIRST_NAME!=null) {
QUERY = QUERY + " and FIRST_NAME=?";
args.add(FIRST_NAME);
}
After you've handled all the conditions you'll have a string with N '?' placeholders and a List with N values. At that point just prepare a query from the SQL string and add the placeholders.
PreparedStatement statement = conn.prepareStatement(QUERY);
for (int i = 0; i < args.size(); i++) {
statement.setString(i + 1, args[i]);
}
For some reason columns and parameters are indexed starting at 1 in the JDBC API, so we have to add 1 to i to produce the parameter index.
Then execute the PreparedStatement.

Retrieving Data from multiple tables from Database

I have some tables in a database. They have some particular pattern. For example, consider I have table employee, then some other table with same pattern like:
table 1:employee
table 2:employee_X
table 3:employee_Y
I want to check if these tables contain data or not and if they do then I have to call some method for each table. I am using following code to retrieve.
DatabaseMetaData meta = con.getMetaData();
ResultSet res = meta.getTables(null, null, "My_Table_Name", new String[] {"TABLE"});
while (res.next()) {
if(rs.getStrin(3).equals(employee)){
//my code to write data of this table to a file
}
if(rs.getString(3).equals(employee_X)){
//my code to write data to the same file
}
if(rs.getString(3).equals(employee_Y)){
//code to write data to the same file from this table
}
}
The code is working fine, but how I can retrieve data from all these tables at once instead of using three checks. If any of these table contains data I want to write it to my file. How I can perform this operation in less lines of code and efficiently?
It would be great if anyone can suggest way to check each of these table either contain data or not in a single statement and then I can call my code to write data to file.
You can use UNION statement in your complex query. Please, check example:
SELECT id, name FROM employee WHERE id = ?
UNION
SELECT id, name FROM employee_x WHERE id = ?
UNION
...
Also you can use UNION ALL statement instead of UNION. The main difference that UNION returns unique result set without duplicates, UNION ALL allows duplicates. Please, check this link https://www.w3schools.com/sql/sql_union.asp for detailed explanation about union statement.
If you need create UNION query with custom filtered tables, please check example:
Set<String> requiredTables = new HashSet<>();
// fill set with required tables for result query
requiredTables.add("employee");
ResultSet res = meta.getTables(null, null, "My_Table_Name",
new String[] {"TABLE"});
List<String> existentTables = new LinkedList<>();
while(res.next()) {
if (requiredTables.contains(res.getString(3)) {
existentTables.add(res.getString(3));
}
}
String query = existentTables.stream().map(table -> String.format("SELECT * FROM %s", table)).collect(Collectors.joinning(" UNION "));

Codename One SQL database storing wrong values

I am used to developing desktop applications with Java. Now I am trying Codename One to develop my first mobile app.
Trying to replicate my experiences with SQL databases I am running into a very odd storage behavior, which I cannot explain.
The database is created, but when I change the table input value, the new value gets ignored and just the old value is added. To save the new value, I have to delete the database.
I like the interface and any kind help would be appreciated.
Database db = Display.getInstance().openOrCreate("MyDB.db");
db.execute("CREATE TABLE IF NOT EXISTS Persons (Date NOT NULL,Event NOT NULL)");
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'John', '10000.00' );";
db.execute (sql);
// adds "John" to the database every time I click the button
// then I change the from "John" to "James"
// I am not adding the lines twice, just change the input
String sql = "INSERT INTO Persons (DATE , Event) " + "VALUES ( 'James', '10000.00' );";
db.execute (sql);
//keeps adding "John" to the database, even though value has been changed to "James"
Cursor cur = db.executeQuery("select * from Persons;");
Row currentRow= cur.getRow();
String dataText = currentRow.getString(0);
while (cur.next()) {
System.out.println(dataText);
}
You're not fetching the next row into dataText in your while() loop, so you're just repeatedly printing out the text from the first row.
It should be:
Cursor cur = db.executeQuery("select * from Persons;");
while (cur.next()) {
Row currentRow = cur.getRow();
String dataText = currentRow.getString("Date");
System.out.println(dataText);
}
If you examine the table with a separate query tool, like PhpMyAdmin, you should see that it contains both rows.
I hope I got the syntax right. I'm not a Java programmer and I got it from a tutorial.

Get inserted row to Oracle with java

I am building a java program to insert data to my oracle database.
My problem is that I need to insert into two tables, and to reach unique rows I use in TABLE_A triggers for id before insert get next val in a sequence.
But i need the same id for the TABLE_B for connection.
( i cant get getval because what if another user uses the program... )
So I need to reach somehow that when I use executeql(sql) command in return I see what I have submit.
Now I use that I have name and date, so I select the id where name and date is the just inserted.
But its not the best because in one day I can insert more names. So now this will not unique.
like :
insert into table a ( name,date) val ( 'Ryan','2014.01.01')
id here is autoincremented by sequence
than another sql run:
inert into table_b ( id,someval) val ( select id from table_a where
name ='Ryan', date='2014.01.01, 23)
so i need something like:
system.out.println(smtp.executesql(sql).whatIinsertednow())
*than console:* '1 row insered (id,name,date) : ( 1, Ryan, 2014.01.01)
PreparedStatement prepareStatement = connection.prepareStatement("insert...",
new String[] { "your_primary_key_column_name" });
prepareStatement.executeUpdate();
ResultSet generatedKeys = prepareStatement.getGeneratedKeys();
if (null != generatedKeys && generatedKeys.next()) {
Long primaryKey = generatedKeys.getLong(1);
}
I have found the answer this is perfectly works. I can insert from JAVA and its return with the key.
Full version:
CREATE TABLE STUDENTS
(
STUDENT_ID NUMBER NOT NULL PRIMARY KEY,
NAME VARCHAR2 (50 BYTE),
EMAIL VARCHAR2 (50 BYTE),
BIRTH_DATE DATE
);
CREATE SEQUENCE STUDENT_SEQ
START WITH 0
MAXVALUE 9999999999999999999999999999
MINVALUE 0;
And the Java code
String QUERY = "INSERT INTO students "+
" VALUES (student_seq.NEXTVAL,"+
" 'Harry', 'harry#hogwarts.edu', '31-July-1980')";
// load oracle driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// get database connection from connection string
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:sample", "scott", "tiger");
// prepare statement to execute insert query
// note the 2nd argument passed to prepareStatement() method
// pass name of primary key column, in this case student_id is
// generated from sequence
PreparedStatement ps = connection.prepareStatement(QUERY,
new String[] { "student_id" });
// local variable to hold auto generated student id
Long studentId = null;
// execute the insert statement, if success get the primary key value
if (ps.executeUpdate() > 0) {
// getGeneratedKeys() returns result set of keys that were auto
// generated
// in our case student_id column
ResultSet generatedKeys = ps.getGeneratedKeys();
// if resultset has data, get the primary key value
// of last inserted record
if (null != generatedKeys && generatedKeys.next()) {
// voila! we got student id which was generated from sequence
studentId = generatedKeys.getLong(1);
}
}
source : http://viralpatel.net/blogs/oracle-java-jdbc-get-primary-key-insert-sql/
You can accomplish that by using the RETURNING clause in your INSERT statement:
INSERT INTO table_a ( name,date) val ( 'Ryan','2014.01.01') RETURNING id INTO ?

ORA-00913: too many values

getting ORA-00913: too many values. don't know how to resolve this issue please anyone could help me?
con2 = DriverManager.getConnection("Jdbc:Oracle:thin:#localhost:1521:XE", "system",
"oracle123");
File image=new File("E:/Users/ganesh/Desktop/line.jpg");
String sql="insert into blobtab values(?,?)";
pstmt=con2.prepareStatement(sql);
pstmt.setString(1,"akshita");
fis=new FileInputStream(image);
pstmt.setBinaryStream(2,(InputStream)fis,(int)(image.length()));
int s = pstmt.executeUpdate();
if (s > 0) {
System.out.println("Image Uploaded successfully !");
} else {
System.out.println("unsucessfull to upload image.");
}
con2.close();
pstmt.close();
This would suggest that your blobtab table didn't have two columns in it (or if there's a trigger on the table, check the DML being fired recursively in those for the same problem).
insert into blobtab values(?,?)
eg:
SQL> create table foo(id number);
Table created.
SQL> insert into foo values (1, 2);
insert into foo values (1, 2)
*
ERROR at line 1:
ORA-00913: too many values
check your table. also you should always put explicit column names on your insert (in case someone adds default or nullable columns later on. i.e. always do:
insert into blobtab (col1, col2) values(?,?)
where col1 col2 are your real column names.
the number of column would have been less than the paraemeter/argument passed
eg: insert into insert into foo(name , age) values (?,?,?) and then preparedStatment object insert
Since there is 2 column and value have 3 parameter
therefore ,
ORA-00913: too many values

Categories