I wonder if there is a way to select table with user input in the following statement:
myStmt = db.myConn.prepareStatement("select * from Rooms where "
+ "idRooms = ?");
myStmt.setInt(1, roomNum);
myRs = myStmt.executeQuery();
Is there a possibility to do something like select * from =? where idRooms = ? to select Rooms with prepared statement upon user input?
myStmt.setString(1, Room);
mysStmt.setInt(2, roomID);
Thanks
It is not possible to add a table name as a parameter.
You can simply create a string containing your constructed query as follows:
String query = "select * from " + userParamVariable + " where idRooms = ?"
I guess you manage your tables with splitting, but unfortunately PreparedStatement does not support it, you can manually replace the table name with String.format() method.
I have a table TotalSales on my database with columns Date(Primary) and Sales. I send query thru my Java Program.
I want to add a row if Date row not exists, and if Date row exists, the value on Sales will be updated. On update, the new value on Sales will be 'current value on Sales' + 'the value of variable totalBill'.
Lets say before execution: row under Sales = 0,
after execution: row under Sales = Sales + totalBill;
I tried this code:
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(date, totalBill)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
st = con.prepareStatement(query);
st.execute();
But doesn't work:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'totalBill' in 'field list'
Can anyone help?
You need to take advantage of the parameterised nature of PreparedStatements and bind the values you want to apply before you execute the statement, something like...
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(?, ?)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+?";
st = con.prepareStatement(query);
st.setDate(1, date);
st.setLong(2, totalBill);
st.setLong(3, totalBill);
for example
Take a look at Using Prepared Statements for more details
You are not appending the variable to your insert query, rather simply using a string. So change this:
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(date, totalBill)
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
to
String query = "INSERT INTO TotalSales (Date, Sales) VALUES(" + date + "," + totalBill + ")
ON DUPLICATE KEY UPDATE Sales= VALUES(Sales)+VALUES(totalBill)";
ADVICE: But for this case, you should learn to use PreparedStatement
I want to use several times the same values.
If I use in dbForge for MySQL next query,
SET #v1 = 123, #v2='2014-04-11', #v3 = 'user1', #v4='title1';
INSERT INTO test_table (TID, CREATED, OWNER, TITLE)
VALUES (#v1,#v2,#v3,#v4)
ON DUPLICATE KEY UPDATE
CREATED=#v2, OWNER=#v3, TITLE=#v4
it correctly executes, but in Java, when I use code
final String dbQuerry = "SET #v1 = %s, #v2='%s', #v3 = '%s', #v4='%s';\n"+
"INSERT INTO test_table (TID, CREATED, OWNER, TITLE)\n" +
"VALUES (#v1,#v2,#v3,#v4)\n" +
"ON DUPLICATE KEY UPDATE\n" +
"CREATED=#v2, OWNER=#v3, TITLE=#v4";
String currentQuerry = String.format(dbQuerry, t.getParam("ID"),
t.getParam("Date"),
t.getParam("User"),
t.getParam("Title"));
mDBStatement.execute(currentQuerry);
I have an exception
SQL Exception: 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 'INSERT INTO test_table (TID, CREATED, OWNER, TITLE) VALUES
(#v1,#v2,#v3,#v4) ON ' at line 2
I can use something like this
final String dbQuerry = "INSERT INTO test_table (TID, CREATED, OWNER, TITLE)\n" +
"VALUES (?,?,?,?)\n" +
"ON DUPLICATE KEY UPDATE\n" +
"CREATED=?, OWNER=?, TITLE=?";
PreparedStatement st = mDBConnection.prepareStatement(dbQuerry);
st.setInt(1, Integer.valueOf(t.getParam("ID")));
st.setString(2, t.getParam("Date"));
st.setString(5, t.getParam("Date"));
st.setString(3, t.getParam("User"));
st.setString(6, t.getParam("User"));
st.setString(4, t.getParam("Title"));
st.setString(7, t.getParam("Title"));
But it looks ugly.
Is there is a way to solve this problem?
One option is to use the special VALUES() function to reference the value that would have been inserted into a column, if the INSERT had succeeded, like this:
...
ON DUPLICATE KEY
UPDATE CREATED = VALUES(CREATED)
, OWNER = VALUES(ONWER)
, TITLE = VALUES(TITLE)
The latter form in your example is preferred, using placeholders for the bind variables. What's ugly is having to supply the same value twice.
I'd recommend something like this:
final String dbQuerry = "INSERT INTO test_table (TID,CREATED,OWNER,TITLE)\n" +
" VALUES (?,?,?, ?)\n" +
" ON DUPLICATE KEY UPDATE\n" +
" CREATED=VALUES(CREATED), OWNER=VALUES(OWNER), TITLE=VALUES(TITLE)";
PreparedStatement st = mDBConnection.prepareStatement(dbQuerry);
st.setInt(1, Integer.valueOf(t.getParam("ID")));
st.setString(2, t.getParam("Date"));
st.setString(3, t.getParam("User"));
st.setString(4, t.getParam("Title"));
And that's not ugly. That's the normative pattern.
Using the special VALUES() function is especially useful if we're upserting more than one row, either with a VALUES clause e.g.
INSERT INTO fee (fi, fo, fum)
VALUES
(1,'doo','dah'),(2,'menom','menah'),(3,'buhdeep','uhdeepee')
ON DUPLICATE KEY
UPDATE fo = VALUES(fo)
, fum = VALUES(fum)
Or, with an INSERT ... SELECT form:
INSERT INTO fee (fi, fo, fum)
SELECT t.ay, t.bee, t.cee FROM sometable t
ON DUPLICATE KEY
UPDATE fo = VALUES(fo)
, fum = VALUES(fum)
BTW... the error being returned from the first form is the type of error we'd expect if allowMultiQueries=true is not included in the connect string. Note that enabling multiple queries per execution effectively disables a security feature.
Consider carefully the SQL text that would be generated and sent to the database with some carefully crafted values:
val = "foo'; DROP TABLE students; --"
Using a prepared statement (with static SQL text with placeholder for bind variables, as in the example above) prevents this mode of SQL injection. And disallowing multiple statements in a single execution is another way to thwart SQL injection attacks.
I believe the # variables are used in stored procedures only...
Either you define a stored procedure or you can use the second option :
final String dbQuerry = "INSERT INTO test_table (TID, CREATED, OWNER, TITLE)\n" +
"VALUES (?,?,?,?)\n" +
"ON DUPLICATE KEY UPDATE\n" +
"CREATED=?, OWNER=?, TITLE=?";
PreparedStatement st = mDBConnection.prepareStatement(dbQuerry);
st.setInt(1, Integer.valueOf(t.getParam("ID")));
st.setString(2, t.getParam("Date"));
st.setString(5, t.getParam("Date"));
st.setString(3, t.getParam("User"));
st.setString(6, t.getParam("User"));
st.setString(4, t.getParam("Title"));
st.setString(7, t.getParam("Title"));
I am inserting into a table from my jdbc program,
like this
PreparedStatement ps = con.prepareStatement(sqlqry);
ps.setInt(1,dto.getInstall_id());
ps.setString(2, dto.getDashboard_name());
ps.setString(3, dto.getDashboard_type());
ps.setString(4, dto.getDashboard_image());
But in the table i have column say D_ID which in is primary key and i dont want o insert the D_ID from my program into table because the same id might be already exist. So for avoiding the PK_CONSTRAINT I am not inseting it.
But when i try this i am getting this error.
ORA-01400: cannot insert NULL into ("TESTDB"."TESTATBLE"."D_ID")
So how can i solve this problem, Any alternative like if i insert D_ID from the program my JDBC program the D_ID column should dynamically generate id's in the table.
I am banging my head for this. Please help!
You should create that ID using a sequence. So for each ID column that you have, you create a corresponding sequence:
create table testatble
(
d_id integer not null primary key,
install_id integer not null,
dashboard_name varchar(100)
... more columns ....
);
create sequence seq_testatble_d_id;
You can use it like this:
// note that there is no placeholder for the D_ID column
// the value is taken directly from the sequence
String sqlqry =
"insert into testatble (d_id, install_id, dashboard_name) " +
"values (seq_testatble_d_id.nextval, ?, ?)";
PreparedStatement ps = con.prepareStatement(sqlqry);
ps.setInt(1,dto.getInstall_id());
ps.setString(2, dto.getDashboard_name());
... more parameters ...
ps.executeUpdate();
That way the id will be generated automatically.
If you need the generated ID in your Java code after the insert, you can use getGeneratedKeys() to return it:
// the second parameter tells the driver
// that you want the generated value for the column D_ID
PreparedStatement ps = con.prepareStatement(sqlqry, new String[]{"D_ID"});
// as before
ps.setInt(1,dto.getInstall_id());
ps.setString(2, dto.getDashboard_name());
... more parameters ...
ps.executeUpdate();
// now retrieve the generated ID
int d_id = -1;
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) // important!
{
d_id = rs.getInt(1);
}
rs.close();
More on sequences in the Oracle manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/pseudocolumns002.htm#SQLRF00253
You should use Auto Increment number for ID(I Oracle you can use sequence). You can do this at the link:
Create ID with auto increment on oracle
You should also read this. If there is a sequence to your ID then here you can read information about that.
It is well known that how to set the field value to null by a simple query like -
UPDATE your_table
SET your_column = NULL
WHERE id = 1;
But pro-grammatically, which one is correct way to update the field value to null -
db.execSQL("UPDATE your_table SET your_column='" + null + "WHERE id='" + myid + "'");
OR
db.execSQL("UPDATE your_table SET your_column= NULL WHERE id='" + myid + "'");
Thanks
I would go with PreparedStatement.
String query="UPDATE your_table SET your_column= ? WHERE id=?");
PreparedStatement stmnt = conn.prepareStatement(query);
if(colyouAretryingtopass == null){]
stmnt.setNull(1, Types.VARCHAR);
}
The correct way is to use bind variables, depending on the framework you are using this is done in different ways.
You query should be something like follows;
String query = "UPDATE your_table SET your_column = null WHERE id = ?";
executeQuery(query, id);
Where executeQuery(String query, Object... args) is the the DB access method of your choice.
If you don't use bind variables you are;
a) Vunerable to SQL injection.
b) Losing performance by not utilising query cache on the database.