How to use PreparedStatement and Case INsensitive search - java

1.How do I use PrepareStatement for familyname and givenname?
2.Also, how do I case insensitive search by familyname or givenname?
String query ="SELECT agent.familyname, agent.givenname" +
" FROM agent" +
" WHERE agent.agentid = piececreation.agentid" +
" AND (LOWER(familyname) = '"+agent_lastname+"' OR LOWER(givenname) = '"+agent_name+"') ORDER by familyname";
PreparedStatement pst = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pst.setString(1, agent_lastname);
pst.setString(2, agent_name);
// Executing the insert
pst.executeUpdate();

Make familyName or givenName to lowercase too since you are already using LOWER DB API
String query ="SELECT agent.familyname, agent.givenname" +
" FROM agent" +
" WHERE agent.agentid = piececreation.agentid" +
" AND (LOWER(familyname) = '"+agent_lastname.toLowerCase()+"' OR LOWER(givenname) = '"+agent_name.toLowerCase()+"') ORDER by familyname";
When you are using PreparedStatement dont append values directly in your SQL, if you do that you are prone to SQL Attack instead parametrize your values.
String query =
"SELECT agent.familyname, agent.givenname"
+ " FROM agent"
+ " WHERE agent.agentid = ?"
+ " AND ("
+ " LOWER(familyname) = ? OR LOWER(givenname) = ?"
+ ") "
+ " ORDER by familyname";
pst.setInt(1, piececreation.agentid);
pst.setString(2, agent_lastname.toLowerCase());
pst.setString(3, agent_name.toLowerCase());
Then set values calling appropriate setXXX methods as defined here.
You can read tutorial here

You can use the following query for caseinsensetive search.
String query =
"SELECT agent.familyname, agent.givenname"
+ " FROM agent"
+ " WHERE agent.agentid = ?"
+ " AND ("
+ " familyname ilike ? OR givenname ilike ?"
+ ") "
+ " ORDER by familyname";
pst.setInt(1, piececreation.agentid);
pst.setString(2, agent_lastname.toLowerCase());
pst.setString(3, agent_name.toLowerCase());

Related

SQL query sees the value as a column name

I am trying to make a connection to a database and then run an INSERT INTO query, but when the code runs, i get the error: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'BLUE'.
As you can see in my code below, i give "BLUE" as an value instead of an column name. Does anyone knows what i am doing wrong? p.s. color is an Enum, all the other values are doubles.
String query = "INSERT INTO [oval] " +
"(anchorX, anchorY, width, height, weight, color) VALUES " +
"(" + drawingItem.getAnchor().getX() +
", " + drawingItem.getAnchor().getY() +
", " + drawingItem.getWidth() +
", " + drawingItem.getHeight() +
", " + ((Oval) drawingItem).getWeight() +
", " + drawingItem.getColor().toString() + ")";
initConnection();
Statement myStmt = con.createStatement();
rowsAffected = myStmt.executeUpdate(query);
closeConnection();
EDIT ANSWER:
String query = "INSERT INTO [oval] VALUES (?,?,?,?,?,?)";
initConnection();
PreparedStatement myPrepStmt = con.prepareStatement(query);
myPrepStmt.setDouble(1, drawingItem.getAnchor().getX());
myPrepStmt.setDouble(2, drawingItem.getAnchor().getY());
myPrepStmt.setDouble(3, drawingItem.getWidth());
myPrepStmt.setDouble(4, drawingItem.getHeight());
myPrepStmt.setDouble(5, ((Oval)drawingItem).getWeight());
myPrepStmt.setString(6, drawingItem.getColor().toString());
rowsAffected = myPrepStmt.executeUpdate();
closeConnection();
As suggested, use parametrized query to prevent SQL injection. As for the problem in hand, you must use single quote to each string values.
Ex:
"('" + drawingItem.getAnchor().getX() +
"', '" +
Correct way would be:
String query = "INSERT INTO [oval] " +
"(anchorX, anchorY, width, height, weight, color) VALUES " +
"(?, ?, ?, ?, ?, ?)";
initConnection();
int i = 1;
Statement myStmt = con.prepareStatement(query);
myStmt.setInt(i++, drawingItem.getAnchor().getX());
myStmt.setInt(i++, drawingItem.getAnchor().getY());
myStmt.setString(i++, drawingItem.getWidth());
myStmt.setString(i++, drawingItem.getHeight());
myStmt.setFloat(i++, ((Oval) drawingItem).getWeight());
myStmt.setString(i++, drawingItem.getColor().toString());
rowsAffected = myStmt.executeUpdate();

