I am using hibernate application in java to retrieve and update database.
During updating a table,i forming an sql query as follows,
String qry = "UPDATE " + entity + " SET " + htmlColumn + " ='"+value+"' WHERE " + id + " = " + primaryId;
where value is a html string which contains single quotes sometimes.
How to escape ignore/escape the single quotes and update the table successfully
Thanks
use PreparedStatement for this
String qry = "UPDATE " + entity +
" SET " + htmlColumn + " = ? " +
"WHERE " + id + " = ?";
PreparedStatement pstmt = con.prepareStatement(qry);
pstmt.setString(1, value);
pstmt.setInt(2, primaryId);
pstmt.executeUpdate();
PreparedStatement
Don't set values directly.
currentSession()
.createQuery("UPDATE " + entity + " SET " + htmlColumn +
" = :value WHERE " + id + " :id")
.setParameter("value", value).setParameter(":id",id).executeUpdate();
You can replace the single quote with a double single quote. value.replace("'","''"); but you will need to cater for more than just that because your value can easily allow for SQL Injection if it is not properly catered for.
You can use preparedstatement as :
String query= "UPDATE " + entity + " SET " + htmlColumn + " =? WHERE " + id + " = " + primaryId;
PreparedStatement ptmt = con.prepareStatement(query);
ptmt.setString(1, value);
Related
Log Cat:
no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
code:
102) public String getID(String note){
103) SQLiteDatabase db = this.getWritableDatabase();
104) String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
105) db.rawQuery(query,null);
106) return query;
107) }
I do have a column name hey in my Database
Database Picture
Your terminology is confused.
hey is a value, NOTEMEMOS is a column.
You need to quote the value hey to let the SQL compiler know that it is a string value, rather than a column you are trying to compare against.
String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'");
Just a note, you would be better off using a parameterised query, as using raw values is insecure (see SQL injection).
String query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?"); // That's right, quotes aren't needed for a parameterized query.
String result = "";
Cursor cursor = db.rawQuery(query,new String[] {note} );
if (cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(COL_0));
}
cursor.close();
return result;
Your query should look like this
SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = 'hey'
Let me know if it helps
The way that you concatenate the parameter note creates this sql statement:
SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
so hey is considered a column identifier and not a string literal because it is not enclosed inside single quotes.
You could do this instead:
String query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'";
and it would work.
But the recommended way is passing parameters as a string array like this:
String query = "SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?";
Cursor cursor = db.rawQuery(query, new String[] {note});
return cursor;
This way you don't worry about single quotes as this is taken care of by rawQuery().
I guess you want to return the Cursor object and not the sql query string, right?
I want to delete one row from multiple tables in an Access database.
This is the code I tried to use in my project, but I got an error.
PreparedStatement ps = con.prepareStatement("DELETE FROM 'customer_details' , 'papers', 'magzines' WHERE 'customer_id' = ? ");
ps.setString(1,tx1.getText());
int string = ps.executeUpdate();
Can anyone help me solve this?
I just tried the following and it worked for me:
String sql =
"DELETE t1.*, t2.*, t3.* " +
"FROM " +
"(" +
"Table1 AS t1 " +
"INNER JOIN " +
"Table2 AS t2 " +
"ON t2.ID=t1.ID " +
")" +
"INNER JOIN " +
"Table3 AS t3 " +
"ON t3.ID=t2.ID " +
"WHERE t1.ID=?";
ps = con.prepareStatement(sql);
ps.setInt(1, 4); // delete where ID=4
int n = ps.executeUpdate();
So in your case try something like this:
PreparedStatement ps = con.prepareStatement(
"DELETE c.*, p.*, m.* " +
"FROM " +
"(" +
"customer_details AS c " +
"INNER JOIN " +
"papers AS p " +
"ON p.customer_id=c.customer_id " +
")" +
"INNER JOIN " +
"magzines AS m " +
"ON m.customer_id=p.customer_id " +
"WHERE c.customer_id=?");
ps.setString(1,tx1.getText());
int n = ps.executeUpdate();
im using this code to populate my jtable with data from database:
String sql = "SELECT "
+ "a.pranesimo_pav AS 'Pavadinimas', a.sukurimo_data AS 'Sukurtas' , b.gavimo_data AS 'Gavimo data'"
+ "FROM Pranesimas a "
+ "INNER JOIN "
+ "( "
+ "SELECT pranesimo_id, gavimo_data "
+ "FROM Pranesimo_siuntimas_vienam_zmogui "
+ "WHERE vardas_pavarde = '" +vardas_pavarde+ "' "
+ "UNION ALL "
+ "SELECT pranesimo_id, gavimo_data "
+ "FROM Pranesimo_siuntimas_grupei "
+ "WHERE grupes_pav = '" +grupes_pav+ "'"
+ ")b ON a.pranesimo_id = b.pranesimo_id ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery(sql);
antraspanelesamipranesimaiTable.setModel(DbUtils.resultSetToTableModel(rs));
}
It does the job, but at the end of my 'datetime' value, it adds '.0' at the end of it, for example:
value in database - '2013-01-20 02:50:00'
value i get in my table - '2013-01-20 02:50:00.0'
how can i fix this?
I am currently trying to implement a jdbc connection that returns all the data in a table when i "search" for anything that matches the input with '%input%'.
eg ResultSet rs4 = stm4.executeQuery("select imageTime from image_data where imageName like '%" + value3 + "%' or imageTime like '%" + value3 + "%' or imageLocation like '" + value3 + "'" );
i am trying to return ALL the rows in the result set as search results.
but if i have Resultset.next commanded when there is no more rows to go to it
causes the following results sets to all null,....
if anything id love a method to output the entire result set, thanks.
EDIT
editing the question: to be more direct; i need a way to get every piece of data from each row in each containing column of the result set. so i can output it.
This is my attempt of this below.
rs4 = a Resultset as declared below.
here is my code;
if(name_time_location == 1)
{
String value3=searchInput.getText();//Sets the search Input as value3
// selecting the cominbation from table, that match input options
try{
con = DriverManager.getConnection("jdbc:mysql:blah blah");
// Query the database for the correct username and passord
Statement stm3 = con.createStatement();
Statement stm4 = con.createStatement();
Statement stm5 = con.createStatement();
//queries database for password from input username
ResultSet rs3 = stm3.executeQuery("select imageName from image_data where imageName like '%" + value3 + "%' or imageTime like '%" + value3 + "%' or imageLocation like '" + value3 + "'" );
//ResultSetMetaData rsmd = rs3.getMetaData();
//stm3.setFetchSize(5);
//rs3.last();
//int numberOfRows = rs3.getRow();
//String[] resultList;
//resultList = new String[numberOfRows];
// Fetch each row from the result set
rs3.beforeFirst();
while(rs3.next())
{
imageSearchResult1 = rs3.getString(1);
rs3.next();
imageSearchResult11 = rs4.getString(1);
rs3.next();
imageSearchResult12 = rs4.getString(1);
rs3.next();
imageSearchResult13 = rs4.getString(1);
rs3.next();
imageSearchResult14 = rs4.getString(1);
}rs3.close();
}catch (Exception e)
{
//System.out.println("Exception: " + e + "");
}
System.out.println("Search Results: \nName: " + imageSearchResult1 + " Time stamp: " + imageSearchResult2 + " Location: " + imageSearchResult3 + "\n" +
"Name: " + imageSearchResult11 + " Time stamp: " + imageSearchResult21 + " Location: " + imageSearchResult31 + "\n" +
"Name: " + imageSearchResult12 + " Time stamp: " + imageSearchResult22 + " Location: " + imageSearchResult32 + "\n" +
"Name: " + imageSearchResult13 + " Time stamp: " + imageSearchResult23 + " Location: " + imageSearchResult33 + "\n" +
"Name: " + imageSearchResult14 + " Time stamp: " + imageSearchResult24 + " Location: " + imageSearchResult34 + "\n" );
I think you can achieve the same thing by modifying the query and instead of creating 3 queries, get the 3 values in the same query as:
select imageName,imageLocation,imageTime from .....
Then use this query to generate the ResultSet and get the three values as rs.getType(1),rs.getType(2),rs.getType(3).
In the same while(rs.next()) loop, you can print the data that you want to print.
I am trying to insert records into SQL Server using jdbc conn (in java).
I am able to insert into SQL, if I manually copy the query statement in the java file. But its not inserting from the code?
Please help, where am I committing mistake?
PreparedStatement preparedStatement = null;
if (conn != null) {
System.out.println("Connection Successful!");
}
//Create a Statement object
Statement sql_stmt = conn.createStatement();
//Create a Statement object
Statement sql_stmt_1 = conn.createStatement();
//Result Set for Prouduct Table
ResultSet rs = sql_stmt.executeQuery("SELECT MAX(ID), MAX(RG_ID), MAX(WG_ID) FROM " + strDBName + ".[dbo].Product");
if ( rs.next() ) {
// Retrieve the auto generated key(s).
intID = rs.getInt(1);
intRG_ID = rs.getInt(2);
intWG_ID = rs.getInt(3);
}
for (int iCount = 0 ;iCount < arrListLevel_1_Unique.size(); iCount++)
{
//Result Set for Prouduct Table
sql_stmt_1.executeUpdate("\n IF NOT EXISTS(SELECT 1 FROM " + strDBName + ".[dbo].Product WHERE [Name] NOT LIKE '" + arrListLevel_1_Unique.get(iCount) + "') "
+ "\nINSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ "VALUES ( '" + arrListLevel_1_Unique.get(iCount) + "',"
+ + (intWG_ID + intRowIncrement) + ", " + (intWG_ID + intRowIncrement + 1) + ", 5828)");
intRowIncrement++ ;
}
rs.close();
sql_stmt.close();
sql_stmt_1.close();
//Close the database connection
conn.close();
You have two plus signs + in the fifth row:
+ + (intWG_ID + intRowIncrement) + ...
Otherwise, the problem may lie in the IF ... statement. You can try this instead:
sql_stmt_1.executeUpdate(
" INSERT INTO " + strDBName + ".[dbo].Product ([Name] ,"
+ "[RG_ID],[WG_ID],[Parent_Product]) "
+ " SELECT '" + arrListLevel_1_Unique.get(iCount) + "',"
+ (intWG_ID + intRowIncrement) + ", "
+ (intWG_ID + intRowIncrement + 1) + ", 5828 "
+ " WHERE NOT EXISTS( SELECT 1 FROM " + strDBName
+ ".[dbo].Product WHERE [Name] LIKE '"
+ arrListLevel_1_Unique.get(iCount) + "') "
) ;
I think the problem lies on the "\n", have you tried eliminating those 2 of "\n" and see if it's working?
Actually this kind of implementation (building SQL string with string concatenation) is really bad. At first is prone to SQL injection, and then secondly you will have problem if the value to be inserted contains character single quote or ampersand.
Instead, you should use "prepare statement".
And it's tidier to store the SQL string into a variable before executing it. So that you can log it (for debug purpose), roughly something like this:
String sqlCommand = "select * from " + tableName;
System.out.println(sqlCommand);
sqlStatement.executeUpdate(sqlCommand);
P.S. it is not advised to use system.out.println for debug, you should implement a proper logging system.