I want to use a SELECT subquery into a INSERT query as PreparedStatement...
I am trying to fill 2 columns with custom value and the 3rd one with subquery...
query = "insert into invoiceOrders (productCode,quantity,amount) values (?,?,select price from priceTable where proCode=pCode)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(0,"productCode");
stmt.setString(1,"qty");
/*3rd column will be filled be subquery*/
n = stmt.executeUpdate();
The subquery:
select price from priceTable where proCode=pCode
must be enclosed in parentheses and make sure that it returns only 1 row.
Also what is the parameter pCode?
I think that you should replace it with ? and pass later its value with setString().
Also the setString() method's 1st argument is 1 based.
So change to this:
query = "insert into invoiceOrders (productCode,quantity,amount) values (?,?,(select price from priceTable where proCode=?))";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1,"productCode");
stmt.setString(2,"qty");
stmt.setString(3,pCode); // or stmt.setInt(3,pCode);
n = stmt.executeUpdate();
Related
I'm trying to insert a sublevel to a table from form like in the picture but why can't I use where?
String sql = "insert into BE_Tracker(sub_item) values(?) where id="+id+" ";
PreparedStatement st = con.prepareStatement(sql);
st.setString(2,addsubItem);
you cannot use where in insert into query in this way.
You can use it like, something like that
insert into MyTable1 select id,name from MyTable2 where id >5
It sounds like you really wanted an UPDATE here:
String sql = "UPDATE BE_Tracker SET sub_item = ? WHERE id = ?";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1, addsubItem);
st.setString(2, id);
st.executeUpdate();
INSERT (...) VALUES (...) query cannot use with finding option WHERE ... = ....
Insert row on table BE_Tracker.
Find rows in table BE_Tracker with 'WHERE' option with 'SELECT', 'UPDATE' or 'DELETE'.
This query:
SELECT
r.report_id,
r.user_id,
u.user_name,
u.user_mail,
d.department_name,
r.report_comment,
r.report_target_date,
r.report_create_date,
r.report_revised_date,
r.report_root_id,
report_revised_id
FROM
report r
JOIN
user u ON u.user_id = r.user_id
JOIN
department d ON u.department_id = d.department_id
JOIN
authority a ON r.user_id = a.user_src_id
AND a.user_dest_id = 131
WHERE
r.report_target_date BETWEEN '2014-07-23 23:59:00' AND '2014-08-22 00:00:00'
AND r.report_comment LIKE '%事務%'
In mysql workbench this query has return value but when using it in java it's not returning anything:
Statement stmt = connection.createStatement();
ResultSet rs = null;
rs = stmt.executeQuery(query);
In mysql workbench this query has return value but rs return is empty.
You pass Japanese characters into the query. This could easily be a character encoding issue.
Use a PreparedStatement and insert the value through a setString() call which will properly take care of the encoding.
Modify your query to have a parameter (marked by a question mark):
...
WHERE
r.report_target_date BETWEEN '2014-07-23 23:59:00' AND '2014-08-22 00:00:00'
AND r.report_comment LIKE ?
And the Java code:
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, "%事務%"); // Parameter index is 1-based
ResultSet rs = ps.executeQuery();
I have 2 tables in my application:
1.newuser
2.introducer_table
Newuser1 table contains *sid**(primary key,auto-generated field)****, fathername,gender,datebirth,occupation,addharnumber as columns
1.I’m inserting values into the newuser table using java prepared statement like below:
PreparedStatement pst = con.prepareStatement("insert into newuser1 (name,fathername,gender,datebirth,occupation,aadharNumber) values(?,?,?,?,?,?)");
//pst.setString(1,NULL);
pst.setString(1,”xyz”);
pst.setString(2,"ram");
pst.setString(3,"male");
pst.setString(4,"oct25");
pst.setString(5,"emps");
pst.setString(6,"4564");
data is inserted successfully,but I want the sid value of newuser1 in my introducer_table so I write the query like this in prepared statement to select the last insert id.
My introducer_table contains the columns:
**sid(foreign key),name,accountno,sign**
PreparedStatement pst = con.prepareStatement("insert into introducer_table(sid,name,accountno,sign) values((SELECT LAST_INSERT_ID() from dual),?,?,?)");
//nomine details into data base
//pst.setString(1,NULL);
pst.setString(1,"ram");
pst.setString(2,"8945");
pst.setString(3,"ssss");
When I execute this,Im getting ‘0’ value in the sid column of introducer_table.I make sid column as not null while creating intoducer_table,even im getting the ‘zero’ value like this:
Introducer_table:
**Sid** name accountno sign
**0** ram 8945 ssss
Please help me I was stucked by this problem from so many days.
Rather than doing it your way think about using
con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
and then after your insert
pst.executeUpdate();
ResultSet rs = prest.getGeneratedKeys();
int last_inserted_id = -1;
if(rs.next())
{
last_inserted_id = rs.getInt(1);
}
Example query:
SELECT country
FROM data
WHERE city LIKE
(SELECT LEFT ('jakartada',7));
Example in JDBC:
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('?',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
Why this doesn't work properly?
There is no parameter within the prepared statement, however the code attempts to set a parameter. Try adding a parameter to the statement.
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT (?,7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
Or try removing the statement setting the parameter:
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('jakartada',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
I believe you're making this harder than it needs to be, and at the same time you're missing something. Is this what you're trying to do?
SELECT country FROM data WHERE city LIKE 'jakarta%'
That is, are you looking for the country column from every row where the city name starts with 'jakarta'? If so, don't forget the % sign. If you don't include the % sign, then
SELECT country FROM data WHERE city LIKE 'jakarta'
and
SELECT country FROM data WHERE city = 'jakarta'
mean exactly the same thing as each other, and the LIKE operator is pointless; you may as well use the = operator.
So, it seems to me the MySQL query you want is
SELECT country FROM data WHERE city LIKE CONCAT(LEFT('jakartada',7),'%')
to add the % sign. You don't need the subselect in this case.
Like you pointed out, the Java code you need then is:
String sql = "SELECT country FROM data " .
"WHERE city LIKE CONCAT(LEFT(?,7),'%')";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
... process the rs records ...
rs.close(); /* please don't forget to close your result sets */
use this link for your solution and this query
http://sqlfiddle.com/#!2/c79ab/10
SELECT country FROM data
WHERE city LIKE CONCAT(LEFT('jakartada',7),'%')
Don't you quotes in your prepared statement when setting values at runtime... Otherwise it will take it as input only not for ps position... Remove single quotes from your question mark...
I am using oracle sequence for inserting log id into tableA as follows,
String SQL_PREP_INSERT = "INSERT INTO tableA (LOG_ID,USER_ID,EXEC_TIME) VALUES"
+ " (logid_seq.nextval, ?, ?)";
Then getting the recently inserted value,
String SQL_PREP_SEL = "SELECT max(LOG_ID) FROM tableA ";
stmt = con.prepareStatement(SQL_PREP_SEL);
stmt.execute();
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
logid = rs.getInt(1);
}
And inserting it into tableB,
String SQL_PREP_INSERT_DETAIL = "INSERT INTO tableB (LOG_ID, RESPONSE_CODE, RESPONSE_MSG) VALUES"
+ " (?, ?)";
stmt = con.prepareStatement(SQL_PREP_INSERT_DETAIL);
stmt.setInt(1, logid);
stmt.setString(2, respCode);
stmt.setString(3, respMsg);
stmt.execute();
Is there a way to generate sequence in Java instead of Oracle and insert into both tables at once, instead of selecting from tableA and inserting into tableB?
In general, selecting the MAX(log_id) is not going to give you the same value that logid_seq.nextval provided. Assuming that this is a multi-user system, some other user could have inserted another row with a larger log_id value than the row you just inserted before your query is executed.
Assuming that both INSERT statements are run in the same session, the simplest option is probably to use the logid_seq.currval in the second INSERT statement. currval will return the last value of the sequence that was returned to the current session so it will always return the same value that was generated by the nextval call in the first statement.
INSERT INTO tableB (LOG_ID, RESPONSE_CODE, RESPONSE_MSG)
VALUES( logid_seq.currval, ?, ? )
Alternatively, you could use the RETURNING clause in your first statement to fetch the sequence value into a local variable and use that in the second INSERT statement. But that is probably more work than simply using the currval.
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);
}
}