can't get parameter with a value of integer in SQL query

I'm trying to get the integer(age information) in my SQL query using this method
// ...
Integer age = 42;
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "',age,'" + email + "')";
try {
PreparedStatement preparedStatement = con.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
try {
i = stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
finally i got the result of successfully inserting all the information, username, passcode, gender and email, but for the AGE info, it just shows NULL in my mysql database table, and i have tried so hard to fix this but still got confused, please help me out, thx:)
Correct your code first to and then try.
gender + "'," + age + ",'" + email
Secondly you are not using PreparedStatement in right manner. In PreparedStatement you set the dynamic values and do concatenate the SQL like this. Check this https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
You got an error in you sql query
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "',age,'" + email + "')";
This will not insert the age value, so age will be set to his default value (NULL)
Try with this query
String sql = "insert into user_info value('" + username + "','" + passcode + "','" + gender + "','" + age + "','" + email + "')";

Unknown SQL Issue with INSERT sentence

Basically I'm trying to update a Database table with the values of a getSelectRow. As you can see, the query finds the correct data, but has huge issues when actually trying to add it to the database.
The error is in the SQL syntax, but I don't know where I'm going wrong. Please Help.
This is the query that it executes, but I have no idea why it isn't updating the table.
INSERT INTO customerdetails
FName = 'Tim'
AND SName = 'Cooley'
AND Address = '52 Buckminster Drive Dorridge Solihull West Mids'
AND Postcode = 'B93 8PG'
Java code:
private void sendBtnMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
int insertRow = newOrderTbl.getSelectedRow();
int col2 = 0;
String sql3 = "INSERT INTO customerdetails VALUES "
+ "FName = '" + newOrderTbl.getValueAt(insertRow, col2) +"'"
+ "AND SName = '" + newOrderTbl.getValueAt(insertRow, col2+1) +"'"
+ "AND Address = '" + newOrderTbl.getValueAt(insertRow, col2+2) +"'"
+ "AND Postcode = '" + newOrderTbl.getValueAt(insertRow, col2+3) +"'";
System.out.println(sql3);
try{
pst = conn.prepareStatement(sql3);
pst.executeUpdate(sql3);
JOptionPane.showMessageDialog(null, "Deleted");
CustomerTable();
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
To begin with, your SQL syntax is wrong (at least that it is a non-standard SQL syntax for your database engine). Second, your code is vulnerable to SQL Injection attack.
In order to solve both problems, you should use a PreparedStatement (that you're doing in the wrong way). A basic example from your code:
String sql = "INSERT INTO customerdetails (FName, SName, Address, Postcode) VALUES (?, ?, ?,?)";
PreparedStatement pst = conn.prepareStatemtnt(sql);
pst.setString(1, newOrderTbl.getValueAt(insertRow, col2));
pst.setString(2, newOrderTbl.getValueAt(insertRow, col2+1));
pst.setString(3, newOrderTbl.getValueAt(insertRow, col2+2));
pst.setString(4, newOrderTbl.getValueAt(insertRow, col2+3));
pst.executeUpdate();
//rest of code...
Assuming your SQL syntax will work, then you should pass the values as parameters, similar to the previous example:
String sql3 = "INSERT INTO customerdetails VALUES "
+ "FName = ?"
+ "AND SName = ?"
+ "AND Address = ?"
+ "AND Postcode = ?"
pst = conn.prepareStatement(sql3);
pst.setString(1, newOrderTbl.getValueAt(insertRow, col2));
pst.setString(2, newOrderTbl.getValueAt(insertRow, col2+1));
pst.setString(3, newOrderTbl.getValueAt(insertRow, col2+2));
pst.setString(4, newOrderTbl.getValueAt(insertRow, col2+3));
pst.executeUpdate();
//rest of code...
for update statement it will be -
String sql3 = "INSERT INTO customerdetails(FName,SName,Address,Postcode) VALUES "
+ " '" + newOrderTbl.getValueAt(insertRow, col2) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+1) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+2) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+3) + "')";
Also you should use PreparedStatement for this.
Thanks
Please change it to
String sql3 = "INSERT INTO customerdetails(FName,SName,Address,Postcode) VALUES ("
+ "'" + newOrderTbl.getValueAt(insertRow, col2) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+1) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+2) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+3) +"')";
The generated insert statement in your code seems invalid. Please see SQL Insert Statement for more information
Also, the better approach would be to create a dedicated Serverside DAO class to handle database operations.

