Get tableName values to be put into hashmap - java

I need to tablevalues.. into the map..
My code is bellow:
public HashMap getValuesFromDeleteAction(String tableName,Object[] filterColumn,Object[] filterValue){
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
HashMap map = new HashMap();
try{
System.out.println("====DELETE_ACTION===");
conn=this.getConnection();
if(conn!=null && !conn.isClosed()){
if(filterColumn!=null && filterValue!=null && !tableName.trim().isEmpty()
&&filterColumn.length==filterValue.length){
String sql = "SELECT * FROM "+tableName+"";
String filterSql = " WHERE " ;
for(int i=0;i<filterColumn.length;i++){
if(i==0){
filterSql = filterColumn[i]+"="+"'"+filterValue[i]+"'";
}else{
filterSql= filterSql+" AND "+filterColumn[i]+"="+"'"+filterValue[i]+"'"; }
}
String sSql=sql+filterSql;
ps = conn.prepareStatement(sSql);
rs=ps.executeQuery();
while(rs.next())
{
map.put(tableName +"LAST_UPDATE_DATE", rs.getString("LAST_UPDATE_DATE"));
map.put(tableName +"LAST_UPDATE_BY" , rs.getString("LAST_UPDATE_BY"));
}
}else{
//do nothing
}
System.out.println("MapValues==2323===>"+map);
}
}catch(Exception e){
}
return map;
}

first define your map by this:
Map<String,String> map = new HashMap<String, String>();
and where is your connection settings!?
then try this:
while(rs.next()) {
map.put("LAST_UPDATE_DATE", rs.getString("LAST_UPDATE_DATE"));
map.put("LAST_UPDATE_BY", rs.getString("LAST_UPDATE_BY"));
}

Related

