public String getDataOfpersons() {
try {
String query = "select * from persons";
rs = st.executeQuery(query);
System.out.println("Records from persons database");
while(rs.next()) {
String name = rs.getString("name");
String age = rs.getString("age");
System.out.println("Name: " + name + " " + "age: " + age);
}
}catch(Exception ex) {
System.out.println(ex);
}
return null;
}
So I have this part of code and I am reading it from mysql database and I am wondering how could I store object to collection (Name and age) ?
First, create a Person class with "name" and "age" fields. Also add the corresponding getters and setters.
Then modify modify your code like this:
// change the return type
public List<Person> getDataOfpersons() {
// create a list to store values
List<Person> personList = new ArrayList<>();
try {
String query = "select * from persons";
rs = st.executeQuery(query);
System.out.println("Records from persons database");
while (rs.next()) {
Person person = new Person();
String name = rs.getString("name");
String age = rs.getString("age");
person.setName(name);
person.setAge(age);
personList.add(person);
System.out.println("Name: " + name + " " + "age: " + age);
}
} catch(Exception ex) {
System.out.println(ex);
}
return personList;
}
Don't know if this is what u looking for without changing the existing signature of the method
public String getDataOfpersons() {
try {
Map<String,String> map = new HashMap<>();
String query = "select * from persons";
rs = st.executeQuery(query);
System.out.println("Records from persons database");
while(rs.next()) {
String name = rs.getString("name");
String age = rs.getString("age");
//System.out.println("Name: " + name + " " + "age: " + age);
map.put("Name",name);
map.put("age",age);
System.out.println(map);
}
}catch(Exception ex) {
System.out.println(ex);
}
return null;
}
Related
i am pretty new i am sorry if i use terms incorrect. I am trying to learn Swing and import it to my current project. In my main file, a method prints a list from mysql database. I want this : when button pressed, print this output to textfield or dialog window, show on the gui, not only cmd output. I hope I could explain my request correctly. I use Netbeans as IDE.
method in Baglanti.java :
public void dogList() {
String sorg = "Select * From dogs";
NewJFrame frame1 = new NewJFrame();
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(sorg);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String species = rs.getString("species");
int age = rs.getInt("age");
String owner = rs.getString("owner");
String date = rs.getString("date");
System.out.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);
}
} catch (SQLException ex) {
Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and my list button in NewJFrame.java
private void listbuttonActionPerformed(java.awt.event.ActionEvent evt) {
Baglanti baglanti = new Baglanti();
// i don't know what next
Thanks.
So first, let's fix your doglist() method. I have Given it a PrintStream parameter so that it can be used with System.out but also with any other PrintStream. I have also taken out the "NewJFrame" creation. This shouldn't go there.
public void dogList(PrintStream stream) {
String sorg = "Select * From dogs";
//Take this out
//NewJFrame frame1 = new NewJFrame();
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(sorg);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String species = rs.getString("species");
int age = rs.getInt("age");
String owner = rs.getString("owner");
String date = rs.getString("date");
stream.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);
}
} catch (SQLException ex) {
Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Now, all you need is a PrintStream for a JTextField or a Dialog. And the easiest way to get this is to use a ByteArrayOutputStream and then convert that to a String and set it in the JComponent
ByteArrayOutputStream bstream = new ByteArrayOutputStream();
PrintStream myPS = new PrintStream(bstream);
dogList(myPS);
String msg = new String(bstream.getBytes());
Now you can use JTextField.setText(msg), or do something similar within your JFrame/Dialog.
It seems you do not need to create another instance of NewJFrame in dogList method of Baglanti class.
Also, it may be redundant to create an instance of Baglanti class in NewJFrame each time when you press on the button. It would suffice to have a single instance of this class responsible for retrieval of the data from the DB.
Next, you need to refactor the code of dogList method so that it begins to return a list of relevant data classes (e.g. Dog) to the caller. Then you'll be able to use this list in the frame and show its data as needed: in a text area, table, list, etc.
That being said, some code snippets:
// data transfer class Dog
public class Dog {
private int id;
private String name;
private String species;
private int age;
private String owner;
private String date;
// constructor with all args, getters/setters
}
import java.util.*;
public class Baglanti {
// ...
public List<Dog> dogList() {
String sorg = "Select * From dogs";
List<Dog> result = new ArrayList<>();
try (statement = con.createStatement()) { // use try-with-resources to make sure the statement is closed
ResultSet rs = statement.executeQuery(sorg);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String species = rs.getString("species");
int age = rs.getInt("age");
String owner = rs.getString("owner");
String date = rs.getString("date");
System.out.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);
// assuming all-args constructor is implemented in Dog
Dog dog = new Dog(id, name, species, age, owner, date);
result.add(dog);
}
} catch (SQLException ex) {
Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
// ... other methods
}
Remaining part in NewJFrame:
public class NewJFrame extends JFrame {
Baglanti baglanti = new Baglanti();
//... other UI components
private void listbuttonActionPerformed(java.awt.event.ActionEvent evt) {
List<Dog> dogs = baglanti.dogList();
for (Dog dog : dogs) {
// set information about the dog in other UI components
textArea.append(String.format("Dog id=%d named: %s, age %d years, owner: %s",
dog.getId(), dog.getName(), dog.getAge(), dog.getOwner()));
}
}
}
I'm doing a phone book project in Java, using MySql for school.
I wanted to print the methods using the Class.getDeclaredMethods();
adding them to a Vector of type String.
and invoke a menu() method that prints and accepts the option from the user using Scanner
the problem is that it always changes the methods places.
for example it can print
0.addPerson
1.deleteContact
2.searchByChar
and the next time
0.deleteContact
1.addPerson
2.searchByChar.
the problem is that i have a Switch case depend on it.
the menu function:
public static int menu(Vector<?> options){
System.out.println("The Options: ");
for (int i = 0; i < options.size(); i++) {
System.out.println(i + ". " + options.get(i));
}
Scanner scanner = new Scanner(System.in);
System.out.println("Your Choice: ");
String optionString = scanner.nextLine();
int option = 0;
if(isNumber(optionString)){
option = Integer.valueOf(optionString);
}else{
System.out.println("Please Choose Valid Option");
return menu(options);
}
return option;
}
the methods that get my methods:
public static Vector<String> getClassMethods(Class whichClass){
Method[] methods = whichClass.getDeclaredMethods();
Vector<String> stringMethods = new Vector<>();
for (Method method : methods) {
if(Modifier.toString(method.getModifiers()).equals("protected")){
stringMethods.add(method.getName());
}
}
return stringMethods;
}
my class the connects to the data base:
private boolean getData(Person person){
String sql = "SELECT * FROM " + DB_NAME + " WHERE name = '" + person.getName() + "' and phone_number = '" + person.getPhoneNumber() + "'";
try {
ResultSet resultSet = db.prepareStatement(sql).executeQuery();
if (resultSet.next()) {
return true;
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return false;
}
protected void addPerson(){
Person person = MyUtills.createPerson();
if(getData(person)){
System.out.println(person.getName() + ", " + person.getPhoneNumber() + ": Already in Contacts" );
}else{
add(person);
}
}
private void add(Person person) {
String pName = person.getName();
String pPhone = person.getPhoneNumber();
String pAddress = person.getAddress();
String sql = "INSERT INTO " + DB_NAME + " (name,phone_number,address)" +
"VALUES (?,?,?)";
try {
statement = db.prepareStatement(sql);
statement.setString(1,pName);
statement.setString(2,pPhone);
statement.setString(3,pAddress);
statement.execute();
System.out.println("Added Successfully");
} catch (SQLException e) {
e.printStackTrace();
}
}
//delete contact by name
protected void deleteContact(){
System.out.println("Enter Name Please");
String name = MyUtills.readStringFromUser();
Vector<Person> vector = checkMoreThanOne(name);
if(vector.size() > 1){
System.out.println("Choose One To Delete: ");
int option = menu(vector);
delete(vector.get(option));
}
System.out.println("Deleted");
}
private Vector<Person> checkMoreThanOne(String name) {
Vector<Person> vector = new Vector<>();
String sql = "SELECT * FROM " + DB_NAME;
try {
ResultSet resultSet = db.prepareStatement(sql).executeQuery();
while(resultSet.next()){
String pName = resultSet.getString("name");
String pPhone = resultSet.getString("phone_number");
String pAddress = resultSet.getString("address");
if(pName.equals(name)){
vector.add(new Person(pName,pPhone,pAddress));
}
}
return vector;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//deleting and existing contact;
private void delete(Person person){
String sql = "DELETE FROM " + DB_NAME + " WHERE name = '" + person.getName() + "' and phone_number = '" + person.getPhoneNumber() + "'";
try {
statement = db.prepareStatement(sql);
statement.execute();
System.out.println("Deleted Successfully");
} catch (SQLException e) {
e.printStackTrace();
}
}
//creating a new table for empty data base!
private void createTable() {
try {
statement = db.prepareStatement(SQL_TABLE_STRING);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void searchByFirstChar(Character character){
Vector<Person> personVector = new Vector<>();
String sql = "SELECT * FROM newphonebook";
try {
ResultSet resultSet = db.prepareStatement(sql).executeQuery();
while(resultSet.next()){
String name = resultSet.getString("name");
String phoneNum = resultSet.getString("phone_number");
String address = resultSet.getString("address");
if(character.equals(name.charAt(0))){
personVector.add(new Person(name,phoneNum,address));
}
}
System.out.println(personVector);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void getOptions(){
Vector<String> options = MyUtills.getClassMethods(DBWriterReader.class);
int option = MyUtills.menu(options);
switch (option){
case 0:
addPerson();
break;
case 1:
deleteContact();
break;
case 2:
// searchByFirstChar();
break;
}
}
}
I know it's not best written but I'm working on it to make it better
The Writing and Reading from the data base works fine, its the way it prints my methods that makes the problem..
If you need to guarantee the order of elements in a data structure, you don't use Vector -- it's not 1999 anymore. Look at the documentation for Vector. You get elements in the order determined by an iterator, not as they are stored.
Change your data structure to an ArrayList, which guarantees order. ArrayLists are also more performant in a single threaded application like yours, because unlike Vector, an ArrayList skips the overhead associated with being synchronized. Using the index of the ArrayList elements may also simplify the way you construct your switch statement.
I'm creating a method wherein a user can search a customer either by first name, last name, or full name. the search bar only shows the result if it's by first or last name but when I try searching a customer by full name the record won't show.
Here's my code:
public int getMatchingCustomerRecords(String keyword) {
int rows = 0;
try {
if (db.startTransaction()) {
String sql = "Select COUNT(firstName OR lastName) AS TOTAL FROM Customer";
String sqlSearch = "";
if (keyword != null) {
sqlSearch = sql + " WHERE firstName LIKE '%" + keyword + "%' AND lastName LIKE '%" + keyword + "%'";
ps = db.getQueryStatement(sqlSearch);
} else {
ps = db.getQueryStatement(sql);
}
rs = ps.executeQuery();
if (rs.next()) {
rows = rs.getInt("TOTAL");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
Your queries should be:
Select * FROM `Customer`
WHERE `firstName` LIKE '%" + keyword + "%' OR `lastName` LIKE '%" + keyword + "%'"
public int getMatchingCustomerRecords(String keyword) {
int rows = 0;
try {
if (db.startTransaction()) {
String sql = "Select COUNT(firstName OR lastName) AS TOTAL FROM Customer";
String sqlSearch = "";
if (keyword != null) {
String[] keywordArray=keyword.split(" ");
if(keywordArray.length>1) {
// matching full Name
sqlSearch = sql+" WHERE firstName LIKE '%" + keywordArray[0].trim() + "%' AND lastName LIKE '%" + keywordArray[1].trim() + "%'";
}else {
// matching firstName or lastName
sqlSearch = sql+" WHERE firstName LIKE '%" + keywordArray[0].trim() + "%' OR lastName LIKE '%" + keywordArray[0].trim() + "%'";
}
ps = db.getQueryStatement(sqlSearch);
} else {
ps = db.getQueryStatement(sql);
}
rs = ps.executeQuery();
if (rs.next()) {
rows = rs.getInt("TOTAL");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
public int getMatchingCustomerRecords(String keyword) {
int rows = 0;
try {
if (db.startTransaction()) {
String sql = "Select COUNT(firstName OR lastName) AS TOTAL FROM Customer";
String sqlSearch = "";
if (keyword != null) {
sqlSearch = sql + " WHERE LOCATE(firstName ,'" + keyword + "')>=0 AND LOCATE(lastName ,'" + keyword + "')>=0";
ps = db.getQueryStatement(sqlSearch);
} else {
ps = db.getQueryStatement(sql);
}
rs = ps.executeQuery();
if (rs.next()) {
rows = rs.getInt("TOTAL");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
I have a JDBC program that takes records from a MySQL database and prints out the results. The user can select which results they want from the database by selecting different checkboxes to only display certain results.
Here is the method which gets the records and prints them out:
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
result += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
result += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
result += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
result += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
result += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
result += zip + " ";
}
// print the results
}
System.out.println(result);
results.setText(result);
stmt.close();
}
Currently, if I were to select say the first three checkboxes, I would get the output:
1 Smith, Tim 12 Elm St 2 Jones, Tom 435 Oak Dr 3 Avery, Bill 623 Ash Ave 4 Kerr, Debra 1573 Yew Crt
However, the output I am after is:
1, Smith, Tim, 12 Elm St
2, Jones, Tom, 435 Oak Dr
3, Avery, Bill, 623 Ash Ave
4, Kerr, Debra, 1573 Yew Crt
Is there any way I can add a new line after each record in the database, as well as maybe the commas in between items in each record? I am new to JDBC and MySQL connectivity, so any help or tips is appreciated.
You can print every single result just before the end of while loop, then it'll print every record in new line.
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
String singleResult = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
singleResult += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
singleResult += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
singleResult += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
singleResult += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
singleResult += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
singleResult += zip + " ";
}
System.out.println(singleResult);
result +=singleResult;
}
//System.out.println(result);
results.setText(result);
stmt.close();
}
Or you can append line separator, just before closing while loop
System.out.println(singleResult);
result +=singleResult;
result +="\n";
First, I would use a StringJoiner to gather the elements. Then, I would eliminate the many local temporary variables. Finally, I would use println in the loop and another StringJoiner for the final result. Like,
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
StringJoiner result = new StringJoiner(System.lineSeparator());
while (rs.next()) {
StringJoiner lineJoiner = new StringJoiner(", ");
if (cb1.isSelected()) {
lineJoiner.add(String.valueOf(rs.getInt("custid")));
}
if (cb2.isSelected()) {
lineJoiner.add(rs.getString("name"));
}
if (cb3.isSelected()) {
lineJoiner.add(rs.getString("address"));
}
if (cb4.isSelected()) {
lineJoiner.add(rs.getString("city"));
}
if (cb5.isSelected()) {
lineJoiner.add(rs.getString("state"));
}
if (cb6.isSelected()) {
lineJoiner.add(String.valueOf(rs.getInt("zip")));
}
System.out.println(lineJoiner);
result.add(lineJoiner.toString());
}
results.setText(result.toString());
stmt.close();
}
You could also do the same thing with Collection(s) like,
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
List<String> msg = new ArrayList<>();
while (rs.next()) {
List<String> al = new ArrayList<>();
if (cb1.isSelected()) {
al.add(String.valueOf(rs.getInt("custid")));
}
if (cb2.isSelected()) {
al.add(rs.getString("name"));
}
if (cb3.isSelected()) {
al.add(rs.getString("address"));
}
if (cb4.isSelected()) {
al.add(rs.getString("city"));
}
if (cb5.isSelected()) {
al.add(rs.getString("state"));
}
if (cb6.isSelected()) {
al.add(String.valueOf(rs.getInt("zip")));
}
String line = al.stream().collect(Collectors.joining(", "));
System.out.println(line);
msg.add(line);
}
results.setText(msg.stream().collect(Collectors.joining(System.lineSeparator())));
stmt.close();
Prefer whichever you find most readable.
I would like to send a broadcast message to all numbers returned from the select statement. It saves elements in the list but then it sends the same message to everyone. What am I doing wrong? Please see my method below.
public static List<Message> listAllMessages(Connection connection) {
List<Message> msg = new ArrayList<Message>();
String messages = ReturnTexts.getMessage(connection, "EMPTYMESSAGE");
String sql = "SELECT b.`productid` as productid, p.`productname` as productname, b.`msisdn` as msisdn , MAX(b.`amount`) as amount, b.`productcode` as productcode, a.`endDate` as enddate FROM "
+ TableNames.SAVEDBIDSTABLE
+ "b LEFT JOIN "
+ TableNames.PRODUCTTABLE1
+ " p ON b.`productcode`= p.`code` "
+ " JOIN "
+ TableNames.AUCTIONTABLE1
+ " a"
+ " ON b.`productcode`= a.`productcode` "
+ "GROUP BY msisdn, productcode ";
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
if (connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
// LOGGER.info(sql);
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
// statement = connection.createStatement();
resultSet = statement.executeQuery();
long productid = 0;
String productname = null;
String msisdn = null;
int amount = 0;
String productcode = null;
Date enddate = null;
while (resultSet.next()) {
productid = resultSet.getLong("productid");
productname = resultSet.getString("productname");
msisdn = resultSet.getString("msisdn");
amount = resultSet.getInt("amount");
productcode = resultSet.getString("productcode");
enddate = resultSet.getTimestamp("enddate");
msg.add(new Message(Long.valueOf(productid), productname,
msisdn, amount, productcode, String.valueOf(enddate)));
}
String messages = ReturnTexts
.getMessage(connection, "BROADCAST")
.replace("XXXX", productname)
// .replace("YYYY", String.valueOf(amount))
.replace("YYYY",
String.valueOf(maxBid(productcode, connection)))
.replace("ZZZZ", String.valueOf(enddate));
//LOGGER.info(messages.toString());
try {
for (Message obj : msg) {
obj.setMessage(messages);
String apiUrl = "url/sendsms.jsp";
getResponse(apiUrl + "?" + "user="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&password="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&mobiles=" + obj.getMsisdn() + "&sms="
+ URLEncoder.encode(obj.getMessage(), "UTF-8"));
//bulkMessagesLog(obj.getMsisdn(), obj.getMessage(),obj.getProductcode(), connection);
bulkMessagesLog(productcode, msisdn, productname, connection);
//LOGGER.info(obj.getMsisdn() + " : " + obj.getProductcode()+ " : " + obj.getMessage());
}
} catch (UnsupportedEncodingException e) {
System.err
.println("UnsupportedEncodingException while trying to send SMS.");
e.getMessage();
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
} finally {
DBConnection.closeAllDBUsage(resultSet, statement, null);
}
return msg;
}
public static void bulkMessagesLog(String msisdn, String message,String productcode,
Connection connection) {
PreparedStatement statement = null;
String sql = "INSERT INTO " + TableNames.BULK_MESSAGESLOGTABLE
+ "(`msisdn`,`message`,`productcode`,`dateCreated`) VALUES(?,?,?,now()) ";
try {
if ( connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
statement.setString(1, msisdn);
statement.setString(2, message);
statement.setString(3, productcode);
//statement.addBatch();
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
DBConnection.closeAllDBUsage(null, statement, connection);
}
}
You do iterate over the result set and build a list of messages in msg. Though you only create the text once, outside of the loop, so it's always the same with the (last) productname etc.
Should probably also be created in the loop.