select statement giving error for string variable

I am writing the following SQL query in my Java program
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from "
+ "student where ID =" + ID + " or FirstName=" + firstName + ";");
However, I am getting the following error:
use the right syntax for FirstName="+Parker
How is this caused and how can I solve it?
You should take advantage of prepared statements by making use of prepared statements parameters. This way, you can set your parameters pragmatically using setters.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
Here is a snippet from the Oracle docs:
PreparedStatement updateSales = null;
String updateString = "update " + dbName + ".COFFEES " + "set SALES =
? where COF_NAME = ?";
updateSales = con.prepareStatement(updateString);
updateSales.**setInt**(1, e.getValue().intValue());
updateSales.**setString**(2, e.getKey());
Just make sure you set the statements *in order a*s the sql query.
Use a PreparedStatement like this:
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from student where ID = ? or FirstName = ?");
pre.setInt(1, ID);
pre.setString(2, firstName);
I haven't used sql in Java, but my guess is it is because you don't have single quotes around first name. You want:
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from " + "student where ID =" + ID + " or FirstName='" + firstName + "';");
emphasis:
... FirstName='" + firstName + "';");

Update statement syntax error

I have the following string which holds the query I want to execute:
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " set bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
I get an Update statement syntax error but I dont see where is the error. Any help is appreciated.
columns "descripcion" and "bodega" are text type columns.
Well it's probably because you've got multiple set parts instead of using comma separation, and potentially because you don't have quotes around the codigo value (if that's another string)... but I'd strongly advise you not to create SQL like this anyway, with values directly in the SQL.
Instead, use a prepared statement:
String sql = "UPDATE inventario set descripcion=?, bodega=? where codigo=?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, descripcion);
st.setString(2, bodega);
st.setString(3, codigo);
Using prepared statements has three immediate benefits:
It avoids SQL injection attacks (think about what happens if your description has a quote in it)
It separates code (SQL) from data (the values)
It means you avoid conversions for types like datetime, where going via a string representation is a huge potential source of error
Remove extra SET on your query.
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
but that query is vulnerable with SQL Injection. Please parameterize your query.
Example,
String query = "UPDATE inventario" +
" set descripcion = ?, bodega = ? " +
" where codigo = ?";
PreparedStatement prep = connection.prepareStatement(query);
prep.setString(1, descripcion);
prep.setString(2, bodega);
prep.setInt(3, codigo);
prep.executeUpdate();
SET keyword is needed only once. Multiple columns that are being updated should be separated by commas, as in the below statement.
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
BTW, it is highly recommended to use PreparedStatement for such operations instead of forming the query like this to avoid SQL Injection attacks.
query = "UPDATE inventario"
+ " set descripcion = ?, bodega = ? "
+ " where codigo = ?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, descripcion);
ps.setString(2, bodega);
ps.setInt(3, codigo);
int updateCount = ps.executeUpdate();

Categories