i want the sequence next value to be inserted into table after concatenating with some string value. eg: case12. Here 'case' will be the string and '12' will be the next sequence value.
i'm trying this code in my jsp page.
String name=request.getParameter("name").toString();
String pwd=request.getParameter("pass").toString();
out.print(name+" and "+pwd);
String add="case";
PreparedStatement ps = connect.prepareStatement("insert into test(caseid,userid,pass) values('CONCAT('"+add+"',test_seq.nextval)',?,?)");
ps.setString(1,name);
ps.setString(2,pwd);
ps.executeUpdate();
connect.commit();
connect.close();
but, i'm getting this error java.sql.SQLException: ORA-00917: missing comma
can anybody tell me the solution for above problem. Any help appreciated.!!
If at all possible, you should prefer passing in parameters to dynamically assembling a SQL statement. So if you don't want "case" to be a hard-coded constant, it ought to be a bind variable.
Additionally, you don't want single-quotes around the CONCAT call. Something like this should work.
String name=request.getParameter("name").toString();
String pwd=request.getParameter("pass").toString();
out.print(name+" and "+pwd);
String add="case";
String sqlStmt = "insert into test(caseid,userid,pass) values(CONCAT(?,test_seq.nextval),?,?)";
PreparedStatement ps = connect.prepareStatement(sqlStmt);
ps.setString(1,add);
ps.setString(2,name);
ps.setString(3,pwd);
ps.executeUpdate();
connect.commit();
connect.close();
Related
I'm trying to update a table in a database through PreparedStatement in ServletClass. It raises java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1). I guess, the problem is car string consists of more words, so it contains whitespaces, but I don't know how exactly solve it. I tried to remove two apostrophe marks surrounding the second question mark in the prepared statement but it didn't help. After removing quotes, there is still the following error:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery()
Here is an extract of code:
private void updateCarAvailability(int value, String car) throws Exception {
Connection conn = null;
PreparedStatement prst = null;
try {
conn = ds.getConnection();
String sql = "update cars set available=? where name='?'";
prst = conn.prepareStatement(sql);
prst.setInt(1, value);
prst.setString(2, car);
prst.executeQuery(sql);
}
The solution is to remove the ' on where name='?', so it should look like update cars set available=? where name=?, and also you should change executeQuery for execute, once you're using an update command.
Remove the single quotes around the ?
String sql = "update cars set available=? where name=?";
They are not needed as the actual value is not passed as part of the SQL statement but as a bind parameter. And bind parameters don't need "SQL formatting".
How can I update my SQL Table column with the value that is stored in a local variable.
In my program I have taken value from the HTML page using the following statement:
String idd=request.getParameter("id");
String report=request.getParameter("rprt");
So now I have to update the value of report in my database table named "ptest" and I am using the following query:
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("update ptest set result = #reprt where patient_id=
#idd");
out.println("Successfully Entered");
But the value is not being stored in the database instead NULL is being stored.
I have already seen this question and got no help.
Question
Please ignore my mistakes if any in this question as I am new to MYSQL.
You can use prepared statements in java.
setString or setInt can set different data types into your prepared statements.
The parameter 1, 2 are basically the positions of the question mark. setString(1,report) means that it would set the string report in the 1st question mark in your query.
Hope this code helps you in achieving what you want.
String query = "update ptest set result = ? where patient_id = ?";
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, report);
preparedStatement.setString(2, idd);
preparedStatement.executeUpdate();
In JDBC, you use ? as placeholders for where you want to inject values into a statement.
So you should do something like this ...
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/tcs","root","root");
PreparedStatement st= con.prepareCall("update ptest set result = ? where patient_id=
?");
///now set the params in order
st.setString(1, report);
st.setString(2, idd);
//then execute
st.executeUpdate();
Doing a string concat with the values is dangerous due to sql injection possibilities, so I typically make statement text static and final, and also if your value has a ' in it that could blow up your sql syntax etc. Also, notice the use of executeUpdate rather than query.
Hope this helps
i searched here to find solution for my error but no one match my problem , So is there anyone help me to find the error in my code !?
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
Object selected = list_1.getSelectedValue();
Connection conn = null;
conn=DriverManager.getConnection("jdbc:mysql://localhost/flyer","root","000");
Statement st= conn.createStatement();
String query = "INSERT INTO flyer_item (discount) SELECT price*? FROM `item` where item_name='?' ";
// PreparedStatement ps = null;
int i = Integer.valueOf((textField_1.getText()));
i=i/100;
java.sql.PreparedStatement ps = conn.prepareStatement(query);
ps.setInt(1,i);
ps.setString(2, selected.toString());
ps.executeUpdate();
st.executeUpdate(query);
} catch (SQLException se){
System.out.println(se.getMessage());
}
} } );
Note : mysql statement it's running successfully in workbench .
thank you
Remove the single quotes around the question mark placeholder
Change this:
where item_name='?'
To this:
where item_name= ?
That should resolve the problem.
With the single quotes, the prepareStatement is seeing the single quotes as enclosing a string literal. The string literal happens to contain a question mark, but it's not seeing that question mark as a bind placeholder.
So the resulting prepared statement only has a single placeholder. Which is why the setString call is encountering an error: there is no second placeholder to supply a value for.
--
EDIT
Also remove this line from the code:
st.executeUpdate(query);
And also remove this line:
Statement st= conn.createStatement();
(The code is creating and using a prepared statement ps.)
remove the quotes from second parameter. within the quotes ? is treated as literal and not as a parameter.
String query = "INSERT INTO flyer_item (discount) SELECT price*? FROM `item` where item_name=?";
type conversion will autonatically handled..
I have a JSON column that I want to create a prepared statement for, but I'm not sure how to go about it since the parameters for the statement are inside a literal string.
For example:
PreparedStatement stmt = myConn.prepareStatement("SELECT JSON_SET(new_friends, '$.?', '[?]') from friend_list where id = ?");
for (int i = 0; i < new_friends.size(); i++) {
String friend = new_friends.get(i);
// not sure what to put here
stmt.set....
stmt.set....
stmt.set(3, i);
}
Anyone have any suggestions?
? placeholders are not used like string interpolation. They replace entire parameters. When the function argument is a string, the entire argument must be the literal string or built with SQL string functions taking parameters as further arguments.
Assuming your syntax is correct for what you want to achieve, consider these:
JSON_SET(new_friends, '$.?', '[?]') -- not valid
JSON_SET(new_friends, ?, ?) -- valid
JSON_SET(new_friends, CONCAT('$.',?), CONCAT('[',?,']')) -- valid
Parameter 1 would be set to the string $.foo for a query in the style of line 2 above, or foo in the style of line 3.
The reason your version isn't valid is exactly the reason you don't/can't use something like WHERE username = '?' but instead would use WHERE username = ? (no quotes around ?).
If you want to add java list objects into a json array like mentioned below:
{"abc":["var1":"val1","var2":"val2","var3":"val3"]}
If there is already a json value in the column then you can use JSON_SET to update value.
String query;
query = "UPADTE tbl1 SET col1 = JSON_SET(col1, '$.abc', CAST(? AS JSON) ) WHERE cdtn = ?";
// if col1 is null then, JSON_SET would be: JSON_SET('{}', '$.abc', CAST(? AS JSON) )
try (Connection conn = DBUtil.getConnection();
PreparedStatement ps = conn.prepareStatement(query)) {
ps.setString(1, jsonArray.toString());
ps.setString(2, cd);
ps.executeUpdate();
}
catch (SQLException e) {
log.error("Error : ", e);
}
I'm trying to insert CLOBs into a database (see related question). I can't quite figure out what's wrong. I have a list of about 85 clobs I want to insert into a table. Even when inserting only the first clob I get ORA-00911: invalid character. I can't figure out how to get the statement out of the PreparedStatement before it executes, so I can't be 100% certain that it's right, but if I got it right, then it should look exactly like this:
insert all
into domo_queries values ('select
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = ''CHQ PeopleSoft FS''')
select * from dual;
Ultimately, this insert all statement would have a lot of into's, which is why I just don't do a regular insert statement. I don't see an invalid character in there, do you? (Oh, and that code above runs fine when I run it in my sql developer tool.) And I if I remove the semi-colon in the PreparedStatement, it throws an ORA-00933: SQL command not properly ended error.
In any case, here's my code for executing the query (and the values of the variables for the example above).
public ResultSet executeQuery(String connection, String query, QueryParameter... params) throws DataException, SQLException {
// query at this point = "insert all
//into domo_queries values (?)
//select * from dual;"
Connection conn = ConnectionPool.getInstance().get(connection);
PreparedStatement pstmt = conn.prepareStatement(query);
for (int i = 1; i <= params.length; i++) {
QueryParameter param = params[i - 1];
switch (param.getType()) { //The type in the example is QueryParameter.CLOB
case QueryParameter.CLOB:
Clob clob = CLOB.createTemporary(conn, false, oracle.sql.CLOB.DURATION_SESSION);
clob.setString(i, "'" + param.getValue() + "'");
//the value of param.getValue() at this point is:
/*
* select
* substr(to_char(max_data),1,4) as year,
* substr(to_char(max_data),5,6) as month,
* max_data
* from dss_fin_user.acq_dashboard_src_load_success
* where source = ''CHQ PeopleSoft FS''
*/
pstmt.setClob(i, clob);
break;
case QueryParameter.STRING:
pstmt.setString(i, "'" + param.getValue() + "'");
break;
}
}
ResultSet rs = pstmt.executeQuery(); //Obviously, this is where the error is thrown
conn.commit();
ConnectionPool.getInstance().release(conn);
return rs;
}
Is there anything I'm just missing big time?
If you use the string literal exactly as you have shown us, the problem is the ; character at the end. You may not include that in the query string in the JDBC calls.
As you are inserting only a single row, a regular INSERT should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):
String query1 = "select substr(to_char(max_data),1,4) as year, " +
"substr(to_char(max_data),5,6) as month, max_data " +
"from dss_fin_user.acq_dashboard_src_load_success " +
"where source = 'CHQ PeopleSoft FS'";
String query2 = ".....";
String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();
reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();
pstmt.executeBatch();
con.commit();
Of the top of my head, can you try to use the 'q' operator for the string literal
something like
insert all
into domo_queries values (q'[select
substr(to_char(max_data),1,4) as year,
substr(to_char(max_data),5,6) as month,
max_data
from dss_fin_user.acq_dashboard_src_load_success
where source = 'CHQ PeopleSoft FS']')
select * from dual;
Note that the single quotes of your predicate are not escaped, and the string sits between q'[...]'.
One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .
Oracle provide some explanation for ORA-00911. You can got this explanation after executing SQL request in Oracle SQL Developer.
ORA-00911. 00000 - "invalid character"
*Cause: identifiers may not start with any ASCII character other than
letters and numbers. $#_ are also allowed after the first
character. Identifiers enclosed by doublequotes may contain
any character other than a doublequote. Alternative quotes
(q'#...#') cannot use spaces, tabs, or carriage returns as
delimiters. For all other contexts, consult the SQL Language
Reference Manual
But in your case it seems to be double ' character