Make Dynamic Query with JdbcTemplate - java

I have one question regarding make dynamic query with JdbcTemplate.
My code is as below :
String insertQueries = "INSERT INTO " + tablename;
StringJoiner joiner = new StringJoiner(",");
StringJoiner joiner1 = new StringJoiner(",");
StringJoiner joiner2 = new StringJoiner(",");
while (mapIterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) mapIterator.next();
key = joiner.add((String) mapEntry.getKey()).toString();
// value = joiner1.add("\"" + (String) mapEntry.getValue() + "\"").toString();
value = joiner1.add("\"" + (String) mapEntry.getValue() + "\"").toString();
value1 = joiner2.add("?").toString();
}
insertQueries += " (" + key + ")";
insertQueries += " VALUES ("+value1+")" ;
int row = jdbcTemplate.update(insertQueries, value);
Now my question is that I want same number of "value" as per auto generate question marks in insert query.
Right now, the value variable consider as one string so if I have 2 or more question marks then in value variable only one full string with comma separated so it's not working.
See below my query :
INSERT INTO tablename (fname, lname) VALUES ("abc, xyz") ;
And I want as below :
INSERT INTO tablename (fname, lname) VALUES ("abc", "xyz") ;

**StringJoiner joiner2 = new StringJoiner(",", "(", ")");**
while (mapIterator.hasNext()) {
//change in value1 as
value = "\"" + (String) mapEntry.getValue() + "\"";
value1 = joiner2.add(value);
myvalue = joiner2.add("?");
}
//change insertQueries as with value as (? ,?)
insertQueries += " VALUES "+ myvalue+"" ;
//get value1 as ("abc", "xyz")
//update query as
int row = jdbcTemplate.update(insertQueries, value1);

Related

error insert data in java netbeans and mysql

