I have a SELECT statement like SELECT * FROM table where id=? and key IN (?,?..?).
For INSERT,UPDATE we have this batchWithParams, how can I do this for SELECT. I am using JDBC driver for MySQL database. The array list is like so,
BATCH [[100,4,11], [150,4,12]]
Why not just convert the ArrayList into String? Like this:
suspend fun getUsersByEmail(emails: Iterable<String>): List<User> {
return mysqlPool.getConnectionAwait().use { conn ->
conn.query(
"""
SELECT * FROM users
WHERE email IN (${emails.joinToString(separator = ", ") { "'$it'" }})
"""
).executeAwait().map { row ->
User(
row.getLong("id"),
row.getString("email")
)
}
}
}
Related
I have created 'smphas' table in my database. To retrieve the data, I write this code:
function goBack() {
window.location.replace("dashboardproject.jsp");
}
function getQuarter(phase){
if(phase==""){
alert("PLEASE CHOOSE PHASE");
} else {
document.getElementById("phase").value = phase;
constructionprogress.submit();
}
}
function selected(){
$('#phaseCons').val('<%=phase%>');
}
Mysql command is:
public List<String[]> constPeriodPhase (String projCde,String co_no){
System.out.println("/*** constPeriodPhase ***/");
String sql = "SELECT distinct smh_phase_num, smh_phase_nme FROM c"+co_no+".smphas WHERE smh_proj_cde = '"+projCde+"'";
System.out.println("Execute = "+sql);
return super.execListStrArr(sql,false);
}
However, the error is:
/* constPeriodPhase */
Execute = SELECT distinct smh_phase_num, smh_phase_nme FROM cnull.smphas WHERE smh_proj_cde = 'null'
nullnulle-Solicitor[cnull.smphas]
2020-03-12 09:53:58.165 SGT EXECUTE: SELECT distinct smh_phase_num, smh_phase_nme FROM cnull.smphas WHERE smh_proj_cde = 'null'
java.sql.SQLSyntaxErrorException: Unknown database 'cnull'
How can i retrieve the database from mysql?
Unknown database 'cnull'
with a query:
...FROM c"+co_no+".smp
mean co_no is null when the function was called.
I am using java JDBI3 to perform basic CRUD on mariaDB.
I am able to establish connection successfully.
The select * query from java works correctly.
jdbi.withHandle(handle -> handle.createQuery(
"SELECT * FROM users where email = :email;")
.bind("email", email)
);
Similarly when I try delete from it does not update the DB
jdbi.withHandle(handle -> {
return handle.createUpdate(
"DELETE FROM users WHERE email = :email;")
.bind("email", email)
.execute();
}
);
I tried to login in the sql shell and form there I am able to delete
DELETE FROM users WHERE email = 'dummy#email.com'
Can someone tell me what am I doing wrong?
You should not be using "createUpdate" method as per its documentation:
https://jdbi.org/apidocs/org/jdbi/v3/core/Handle.html
Create an Insert or Update statement which returns the number of rows
modified.
Instead, write
jdbi.withHandle(handle -> {
return handle.execute(
"DELETE FROM users WHERE email = :email",email);
});
I'm working on a simple VertX Application. I have a hsqlDB and I'm trying to execute a query where I want to get all IDs from the Table where the Name contains a search parameter
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE ?";
So this works when the Name is the same as the ?
When I try to use wildcards:
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE %?%";
or
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE '%?%'";
it doesn't work.
My Code:
private void getIDsBySearchString(String search, SQLConnection conn, Handler<AsyncResult<Vector<Integer>>> resultHandler) {
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE ?";
conn.queryWithParams(sql, new JsonArray().add(search), asyncResult -> {
if(asyncResult.failed()) {
resultHandler.handle(Future.failedFuture("No Names Found"));
} else {
int numRows = asyncResult.result().getNumRows();
if(numRows >= 1) {
Vector<Integer> IDVector = new Vector<>();
for(int i = 0; i < numRows; i++) {
int id = asyncResult.result().getRows().get(i).getInteger("ID");
IDVector.add(id);
}
resultHandler.handle(Future.succeededFuture(IDVector));
} else {
resultHandler.handle(Future.failedFuture("No Names found"));
}
}
});
}
How do I need to edit my query String so the ? will be replaced by the search String and I will be able to use wildcards?
A parameter cannot be inside a quoted string. It can be part of a concat expression involving other strings.
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE '%' || ? || '%'";
The part that should be changed is your search parameter, not the sql part:
String sql = "SELECT ID FROM MYTABLE WHERE NAME LIKE ?";
conn.queryWithParams(sql, new JsonArray().add("%"+search+"%"), asyncResult -> { ... }
I'm new to java and I need help with displaying a joined table/query in jtable.
First, I have done displaying data from 1 table which is:
Select data from 1 table
insert the result to its entity and insert each one of it to a List
return the list to view and insert row to jtable
I am using a DAO pattern, which has a factory, interface, implement, entity and view.
So what if I select data from other table?
Here is my get method in implement for getting book
public List get(String find) {
try {
ps = db.connect().prepareStatement("SELECT * FROM books WHERE title like ? ");
ps.setString(1, "%" + find + "%");
status = db.execute(ps);
if (status) {
books = db.get_result();
listBooks = new ArrayList<>();
while (books.next()) {
entity_books b = new entity_books();
b.setId(books.getInt(1));
b.setId_category(books.getInt(2));
b.setTitle(books.getString(3));
listBooks.add(b);
}
books.close();
return listBooks;
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
and then in my view:
listBooks = booksDAO.get(find.getText());
model = (DefaultTableModel) book_table.getModel();
model.setRowCount(0);
listBooks.forEach((data) -> {
model.addRow(new Object[]{
data.getId(),
data.getId_category(),
data.getTitle(),
});
});
This works fine, but I want the query to join table so I can see the category name instead of just ID category. I can do the query, but how do I apply that to my code?
Here is the query for joined table
select title,category from book b
join category c on c.id = b.id_category
Normally if I select only 1 table, I would insert it to its entity ( book table -> book entity ), so how do I handle this with multiple tables?
I didn't use prepared statement, but this code works on my end.
String sql = "SELECT * FROM customer c JOIN company cmp ON c.company_idcompany = cmp.idcompany";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while (rs.next()) {
//Retrieve this from customer table
int id = rs.getInt("idcustomer");
//Retrieve this from customer table
String username = rs.getString("company_username");
//Display values
System.out.println("ID: " + id);
System.out.println("Username: " + username);
}
I am using "with data as" as in below query. When I run this in sql developer, it's executing fine, but in java code when I call the query as normal string or through jdbc template in xml configuration file, it gives me bad SQL grammar. Is there any alternative to the below query?
public class NppGWOrphanMessageDao extends DefaultDao {
String sql = "same sql as i posted"
private String replayGWOrphanMsgSQL;
public void setReplayGWOrphanMsgSQL(String replayGWOrphanMsgSQL) {
this.replayGWOrphanMsgSQL = replayGWOrphanMsgSQL;
}
public String getReplayGWOrphanMsgSQL() { return replayGWOrphanMsgSQL; }
public List<Map<String, Object>> getReplayList(HashMap<String, Object> epoch) {
return retrieveAll(replayGWOrphanListSQL, params);
return retrieveAll(sql, epoch); }
}
WITH DATA AS (
SELECT GLOB.ID, GLOB.CHARACTERS
FROM GW_LOB_STORE GLOB
WHERE
NOT EXISTS(SELECT 1 FROM GW_NPP_MSG_INTEGRITY M WHERE M.LOB_STORE_ID=GLOB.ID)
AND NOT EXISTS(SELECT 1 FROM GW_NPP_SAFE_STORE S WHERE S.LOB_STORE_ID=GLOB.ID)
AND NOT EXISTS(SELECT 1 FROM GW_POISON_LOG P WHERE P.LOB_STORE_ID=GLOB.ID)
AND GLOB.CREATED_TS > = :epoch)
SELECT
A.ID AS "GLOBID",
INQUEUEDTL.ID AS "INQUEID",
A.CHARACTERS AS "REQUESTBODY",
INQUEUEDTL.ENDPOINT_ID AS "ENDPOINTID",
INQUEUEDTL.HEADER AS "HEADERS"
FROM DATA A, GW_IN_QUEUE_DETAIL INQUEUEDTL
WHERE A.ID=INQUEUEDTL.ID;
For the sake of completeness:
The problem with this query is the ; at the end of it.
Oracle JDBC driver does not handle it well.