Send message to multiple recipients on Java | Javax.mail - java

My code only sends either the first or the last email, i dont even know why is that.
below is my code
// Fetch the emails on the database
List<String> emails = new ArrayList<>();
try(Connection connection = connect();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT email FROM user")){
// Get the emails from the database
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String email = resultSet.getString("email");
emails.add(email);
}
}catch (Exception e){
System.out.println(e.getMessage());
}
// Setting the recipients
for (String email : emails) {
msg.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(email, false));
}
I've tried making it an array of string but it still the same

Alright, I fixed it by changing the arguments take by my List as follows:
Just posting here for future reference if someone else gets in the same problem
//Fetching the email on the database
List<InternetAddress> emails = new ArrayList<>();
try(Connection connection = connect();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT email FROM user")){
// Get the emails from the database
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String email = resultSet.getString("email");
emails.add(new InternetAddress(email, false));
}
}catch (Exception e){
System.out.println(e.getMessage());
}
// Setting the recipients
InternetAddress[] recipients = emails.toArray(new InternetAddress[emails.size()]);
msg.setRecipients(Message.RecipientType.BCC, recipients);

Related

How can I pass integer into string for sql query

I have written a program that extracts data from an SQL table:
String url = "jdbc:mysql://localhost/petcare";
String password = "ParkSideRoad161997";
String username = "root";
// Step 2: Making connection using
// Connection type and inbuilt function on
// Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
// Try block to catch exception/s
try {
Connection con = DriverManager.getConnection(url, username, password);
// SQL command data stored in String datatype
String sql = "select * from inbox";
p = con.prepareStatement(sql);
rs = p.executeQuery();
// Printing ID, name, email of customers
// of the SQL command above
System.out.println("inboxId");
int inboxId;
// Condition check
while (rs.next()) {
inboxId = rs.getInt("InboxId");
// System.out.println(inboxId);
}
String sql2 = "select * from message where inboxId = int";//this is where i need help
p = con.prepareStatement(sql2);
rs = p.executeQuery();
// Printing ID, name, email of customers
// of the SQL command above
System.out.println("Inbox:");
}
// Catch block to handle exception
catch (SQLException e) {
// Print exception pop-up on screen
System.out.println(e);
}
Once I get the inboxId, I want to run sql2 and pass inboxId as int. How can I do this. Each user will have a different inboxId so thats why to get the user inbox I want to extract and messages in the message table that are meant for inboxId of the user.
I tried the query string sql and it works now I just need to fix String sql2.
String sql2 = "select * from message where inboxId = " + 1234;
1234 could be a variable. You could also use String.format() to do it as well.
String sql2 = String.format("select * from message where inboxId = %d", 1234);
Try this:
String sql2 = "select * from message where inboxId = ?"; //The ? indicates a variable in the prepared statement.
p = con.prepareStatement(sql2);
p.setInt(1, inboxId);
rs = p.executeQuery();

JAVA GUI - GET and SHOW DATA FROM MYSQL

I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.

SQL Query Java Net Beans

Basically I have a table name java_db.Customer with the columns CustomerID,
Name, Address and FinanceOK.
Basically I want to write a simple query that says if FinanceOK = true JOptionPane.ShowMessage "Finance Accepted"
Otherwise FinanceOK = False JOptionPane.ShowMessage "Finance Declined".
What is the the best way to go about writing this query?
Now, there's a lot of information in your post that is missing but down and dirty here is how you might accomplish the task:
long customerID_Variable = 232; // .... whatever you have to provide customer ID number ....
String customerName = "John Doe"; // .... whatever you have to provide customer name ....
boolean financeOK = false; // default financing approval flag
String message = "Finance Declined!"; //default message
// Catch SQLException if any...
try {
// Use whatever your connection string might be
// to connect to your particular Database....
Connection conn = DriverManager.getConnection("jdbc:derby:c:/databases/salesdb jdbc:derby:salesdb");
conn.setAutoCommit(false);
// The SQL query string...
String sql = "SELECT FinanceOK FROM Customer WHERE CustomerID = " + customerID_Variable + ";";
// Although it is best to use the Customer ID to reference a
// particular Customer you may prefer to to use the Customer
// name and if so then use the query string below instead...
// String sql = "SELECT FinanceOK FROM Customer WHERE Name = '" + customerName + "';";
// Execute the SQL query...
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
//Retrieve the data from the query result set...
while (rs.next()) {
financeOK = rs.getBoolean("FinanceOK");
}
//Close everything...
rs.close();
stmt.close();
conn.close();
}
catch (SQLException ex) { ex.printStackTrace(); }
int msgIcon = JOptionPane.ERROR_MESSAGE;
if (financeOK) {
message = "Finance Accepted!";
msgIcon = JOptionPane.INFORMATION_MESSAGE;
}
JOptionPane.showMessageDialog(null, message, "Financing Approval...", msgIcon);

java.sql.SQLException:Access denied for user

I have MySQL database "database" in my web. I want to connect it remotly from java. But I get Exception.
I use this code to connect it.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://site.ir:3306/database", username", "password");
Statement st = con.createStatement();
String sql = ("SELECT * FROM users ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if(rs.next()) {
int id = rs.getInt("id");
String str1 = rs.getString("imei");
System.out.print(id+"+++"+str1);
}
con.close();
}catch(Exception e){
e.printStackTrace();
}
I think there's no problem in my code and username has All permission to access database! Please say what's problem!

How do I verify password entered is the password associated with entered email?

Hey I am trying to verify the password matches the one they entered with the email I have been searching for the web for a few hours and everything else I have tried does not work this is what i have so far:
try {
Class.forName(driver).newInstance();
Connection conn = (Connection) DriverManager.getConnection
(url + dbName, userName, password);
PreparedStatement checkUserInfo = (PreparedStatement) conn.prepareStatement
("SELECT password FROM profiles WHERE email = ?");
checkUserInfo.setString(1, emailT); //emailT is email pulled from an editText
//checkUserInfo.setString(2, pass1);
//Statement state = (Statement) conn.createStatement();
//String querychk = "SELECT * FROM profiles WHERE email = '"+emailT+"'";
//ResultSet rs = state.executeQuery(querychk);
ResultSet rs = checkUserInfo.executeQuery();
while (rs.next()){
String pass = rs.getString(2);
if (pass.equals(pass1)) {
return success;
}
}
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
Simply modify your SQL Query to:
"select * from profiles where email=? and password=?"
And be-aware to validate input fields for preventing from SQL injection
And for getting PreparedStatement object or Connection object, you don't have to externally typecast it, cause it is returning the same object as you assigning to it. Even java doc also provided the below statement for the PreparedStatement
PreparedStatement pstmt = con.prepareStatement(Query);

Categories

Resources