I am a beginner in learning programming and I am trying to apply what I learned with an application example in java , and I encountered a problem. I hope you will find a solution, please.
When I insert data the combobox (combo_produits) it doesn't give me the specified value,
The code has no errors, but the combobox does not give us the desired value despite using the function getSelectedIndex() .
/*method of combobox combo_produits */
private void combo_PRODUIT() {
try {
String qyP = "SELECT CONCAT(NOM_COM,' ',lib_court,' ',DOSAGE ,' ',UNITE , ' ', CONDIT)AS DESIGNATION "
+ "FROM produit JOIN forme USING(cd_forme) ";
prs_sort = connectio.prepareStatement(qyP);
rs_sort = prs_sort.executeQuery();
while (rs_sort.next()) {
combo_produits.addItem(rs_sort.getString("DESIGNATION"));
}
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
}
/* button of insert */
private void valider_bpActionPerformed(java.awt.event.ActionEvent evt) {
int pharID = 0;
int donid = 0;
int lotID = 0;
int prodid= 0 ;
try {
String qr1 = "insert into tbl_pharmacien (NOM_PHARM) values ('" + combo_pharm.getSelectedItem() + "')";
prs_sort = connectio.prepareStatement(qr1, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
pharID = rs_sort.getInt(1);
}
String qr2 = "insert into donner_medic (PHARM_ID , DATE_ECHANDONN) values "
+ "('" + pharID + "', '" + new SimpleDateFormat("yyyy-MM-dd").format(date_prod_sort.getDate()) + "' )";
prs_sort = connectio.prepareStatement(qr2, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
donid = rs_sort.getInt(1);
}
int index =combo_produits.getSelectedIndex();
String qr3 = " insert into tbl_lot (NUM_ENR,PPA, QNT) values "
+ "('" +index + "', '" + txtf_ppa.getText() + "', '" + txt_Qnt.getText() + "' )";
prs_sort = connectio.prepareStatement(qr3, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
lotID = rs_sort.getInt(1);
}
String qr4 = "insert into tbl_donnelot (LOT_ID,DONN_ID) values ('" + lotID + "', '" + donid + "')";
prs_sort = connectio.prepareStatement(qr4);
prs_sort.executeUpdate();
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
Table_prod_sort();
}
For example let's create a compobox with the student's name:
First, we work a class with the student's name and id for him, and we do the Setter, getter and Constructor functions.
Second, we create a function to link the database with the students' class, thus:
public class class_array {
private Connection co=get_connection.ConnDb() ;
private PreparedStatement prst ;
private ResultSet res ;
public HashMap<String, Integer> fillCombobox(){
String sqls = "SELECT `ID_student`, `Name_student` FROM `student`";
HashMap<String, Integer> hmp = new HashMap<String, Integer>();
try {
prst = co.prepareStatement(sqls);
res = prst.executeQuery();
student st ;
while(res.next()){
st = new student(res.getInt(1), res.getString(2));
hmp.put(st.getName_stud(), st.getId_stu());
}
} catch (SQLException ex) {
Logger.getLogger(student_f.class.getName()).log(Level.SEVERE, null, ex);
}
return hmp ;
}}
Third, in the form we write the compobox content display function like this :
private void combo(){
class_array std = new class_array();
HashMap<String, Integer> hmp = std.fillCombobox();
for (String cb :hmp.keySet()) {
combo_st.addItem(cb);
}
}
And finally, like in the previous example, we want to use the last Selection of combobox , so we write the following:
private void bp_valid_indexActionPerformed(java.awt.event.ActionEvent evt) {
class_array stb = new class_array();
HashMap<String,Integer> has = stb.fillCombobox();
int index = has.get(combo_st.getSelectedItem().toString()).toString();
}
I found the solution, and it lies in displaying the content of the combobox with linking it to the number of his id, so that when we work getSelectedItem the value of the combobox is selected with his id

h2|Java Column not found (but statement works elsewhere)

I want to insert data to my table, I have an insert statement (to the same table) that I use in a different method which works in one method, but returns an JdbcSQLSyntaxErrorException: Column xyz not found; in another.
where xyz is the value I want to pass into the column (not the column name).
This is the method which triggers the exception:
public void btnSaveStock(MouseEvent mouseEvent) {
ArrayList<Stock> stock = new ArrayList<>();
stock.addAll(tblStock.getItems());
stock.remove(removedStock);
try {
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection(url, "", "");
Statement statement = connection.createStatement();
for (int i = 0; i < stock.size(); i++) {
String stockName = stock.get(i).getDescription();
String stockCode = stock.get(i).getCode();
double fuelBalance = stock.get(i).getStoresBalance();
double counterBalance = stock.get(i).getCounterBalance();
System.out.println(stockName + stockCode + fuelBalance + counterBalance);
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES (" + stockCode + ",'New Product','1.00','1.00')";
statement.executeUpdate(insertQuery);
String updateQuery = "Update STOCK set DESCRIPTION='" + stockName + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
updateQuery = "Update STOCK set \"fuelBalance\"='" + fuelBalance + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
updateQuery = "Update STOCK set \"counterBalance\"='" + counterBalance + "' where CODE='" + stockCode + "'";
statement.executeUpdate(updateQuery);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
//more method calls here
}
This is the method that successfully inserts data:
public void addNewStock(MouseEvent mouseEvent) {
Stock stock = new Stock();
String lastCode = savedStockList.get(savedStockList.size() - 1).getCode();
int newCode = 1 + Integer.parseInt(lastCode);
stock.setCode(String.valueOf(newCode));
stock.setCounterBalance(0);
stock.setDescription("New Product");
stock.setStoresBalance(0);
savedStockList.add(stock);
try {
Class.forName("org.h2.Driver");
Connection connection = DriverManager.getConnection(url, "", "");
Statement statement = connection.createStatement();
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES (" + newCode + ",'New Product','1.00','1.00')";
statement.executeUpdate(insertQuery);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
initialiseStock();
}
So if stockCode contains the value xyz, the exception will be Column xyz not found
I'm failing to understand why this works in one method, but returns an exception in another.
It works because newCode is a number which doesn't need quotes and doesn't work because stockCode is a string and needs to be quoted. Add single quotes around stockCode and it should work:
String insertQuery = "INSERT INTO PUBLIC.STOCK (CODE, description, \"fuelBalance\", \"counterBalance\") VALUES ('" + stockCode + "','New Product','1.00','1.00')";
As a side note you should really use prepared statement.

Updating multiple rows by their IDs

I have an ArrayList of IDs and I want to update a certain column in each row corresponding to each ID. What I am trying to do is writing another, existing ID in that column.
I've got a more or less working solution; I'll show it to you first and then describe my problems with it:
public static void partnerStmt(ArrayList<Integer> keys, int age, int sex, int variable){
int amount = keys.size();
int ageMin = age - variable;
int ageMax = age + variable;
if (ageMin < 18)
ageMin = 18;
String select = "SELECT ID FROM individuen WHERE Jahre BETWEEN "
+ ageMin +" AND "+ ageMax + " AND family IS 2 AND married IS NULL AND Sex "
+ "IS " + sex + " ORDER BY RANDOM() LIMIT " +amount+";";
try {
Statement stmt = DBController.connection.createStatement();
ResultSet rs = stmt.executeQuery(select);
for (int i = 0; i < keys.size(); i++) {
int key = keys.get(i);
int idColumn = rs.findColumn("ID");
int partnerID = rs.getInt(idColumn);
PreparedStatement person = DBController.connection
.prepareStatement("UPDATE individuen set Partner = " + partnerID +
" WHERE ID = " + key);
person.executeUpdate();
rs.next()
}
} catch (SQLException e) {
e.printStackTrace();
}
}
My problems with this are, that it is slow. Updating one row at a time just doesn't work with more then 100k entries to be updated. The second problem is, that for some reason IDs, that I am writing into the table (partnerID) show up multiple times after running the programm.
Does anybody know a more efficient and better way of doing something like this?
Use batching functionality of JDBC to reduce the number of round-trips:
PreparedStatement person = DBController.connection.prepareStatement(
"UPDATE individuen set Partner = ? WHERE ID = ?"
);
int idColumn = rs.findColumn("ID");
for (Integer key : keys) {
if (!rs.next()) {
// Make sure that we do not read a missing parent ID.
// This should never happen, as long as rs has enough rows.
break;
}
person.setInt(1, rs.getInt(idColumn));
person.setInt(2, key);
person.addBatch();
}
person.executeBatch();
Note that this code uses parameterized statements with ? parameters and setXYZ methods for supplying values.
you could try using in since it looks like your partner id doesnt change
just create a list of your keys and use it like this
"UPDATE individuen set Partner = " + partnerID + " WHERE ID IN (1,2,3,4)"
also even if this doesnt work try moving
int idColumn = rs.findColumn("ID");
int partnerID = rs.getInt(idColumn);
our of your for loop since it never changes
This is how I solved it thanks to you help. I'm still not sure, if this is the most efficient way. So if you've got some suggestions, I'm happy to try them out ;)
public static void partnerStmt(ArrayList<Integer> keys, int age, int sex, int range){
int amount = keys.size();
int aageMin = alter - range;
int ageMax = alter + range;
int[][] storeArr = new int[amount][2];
if (ageMin < 18)
ageMin = 18;
String select = "SELECT ID FROM individuen WHERE Age BETWEEN "
+ ageMin +" AND "+ ageMax + " AND Family IS 2 AND Partner IS NULL AND Sex "
+ "IS " + sex + " ORDER BY RANDOM() LIMIT " +amount+";";
try {
Statement stmt = DBController.connection.createStatement();
ResultSet rs = stmt.executeQuery(select);
for (int i = 0; i < anzahl; i++){
int idColumn = rs.findColumn("ID");
int idPartner = rs.getInt(idColumn);
storeArr[i][0] = keys.get(i);
storeArr[i][1] = idPartner;
rs.next();
}
PreparedStatement person = DBController.connection.prepareStatement(
"UPDATE individuen set Partner = ? WHERE ID = ?");
for (int i = 0; i < amount; i++){
person.setInt(1, storeArr[i][0]);
person.setInt(2, storeArr[i][1]);
person.addBatch();
}
person.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}
}

Pass value of an object from DAO to servlet in 2D array

I would like to print the values of an object from DAO to servlet.
DAO:
public static List getFree(String svLectID,String ExLectID) throws SQLException, ClassNotFoundException
{
currentCon = JavaConnectionDB.getConnection() ;
PreparedStatement ps1 = currentCon.prepareStatement("SELECT *\n" +
"FROM (\n" +
" SELECT e1.FreeID,\n" +
" e1.lecturerID SVID,\n" +
" e1.availableID SVavail,\n" +
" e1.freedate AS SVFree,\n" +
" e2.lecturerID AS Examiner, \n" +
" e2.freedate EXFree,\n" +
" s.studentID,\n" +
" s.studentName,\n" +
" s.lecturerID AS lectID,\n" +
" sv.lecturerID AS SVlecturerID,\n" +
" sv.lecturerFullname AS SVlecturerName,\n" +
" ex.lecturerID AS EXlecturerID,\n" +
" ex.lecturerFullname AS EXlecturerName,\n" +
" v.availableID availID,\n" +
" v.availableDay,\n" +
" v.availableStart,\n" +
" v.availableEnd,\n" +
" ROW_NUMBER() OVER (PARTITION BY e1.lecturerID \n" +
" ORDER BY dbms_random.random) AS rn\n" +
" FROM free e1 \n" +
" INNER JOIN free e2 \n" +
" ON e1.availableID = e2.availableID\n" +
" INNER JOIN student s\n" +
" ON s.lecturerID = e1.lecturerID\n" +
" INNER JOIN lecturer sv\n" +
" ON sv.lecturerID = e1.lecturerID\n" +
" INNER JOIN lecturer ex\n" +
" ON ex.lecturerID = e2.lecturerID\n" +
" INNER JOIN availability v\n" +
" ON v.availableID = e2.availableID\n" +
" \n" +
" \n" +
" WHERE e1.lecturerID = ? \n" +
" AND e2.lecturerID = ? \n" +
" ORDER BY e2.availableID asc\n" +
" \n" +
" )\n" +
"WHERE rn <=5") ;
ps1.setString(1, svLectID) ;
ps1.setString(2, ExLectID);
List list = new ArrayList() ;
ResultSet rs1 = ps1.executeQuery() ;
while(rs1.next())
{
Object[] obj = new Object[17] ;
obj[0] = rs1.getString(1) ;
obj[1] = rs1.getString(2);
obj[2] = rs1.getInt(3);
obj[3] = rs1.getDate(4);
obj[4] = rs1.getString(5);
obj[5] = rs1.getDate(6);
obj[6] = rs1.getString(7);
obj[7] = rs1.getString(8);
obj[8] = rs1.getString(9);
obj[9] = rs1.getString(10);
obj[10] = rs1.getString(11);
obj[11] = rs1.getString(12);
obj[12] = rs1.getString(13);
obj[13] = rs1.getInt(14);
obj[14] = rs1.getString(15);
obj[15] = rs1.getDate(16);
obj[16] = rs1.getDate(17);
list.add(obj) ;
System.out.println("zabir "+rs1.getString(8));
}
return list ;
}
As you can see these values are stored in an object into a list. I retrieve these values to servlet.
SERVLET:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
currentCon = JavaConnectionDB.getConnection();
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletContext context=getServletContext();
String[] studentID = request.getParameterValues("studentID");
String[] supervisorID = request.getParameterValues("supervisorID");
String[] examinerID = request.getParameterValues("examinerID");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try{
out.println("<br><center><table><tr>"
+ "<th>Student Name</th>"
+ "<th>Project Title</th>"
+ "<th>Supervisor Name</th>"
+ "<th>Examiner Name</th>"
+ "<th>Start</th>"
+ "<th>End</th>"
+ "<th>Date</th>"
+ "</tr>");
for (int i=0 ; i<studentID.length ; i++){
FreeBean free = new FreeBean();
PresentationBean present = new PresentationBean();
StudentBean student = new StudentBean();
List list = new ArrayList() ;
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
System.out.println(list.get(0)); //DEBUGGED HERE
System.out.println(list); //DEBUGGED HERE
out.println("<tr>");
out.println("<tr>");
out.println("<td>"+ studentID[i]+"</td>");
out.println("<td> Hello </td>");
out.println("<td>"+ supervisorID[i] +"</td>");
out.println("<td>"+ examinerID[i] +"</td>");
out.println("<td>"+ SVavailableID+"</td>");
out.println("<td>"+ EXavailableID+"</td>");
out.println("<td>"+ EXFreeDate+"</td>");
out.println("</tr>");
}//student loop
out.println("</center></table><br><br>");
out.println("</body>");
out.println("</html>");
}// first try
catch (Exception e)
{
e.printStackTrace() ;
}//first catch
}//throws method
I tried to get the value using SOP first like this:
System.out.println(list.get(0)); //DEBUGGED HERE
System.out.println(list); //DEBUGGED HERE
First SOP produce : [Ljava.lang.Object;#13432ad
Second SOP produce : [[Ljava.lang.Object;#1dd079f,
My first assumption was get(0) wil give me FreeID value. As declared in DAO.
So how can i get the value if using get(0) is wrong?
Your freeId should be in the first position of each array present in the list returned by the method getFree.
To get the freeId of the first element of the list you should do something like:
System.out.println((Object[]) list.get(0))[0]);
For the freeId of the second element of the list:
System.out.println((Object[]) list.get(1))[0]);
and so on.
It will be more readable doing something like that:
Object[] firstObjectAsArray = (Object[]) list.get(0);
System.out.println(firstObjectAsArray[0]);
Object[] secondObjectAsArray = (Object[]) list.get(1);
System.out.println(secondObjectAsArray[0]);
To print the freeId of all elements of the list
for (Object objectAsArray : list) {
System.out.println(((Object[]) objectAsArray)[0]);
}
Note: looking at your code there is a not necessary creation of an empty list. The code:
List list = new ArrayList() ; // Not necessary
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
can be optimized as follow:
int SVavailableID = free.getAvailableID();
int EXavailableID = free.getAvailableID();
List list = GenerateScheduleDAO.getFree(supervisorID[i],examinerID[i]);
Note: using generics you don't need the cast. To do that replace the definition of the list
List list = new ArrayList();
with
List<Object[]> list = new ArrayList<Object[]>();
Your list contains arrays of Object, so you have to call the relevant indexes of the array.
You could debug the full list like this
// iterate over the list
for (int i = 0; i < list.size(); i++) {
Object[] array = (Object[])(list.get(i));
// iterate over the Object array
for (int j = 0; j < array.length; j++) {
System.out.println(array[j]);
}
}

Sorting arrayList from resultset

I'm working on a project that involves 2 separate db to generate the report. The result of one is passed into the other query and a final report is generated. Now, i wan to sort the final report but having issues with it. Java constructor for "java.util.Arrays" with arguments "" not found.
var fist = new java.util.Arrays();
var list = new java.util.ArrayList();
var gist = new java.util.ArrayList();
var arr = '';
var dbConn = DatabaseConnectionFactory.createDatabaseConnection('Postgres connection');
var result3 = dbConn.executeCachedQuery(...)
while (result3.next()) {
var value1 = result3.getString(1);
var value2 = result3.getString(2);
var dbConn3 = DatabaseConnectionFactory.createDatabaseConnection('Oracle connection'));
var result2 = dbConn3.executeCachedQuery("SELECT name FROM producer WHERE send = '" + value1 + "' AND code = '" + value2 + "' ORDER BY name")
while (result2.next()) {
var sending = result2.getString(1);
}
dbConn3.close();
if (sending != undefined) {
arr += gist.add(sending);
arr += gist.add(value1);
arr += gist.add(value2);
arr += gist.add(result3.getString(3));
fist.add(arr);
}
}
Arrays.sort(fist); //i'm thinking this should sort it before displaying it
while (fist.next()) {
xmlMs += "<tr>"
xmlMs += "<td>" + sending + "</td>";
xmlMs += "<td>" + value1 + "</td>";
xmlMs += "<td>" + value2 + "</td>";
xmlMs += "<td align='center'>" + result3.getString(3) + "</td>";
xmlMs += "</tr>";
}
Well yes, your compiler is telling you that var fist = new java.util.Arrays(); is invalid, java.util.Arrays doesn't provide a public no-args constructor. Did you by chance mean ArrayList instead of Arrays?
Arrays doesn't have a constructor defined in the source code, so new Arrays(); causes the compiler to scream at you.
If you want an array of something you use
type[] varname = new type[size];
Note that the [] is what makes it an Array.
Ex:
int[] x = new int[5];
That will hold an array of 5 ints.

Categories

Resources