Loop in List of Map in get Query JDBC [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to make a get result of my query with List<Map<String, String>> result
But I'm blocked because I don't see how I can do the loop in my List Map and I have an error in method put
This is a part of my method with the loop for below :
protected List<Map<String, String>> getAllResultForQuery(String sql) throws SQLException {
List<Map<String, String>> result = null;
Connection conn = null;
Statement stmt = null;
try {
// Create connection
conn = endpoint.getDBConnection();
// Execute a query
stmt = conn.createStatement();
// Let us select all the records and display them.
ResultSet rs = stmt.executeQuery(sql);
LOG.debug("Execute query: " + sql);
ResultSetMetaData rsmd = rs.getMetaData();
int nbColumns = rsmd.getColumnCount();
//loop
for (Map<String, String> map : result) {
for (Map.Entry<String, String> entry : map.entrySet()) {
if (rs.next()) {
if (result == null) {
result = new HashMap<String, String>();
}
for (int i = 1; i <= nbColumns; i++) {
String columnName = rsmd.getColumnName(i).toUpperCase();
String columnValue = rs.getString(i);
result.put(columnName, columnValue);
}
}
}
}
Anyone can Help please ?
Thanks
Try this.
protected List<Map<String, String>> getAllResultForQuery(String sql) throws SQLException {
List<Map<String, String>> result = new ArrayList<>();
try (Connection conn = endpoint.getDBConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
ResultSetMetaData rsmd = rs.getMetaData();
int nbColumns = rsmd.getColumnCount();
while (rs.next()) {
Map<String, String> map = new HashMap<>();
for (int i = 1; i <= nbColumns; i++) {
String columnName = rsmd.getColumnName(i).toUpperCase();
String columnValue = rs.getString(i);
map.put(columnName, columnValue);
}
result.add(map);
}
}
return result;
}
I make like this :
for (Map result : results) {
if (rs.next()) {
if (result == null) {
result = new HashMap<String, String>();
}
for (int i = 1; i <= nbColumns; i++) {
String columnName = rsmd.getColumnName(i).toUpperCase();
String columnValue = rs.getString(i);
result.put(columnName, columnValue);
}
}
}
How do you think ?

How come my .setTexts are coming out blank?

I am having to connect an access database to a netbeans project and create a program that allows a user to search for a football player's name, and have their results displayed on the screen. My problem is that when I do the setTexts at the end, the labels simply turn blank. I do not receive any error messages.
I don't know whether the problem lies in the linking to the database or in parsing the parameters, or somewhere else?
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
String temp = new String();
String playerID = null;
String name = null;
String surname = null;
String shirtNo = null;
String height = null;
String prefFoot = null;
String nation = null;
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
conn = DriverManager.getConnection("jdbc:ucanaccess://Database4.accdb");
String sql = "SELECT * FROM Players WHERE Name = (?) and Surname = (?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txtfieldFirst.getText());
pst.setString(2, txtfieldSecond.getText());
rst = pst.executeQuery();
if(rst.next())
{
int count = 0;
while(rst.next())
{
playerID = rst.getString("PlayerID");
name = rst.getString("Name");
surname = rst.getString("Surname");
shirtNo = rst.getString("ShirtNo");
height = rst.getString("Height (Metres)");
prefFoot = rst.getString ("PrefFoot");
nation = rst.getString ("Nation");
}
}
conn.close();
}
catch (Exception e)
{
System.out.println(e);
}
Connection con = null;
PreparedStatement pstt = null;
ResultSet rs = null;
String temp2 = new String();
String league = null;
String DOB = null;
String club = null;
boolean tec = false;
String goals15 = null;
String goals16 = null;
String goals17 = null;
String assists15 = null;
String assists16 = null;
String assists17 = null;
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con = DriverManager.getConnection("jdbc:ucanaccess://Database4.accdb");
String sqll = "SELECT * FROM Stats WHERE PlayerID = (?)";
pstt = con.prepareStatement(sqll);
pstt.setString(1, playerID);
rs = pstt.executeQuery();
if(rs.next())
{
int count = 0;
while(rs.next())
{
league = rs.getString("League");
DOB = rs.getString("DOB");
club = rs.getString("Club");
goals15 = rs.getString("Goals15/16");
goals16 = rs.getString("Goals16/17");
goals17 = rs.getString("Goals17/18");
assists15 = rs.getString("Assists15/16");
assists16 = rs.getString("Assists16/17");
assists17 = rs.getString("Assists17/18");
}
}
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
babyStats pps = new babyStats(league, DOB, club, goals15, goals16, goals17, assists15, assists16, assists17);
babyPlayers ps = new babyPlayers(name, surname, shirtNo, height, prefFoot, nation);
PlayerScreen p = new PlayerScreen(ps, pps); //connection to other screen
p.setVisible(true);
this.setVisible(false);
public PlayerScreen(babyPlayers obj, babyStats objj) //parsed as paramters
{
initComponents();
lblName.setText(obj.getName());
lblSurname.setText(obj.getName());
lblShirtNo.setText(obj.getShirtNo());
lblDOB.setText(objj.getDOB());
lblHeight.setText(obj.getHeight());
lblPFoot.setText(obj.getPreFoot());
lblClub.setText(objj.getClub());
lblNation.setText(obj.getNation()); //these setTexts just make the labels blank
lblGoals16.setText(objj.getGoals1516());
lblGoals17.setText(objj.getGoals1617());
lblGoals18.setText(objj.getGoals1718());
lblAssists16.setText(objj.getAssists1516());
lblAssists17.setText (objj.getAssists1617());
lblAssists18.setText (objj.getAssists1718());
}
I expect the labels to be set with the details coming from the database, but they turn blank instead. I would really appreciate any help. *Update, while debugging, I used system.out.println to print one of the names, and the result came out as null. *Update, I fixed it, the while loops were not meant to be there.

Potential memory leak in this Java code that produces out of heap error

I can't find the reason why this piece of code when run for a long time produces an out of memory heap error. It runs constantly for 1-2 days before crashing. Can anyone see anything?
I only call a static function from another class that should not keep any resources open and then the mysql stuff but I close them all.
note: some of the variable names were changed.
public class Application {
public static void main(String ...args) throws InterruptedException, IOException {
Data.connectDb(); //init
try {
List<Integer> written = new ArrayList<>();
Connection con = Data.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM table2 LIMIT 500");
while (rs.next()) {
Integer mId = rs.getInt("mId");
written.add(mId);
}
Map<Integer,String> bs = new HashMap<>();
rs = st.executeQuery("SELECT * FROM b");
while (rs.next()) {
bs.put(rs.getInt("bId"),rs.getString("name"));
}
st.close();
rs.close();
while (true) {
List<String> abers = new ArrayList<>();
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM table1 WHERE enabled = 1");
while (rs.next()) {
String email = rs.getString("email");
abers.add(email);
}
rs.close();
st.close();
ArrayList<Map> abs = Aber.getAbs(false);
ArrayList<Map> toDispatch = new ArrayList<>();
arbs.forEach((ab) -> {
Integer mId = (Integer) ab.get("mId");
if (!written.contains(mId)) {
written.add(mId);
toDispatch.add(arb);
Pair hLine = (Pair) ab.get("hLine");
Pair dLine = (Pair) ab.get("dLine");
Pair aLine = (Pair) ab.get("aLine");
//todo write it to the database not caring if it's already there as we have a unique constraint
try (Statement st2 = con.createStatement()) {
String sql = "INSERT INTO table1")";
st2.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
if (toDispatch.size() >0) {
Email email = new Email();
abes.forEach(arber -> email.addRecipient(aber, aber, Message.RecipientType.BCC));
String HTML = "<h3>Dear subscribers</h3>";
email.setTextHTML(HTML);
new Mailer(
new ServerConfig("mail.name.com", 587, "info#mm.com", "mmpass"),
TransportStrategy.SMTP_TLS
).sendMail(email);
}
Thread.sleep(600000);
}
} catch (SQLException sqle) {
System.out.println(sqle.getMessage());
}
}
}

Display multiple query results java

Ok, so I'm having some difficulties in returning multiple results on this query in Java
public String getActive() throws SQLException
{
Connection con = DBConnect.getConnection();
String numeUser = "";
String sql=("select NUME from agents WHERE ACTIV = ? AND FILIALA = ? ");
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.setString(2, "MS10");
ResultSet rs = pstmt.executeQuery();
while(rs.next())
{
numeUser = rs.getString("NUME");
}
rs.close();
con.close();
return numeUser;
}
I heard something about that i can return the result with split() method or tokenizer but I don't seem to return the right result.
Agenti q2 = new Agenti();
String str1 = q2.getActive();
StringTokenizer stk1 = new StringTokenizer(str1);
String[] s1 = new String[0];
int i = 0;
while(stk1.hasMoreElements())
{
s1[i] = (String) stk1.nextElement();
i++;
}
System.out.println(s1[0]);
This is my tokenizer code. Can someone help me a little, please?

Search a JTable using multiple JTextfield

I have a JFrame that has 3 JTextfields and 2 JDatechooser, what I am trying to do is if only one JTextfield has something typed in it and I press the search button, then I will be able to retrieve the data to JTable, but the problem is I have to fill out all JTextFileds and JDatechooser in order to retrieve data. My idea is to ignore null JTextfields and JTdatechooser if only one JTextfield has the keyword I want ?? Any suggestions ?? Thanks in advance,
public ArrayList<BillsRecord> getBillRecordByID(int EmpCode, String Fname, String Lname, String sDate, String eDate) throws SQLException {
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE B.EMP_ID = ? "
+ " OR E.FNAME = ? "
+ " OR E.LNAME = ? "
+ " OR DATE BETWEEN ? AND ? "
+ " ORDER BY B.DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
PreparedStatement ps = null;
ArrayList<BillsRecord> records = new ArrayList<>();
try {
ps = connect.prepareStatement(sql);
ps.setInt(1, EmpCode);
ps.setString(2, Fname);
ps.setString(3, Lname);
ps.setString(4, sDate);
ps.setString(5, eDate);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
BillsRecord billrec = new BillsRecord();
billrec.setDATE(rs.getString("DT"));
billrec.setEMP_ID(rs.getInt("EMP_ID"));
billrec.setFNAME(rs.getString("FNAME"));
billrec.setLNAME(rs.getString("LNAME"));
billrec.setMONEY_SENT(rs.getDouble("MONEY_SENT"));
billrec.setRENT(rs.getDouble("RENT"));
billrec.setPHONE(rs.getDouble("PHONE"));
billrec.setGAS(rs.getDouble("GAS"));
billrec.setELECTRICITY(rs.getDouble("ELECTRICITY"));
billrec.setINTERNET(rs.getDouble("INTERNET"));
billrec.setOTHER(rs.getDouble("OTHER"));
records.add(billrec);
return records;
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
if (ps != null) {
ps.close();
}
if (connect != null) {
connect.close();
}
}
return null;
}
private void search() {
try {
JTextField stxt = ((JTextField) startdatetxt.getDateEditor().getUiComponent());
String sDATE = stxt.getText().trim();
JTextField etxt = ((JTextField) enddatetxt.getDateEditor().getUiComponent());
String eDATE = etxt.getText().trim();
int EMP_ID = Integer.parseInt(this.empidtxt.getText().trim());
String FNAME = this.firstnametxt.getText().trim();
String LNAME = this.lastnametxt.getText().trim();
BillRecordDao billrecdao = new BillRecordDao();
ArrayList<BillsRecord> records = billrecdao.getBillRecordByID(EMP_ID, FNAME, LNAME, sDATE, eDATE);
Object[] tableColumnName = new Object[11];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "MONEY SENT";
tableColumnName[5] = "RENT";
tableColumnName[6] = "PHONE";
tableColumnName[7] = "GASE";
tableColumnName[8] = "ELECTRICITY";
tableColumnName[9] = "INTERNET";
tableColumnName[10] = "OTHER";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.BillsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[11];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getMONEY_SENT();
RowRec[5] = records.get(i).getRENT();
RowRec[6] = records.get(i).getPHONE();
RowRec[7] = records.get(i).getGAS();
RowRec[8] = records.get(i).getELECTRICITY();
RowRec[9] = records.get(i).getINTERNET();
RowRec[10] = records.get(i).getOTHER();
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
Basically, you need to create a variable/dynamic query based on the available values
Now, you can do this using something like StringBuilder or even storing each query element in a List or array, but you always end up with the "trailing OR" problem (you need to know when you've got to the last element and not append the "OR" to the String or remove the trailing "OR" from the resulting String). While not difficult, it's just a pain.
However, if you're using Java 8, you can use StringJoiner!
StringJoiner sj = new StringJoiner(" OR ");
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE ";
List values = new ArrayList();
// EmpCode MUST be a Integer, so it can be null
if (EmpCode != null) {
sj.add("B.EMP_ID = ?");
values.add(EmpCode);
}
if (FName != null) {
sj.add("E.FNAME = ?");
values.add(FName);
}
if (LName != null) {
sj.add("E.LNAME = ?");
values.add(LName);
}
if (sDate != null && eDate != null) {
sj.add("DATE BETWEEN ? AND ?");
values.add(sDate);
values.add(eDate);
}
sql += sj.toString();
Connection connect = null;
try (PreparedStatement ps = connect.prepareStatement(sql)) {
for (int index = 0; index < values.size(); index++) {
ps.setObject(index + 1, values.get(index));
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
//...
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
You might also like to have a look at The try-with-resources Statement and have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Categories