Having issues with this the one that needs to be set is a auto increment integer so how would I Specify that
PreparedStatement stmt = conn.prepareStatement("INSERT INTO `"+OnlineUsers.table2+"` VALUES (?,?,?)");
//What I do here
stmt.setInt(2, currentonline);
stmt.setDate(3, new java.sql.Date(b.getTime()));
stmt.execute();
It's best to specify the column names explicitly:
"INSERT INTO `" + OnlineUsers.table2 + "` (col2, col3) VALUES (?,?)"
Then:
stmt.setInt(1, currentonline);
stmt.setDate(2, new java.sql.Date(b.getTime()));
This will make your code robust to the order of the columns changing in the database.
Note: If OnlineUsers.table2 comes from an untrusted source you should validate this string, otherwise you could be at risk of an SQL injection attack.
Related
Can we use OR clause in a PreparedStatement using java?
PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
stmt.setString(1, "'MIKE' || 'ANDY'");
int i = stmt.executeUpdate();
System.out.println(i + " records deleted");
You can simply use two parameters.
PreparedStatement stmt=con.prepareStatement("delete from emp where id=? or id=?");
stmt.setString(1,"ANDY");
stmt.setString(2,"MIKE");
No. This is not raw text substitution and you can’t drop in chunks of the query and expect them to get incorporated in. Each thing substituted for a placeholder gets sanitized, encoded, and quoted as a separate value.
But you can write it with 2 placeholders:
PreparedStatement stmt=con.prepareStatement(
“delete from emp where id in (?, ?)”);
stmt.setString(1,"MIKE”);
stmt.setString(2, “ANDY”);
If you have a lot of values in the IN clause an alternative is to put those values in a table and join to it.
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();
I have raw insert query like
insert into sample(id, name) values(1, 'text \\N\');
Getting SqlException while trying to insert via jdbc but the same insert query is working if I insert via mysql command prompt(console).
jdbc insert query is failing due to special characters("\N") in name field.
so how to overcome and insert the name with \N?
The cleanest approach is to not use a raw SQL query at all. If, as you've stated, you receive the name from some other process then it is presumably in a String variable (or property, or similar) so you can simply use a parameterized query to perform the insert:
// example data
int theId = 1;
String theName = "the name you received from somewhere else";
//
PreparedStatement ps = conn.prepareStatement("INSERT INTO sample (id, name) VALUES (?, ?)");
ps.setInt(1, theId);
ps.setString(2, theName);
ps.executeUpdate();
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
My database contains one column having data type as Integer. I want to delete record using that column value but i'm getting an error.
Here is my code
int id=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter ID to serach"));
//....code
st.executeUpdate("delete from Table where ID='"+id+"'");
I'm getting following error:
Data type mismatch in criteria expression.
you pass a VARCHAR value in your query:
delete from Table where ID='"+id+"'"
just remove the ' and try it again.
I bet your ID is of type NUMBER.
Furthermore I suggest you to use an PreparedStatement to add the Integer value:
delete from Table where ID=?
Otherwise you could have some security problems.
Simple change to :
st.executeUpdate("delete from Table where ID = "+id);
OR
SQLiteDatabase _db = null;
DataBaseHelper _dbHelper = new DataBaseHelper(_context, name, null, 1);
_db = _dbHelper.getWritableDatabase();
_db.delete(TABLE, _ID + "=?", new String[]{id});
So you are inserting integer and not character.Thus no need of single quote around value you are inserting ie int value.It should be
st.executeUpdate("DELETE FROM Table WHERE ID="+id);
It is good practice to have main key words/clauses in Uppercase.And one more, always try to use PreparedStatement rather simple Statement.
EDIT
PreparedStatement Example to insert into database
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();