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'.
Related
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();
This question already has an answer here:
Is it possible to supply parameters for table or column name in Prepared Statements or QueryRunner.update()?
(1 answer)
Closed 7 years ago.
Are there anyway to parametrize the table in a PreparedStatement?
select * from ? where id=?
If not, what is the best approach to do that or, are there any other way to do it without loosing the advantages of a PreparedStatement?
Thanks.
The short answer is that you cannot parameterize a tablename in a prepared statement. You have to contruct the sql with string concatenation. Basically prepared statements are used for column values and not for the table names.
The best I can think of is to use string.format like this:
String sql = String.format("select * from $1%s", yourtable);
We could do in the following way
"select * from "+table_name+" where id=?";
PreparedStatement allow you to provide dynamic query parameters in where clause only
Use placeholder in place of table name and then replacing that with your tablename.
String strQuery = "INSERT INTO $tableName (col1, col2)
VALUES (?,?);";
and replace when you come to know the tablename as below:
String query =strQuery.replace("$tableName",tableName);
stmt =connection.prepareStatement(query);
String table_name= // get tablename
String sql= "select * from" +table_name+" where id=?";
If you have your PreparedStatement with an SQL query as you stated you can do:
int yourID = 1;
String tablename = "table";
String query = "SELECT * FROM " + tableName + " where id = ?";´
PreparedStatement statement = con.prepareStatement(query);
statement.setInt(1, yourID);
It will replace the ? with 1. If you have multiple ? you can set those like
statement.setString(2, "YourString");
Check
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html for more Information.
Is is possible to get the id from a MySQL table and "save" it into a variable on JDBC?
In my program, I have a JTextfield in which the user gives a ticket which will be stored on a MySQL DB. Everytime he gives a ticket, I want to get the id from my db where the ticket was inserted and not print in on teminal, but resolve it into a variable and use it on other classes also. I need it for other classes.
Is is possible?
Something like this ?
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
long generatedId= 0L;
if (generatedKeys.next()) {
generatedId = generatedKeys.getLong(1);// here is your generated Id ,
}
Something like that?
PreparedStatement st;
st = con.prepareStatement("SQL STATAMENT", "HERE COLUMN NAME FROM TABLE") VALUES(?)",Statement.RETURN_GENERATED_KEYS);
st.setString(1,"Binded String Veriable");
st.executeUpdate();
ResultSet rs = st.executeQuery("select last_insert_id() as id from "HERE TABLE NAME"");
if(rs.next()){
int lastId = Integer.parseInt(rs.getString("id"));
Use PrpearedStatment to prevent SQL Injection for example:
st = con.prepareStatement("INSERT INTO component(user) VALUES(?)", Statement.RETURN_GENERATED_KEYS )
st.setString(1,username)
Here you have how last_insert_id() works: JDBC LAST INSER ID AND OTHER
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...