I'm working on my application where I want to update my table after email has been sent. I created function that connect sql database and java, also in other class I created function that updates table but what I need is these two classes together. I want to use my array-list after execution for updating of my table.
Here is my code for connection and sending emails:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class TestSendEmails {
private String emailTo;
private String emailSubject;
private String emailBody;
private String emailAttachments;
private Integer RecordId;
public TestSendEmails(){
}
public TestSendEmails(String emailTo, String emailSubject, String emailBody, String emailAttachments, Integer RecordId){
super();
this.emailTo = emailTo;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
this.emailAttachments = emailAttachments;
this.RecordId = RecordId;
}
public String getEmailTo(){
return emailTo;
}
public void setEmailTo(String emailTo){
this.emailTo = emailTo;
}
public String getEmailSubject(){
return emailSubject;
}
public void setEmailSubject(String emailSubject){
this.emailSubject = emailSubject;
}
public String getEmailBody(){
return emailBody;
}
public void setEmailBody(String emailBody){
this.emailBody = emailBody;
}
public String getEmailAttachments(){
return emailAttachments;
}
public void setEmailAttachments(String emailAttachments){
this.emailAttachments = emailAttachments;
}
public Integer getRecordId(){
return RecordId;
}
public void setRecordId(Integer RecordId){
this.RecordId = RecordId;
}
}
class TestSendEmailD{
private Connection con;
private static final String GET_EMAILS = "Select* From Emails";
private void connect() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:sqlserver://100.000.000.00\\:3333;databaseName=Test;user=mmmm;password=1234");
}
public List<TestSendEmails> getTestSendEmails() throws Exception{
connect();
PreparedStatement ps = con.prepareStatement(GET_EMAILS);
ResultSet rs = ps.executeQuery();
List<TestSendEmails> result = new ArrayList<TestSendEmails>();
while(rs.next()){
result.add(new TestSendEmails(rs.getString("emailTo"), rs.getString("emailSubject"),rs.getString("emailBody"),rs.getString("emailAttachments",rs.getInt("RecordId"))));
}
disconnect();
return result;
}
private void disconnect() throws SQLException{
if(con != null){
con.close();
}
}
}
class EmailSender{
private Session session;
private void init(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "100.000.000.00");
props.put("mail.smtp.port", "678");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("test#gmail.com", "123");
}
});
}
public void sendEmail(TestSendEmails s) throws MessagingException{
init();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("test#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo().replace(";", ",")));
message.setSubject(s.getEmailSubject());
message.setText(s.getEmailBody());
message.setContent(s.getEmailBody(),"text/html");
Transport.send(message);
System.out.println("Done");
}
public void sendEmail(List<TestSendEmails> emails) throws MessagingException{
for(TestSendEmails TestSendEmails:emails ){
sendEmail(TestSendEmails);
}
}
}
Here is my Update code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Date;
public class UpdateEmail {
public static Connection getConnection() throws Exception {
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String url = "jdbc:sqlserver://100.000.000.00\\:3333;databaseName=Test";
String username = "mmmm";
String password = "1234";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) throws Exception {
java.util.Date date = new Date();
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "update Emails set SentOn = ? where Id = ? ";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
pstmt.setInt(2, 200); // In this line I want to use my array-list to update my table.
pstmt.executeUpdate(); // execute update statement
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
pstmt.close();
conn.close();
}
}
}
I'm not sure if I have to create new connection for my update in my second program and where I should implement my update code. If you know what I should change please let me know. Thanks in advance.
Main.java code:
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
TestSendEmailD dao=new TestSendEmailD();
List<TestSendEmails> list=dao.getTestSendEmails();
EmailSender sender=new EmailSender();
sender.sendEmail(list);
}
}
I guess you have an ArrayList() called yourList. The following code goes before
String query ...
StringBuilder ids = "";
String prefix ="";
for (Integer id: yourList) {
append(prefix);
prefix = ",";
ids.append(String.valueOf(id));
}
change your query to:
String query = "update Emails set SentOn =? where Id in (" + ids.toString() + ")";
and send only the SentOn as parameter:
pstmt.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
Connection conn = null;
PreparedStatement pstmt = null;
conn = getConnection();
java.util.Date date = new Date();
message.setFrom(new InternetAddress("test#gmail.com"));
String query = "update Emails set SentOn = ? where Id = ? ";
pstmt = conn.prepareStatement(query); // create a statement
String str[]=String.valueOf(s.getRecordId()).split(";");//id1;id;id3;....
for(int i=0;i<str.length();i++)
{
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo().replace(";", ",")[i]));
message.setSubject(s.getEmailSubject());
message.setText(s.getEmailBody());
message.setContent(s.getEmailBody(),"text/html");
Transport.send(message);
System.out.println("Done");
pstmt.setTimestamp(1, new java.sql.Timestamp(date.getTime()));
pstmt.setInt(2, str[i]); // In this line I want to use my array-list to update my table.
pstmt.executeUpdate(); // execute update statement
System.out.println(str[i]+" "+s.getEmailTo().replace(";", ",")[i]+" "+new java.sql.Timestamp(date.getTime()));//to check whether its working or not.
}
Its exactly not an exact answer. check whether its working or not. Here you must take care of exceptions also. I didn't written that code here.
Related
I've been working at this for almost a day and a half now and I can't seem to work this error out. I don't know why the ResultSet is being closed. Maybe some of you can help me out.
MySQLDatabase:
package net.gielinor.network.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public abstract class MySQLDatabase {
private String host;
private String database;
private String username;
private String password;
private Connection connection = null;
private Statement statement;
public MySQLDatabase(String host, String database, String username, String password) {
this.host = host;
this.database = database;
this.username = username;
this.password = password;
}
public abstract void cycle() throws SQLException;
public abstract void ping();
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(String.format("jdbc:mysql://%s/%s", host, database), username, password);
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ping(String table, String variable) {
try {
statement.executeQuery(String.format("SELECT * FROM `%s` WHERE `%s` = 'null'", table, variable));
} catch (Exception e) {
connect();
}
}
public ResultSet query(String query) throws SQLException {
if (query.toLowerCase().startsWith("select")) {
return statement.executeQuery(query);
} else {
statement.executeUpdate(query);
}
return null;
}
public Connection getConnection() {
return connection;
}
}
MySQLHandler
package net.gielinor.network.sql;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import net.gielinor.network.sql.impl.MySQLDonation;
public class MySQLHandler extends Thread {
private static final MySQLHandler mysqlHandler = new MySQLHandler();
public static MySQLHandler getMySQLHandler() {
return mysqlHandler;
}
private static List<MySQLDatabase> updateList;
private static String host;
private static String database;
private static String username;
private static String password;
#Override
public void run() {
while (true) {
for (MySQLDatabase database : updateList) {
try {
if (database.getConnection() == null) {
database.connect();
} else {
database.ping();
}
database.cycle();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (Exception ex) {
}
}
}
}
private static void loadProperties() {
Properties p = new Properties();
try {
p.load(new FileInputStream("./sql.ini"));
host = p.getProperty("host");
database = p.getProperty("database");
username = p.getProperty("username");
password = p.getProperty("password");
} catch (Exception ex) {
System.out.println("Error loading MySQL properties.");
}
}
public static String getHost() {
return host;
}
static {
loadProperties();
updateList = new ArrayList<MySQLDatabase>();
updateList.add(new MySQLDonation(host, database, username, password));
}
}
MySQLDonation
package net.gielinor.network.sql.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.gielinor.game.model.player.Client;
import net.gielinor.game.model.player.PlayerHandler;
import net.gielinor.game.model.player.PlayerSave;
import net.gielinor.network.sql.MySQLDatabase;
public final class MySQLDonation extends MySQLDatabase {
public MySQLDonation(String host, String database, String username, String password) {
super(host, database, username, password);
}
#Override
public void cycle() throws SQLException {
ResultSet results = query("SELECT * FROM `gieli436_purchases`.`donations`");
if (results == null) {
return;
}
while (results.next()) {
String username = results.getString("username").replace("_", " ");
System.out.println("name=" + username);
Client client = (Client) PlayerHandler.getPlayer(username.toLowerCase());
System.out.println(client == null);
if (client != null && !client.disconnected) {
int creditamount = results.getInt("creditamount");
if (creditamount <= 0) {
continue;
}
handleDonation(client, creditamount);
query(String.format("DELETE FROM `gieli436_purchases`.`donations` WHERE `donations`.`username`='%s' LIMIT 1", client.playerName.replaceAll(" ", "_")));
}
}
}
#Override
public void ping() {
super.ping("donations", "username");
}
private void handleDonation(Client client, int creditamount) throws SQLException {
client.credits = (client.credits + creditamount);
client.sendMessage("Thank you for your purchase. You have received " + creditamount + " store credits.");
PlayerSave.save(client);
}
}
The exception occurs here: in the while loop within MySQLDonation and the actual stacktrace is this:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7077)
at net.gielinor.network.sql.impl.MySQLDonation.cycle(Unknown Source)
at net.gielinor.network.sql.MySQLHandler.run(Unknown Source)
With this information let me say that this does work, I get my message and what not in-game but it repeats, like the user is never removed from the query so it gives them infinite rewards. If you need any more information feel free to ask.
When you run the Delete query, you use the same Statement that was used in the Select query. When you re-execute on the same Statement, the previous ResultSet gets closed.
To avoid this, you should create a new Statement everytime you execute a query. So remove statement = connection.createStatement(); from the connect() method in MySQLDatabase class, and replace all statement in that class to connection.createStatement(). You may also choose to delete the private variable statement altogether.
You can read more about it here.
this error is some time occur when we use same statement object for diff. types
check Statement objectsss;
I have a login app that needs to connect to a server to check the username and password. I am using netbeans and the jbdc is installed and working in the services tab(thanks stack overflow!). By the jbdc is work I mean that i can execute SQL script through it.
I have set this up with MS Server 16 and MySQL so I am convied it is the code:
Connection method:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
private static final String USERNAME = "root";
private static final String PASSWORD = "mess";
private static final String SQCONN = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection()throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(SQCONN, USERNAME, PASSWORD);
}catch (ClassNotFoundException e) {
}
return null;
}
}
loginmodel:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
Connection connection;
public LogInModel() {
try{
this.connection = dbConnection.getConnection();
}catch(SQLException e){
}
if(this.connection == null){
System.out.println("here");
// System.exit(1);
}
}
public boolean isDatabaseConnected(){
return this.connection != null;
}
public boolean isLogin(String username, String password) throws Exception{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
try{
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
boolean bool1;
if(rs.next()){
return true;
}
return false;
}
catch(SQLException ex){
return false;
}
finally {
{
pr.close();
rs.close();
}
}
}
}
I believe the issue is the return null; from the dbConnection file. The if(this.connection==Null) comes back true and the system is exiting.
Thank you in advance.
Your dbConnection class is a bad idea. Why hard wire those values when you can pass them in?
Your application will only have one Connection if you code it this way. A more practical solution will use a connection pool.
Learn Java coding standards. Your code doesn't follow them; it makes it harder to read and understand.
Here's a couple of recommendations:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "root";
public static final String PASSWORD = "mess";
public static final String URL = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
I might write that LogInModel this way:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
private static final String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
private Connection connection;
public LogInModel(Connection connection) {
this.connection = connection;
}
public boolean isLogin(String username, String password) {
boolean isValidUser = false;
PreparedStatement pr = null;
ResultSet rs = null;
try {
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
while (rs.hasNext()) {
isValidUser = true;
}
} catch (SQLException ex) {
e.printStackTrace();
isValidUser = false;
} finally {
dbUtils.close(rs);
dbUtils.close(pr);
}
return isValidUser;
}
}
Here's my guess as to why your code fails: You don't have the MySQL JDBC driver JAR in your runtime CLASSPATH. There's an exception thrown when it can't find the driver class, but you didn't know it because you swallowed the exception.
Here is my app that use SQL database to pull emails from and then send those emails with java app. For some reason I'm getting this error:
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ''. ClientConnectionId:85cbe035-a937-4f1a-81eb-69f5b7684049
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:215)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:251)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:3004)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:2286)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:2272)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5846)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1719)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1330)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:995)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:831)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at TestSendEmailD.connect(TestSendEmails.java:72)
at TestSendEmailD.getTestSendEmails(TestSendEmails.java:76)
at Main.main(Main.java:6)
Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class TestSendEmails {
private String emailTo;
private String emailSubject;
private String emailBody;
private String emailAttachments;
public TestSendEmails(String emailTo, String emailSubject, String emailBody, String emailAttachments){
super();
this.emailTo = emailTo;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
this.emailAttachments = emailAttachments;
}
public String getEmailTo(){
return emailTo;
}
public void setEmailTo(String emailTo){
this.emailTo = emailTo;
}
public String getEmailSubject(){
return emailSubject;
}
public void setEmailSubject(String emailSubject){
this.emailSubject = emailSubject;
}
public String getEmailBody(){
return emailBody;
}
public void setEmailBody(String emailBody){
this.emailBody = emailBody;
}
public String getEmailAttachments(){
return emailAttachments;
}
public void setEmailAttachments(String emailAttachments){
this.emailAttachments = emailAttachments;
}
}
class TestSendEmailD{
private Connection con;
private static final String GET_EMAILS = "Select * From Emails";
private void connect() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:sqlserver://100.000.000\\SQLEXPRESS:2233;databaseName=Emails");
}
public List<TestSendEmails> getTestSendEmails() throws Exception{
connect();
PreparedStatement ps = con.prepareStatement(GET_EMAILS);
ResultSet rs = ps.executeQuery();
List<TestSendEmails> result = new ArrayList<TestSendEmails>();
while(rs.next()){
result.add(new TestSendEmails(rs.getString("emailTo"), rs.getString("emailSubject"),rs.getString("emailBody"),rs.getString("emailAttachments")));
}
disconnect();
return result;
}
private void disconnect() throws SQLException{
if(con != null){
con.close();
}
}
}
class EmailSender{
private Session session;
private void init(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "100.00.00.000.0");
props.put("mail.smtp.port", "666");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("aaaa", "5555");
}
});
}
public void sendEmail(TestSendEmails s) throws MessagingException{
init();
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mmmm#gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(s.getEmailTo()));
message.setSubject(s.getEmailSubject());
message.setText(s.getEmailBody());
Transport.send(message);
}
public void sendEmail(List<TestSendEmails> emails) throws MessagingException{
for(TestSendEmails TestSendEmails:emails ){
sendEmail(TestSendEmails);
}
}
}
here is my main.java class:
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
TestSendEmailD dao=new TestSendEmailD();
List<TestSendEmails> list=dao.getTestSendEmails();
EmailSender sender=new EmailSender();
sender.sendEmail(list);
}
}
I'm not sure if this is the right way to do this. If anyone knows better way please let me know. Thanks in advance.
Your error is entirely database authentication related and has nothing to do with mail.
Login failed for user ''
Your SQL connection string doesn't contain any authentication information:
jdbc:sqlserver://100.000.000\\SQLEXPRESS:2233;databaseName=Emails
There is a guide on how to build a JDBC connection string for SQL Server here.
I am writing a code to make a list in JComboBox using the data in the database.
It's actually for a POS system, where i have to select an item from a list in the database..
Here is the code i have been trying:
(i did take try it without the while(itemsList != null) .. but it didnt work either
private class ButtonHandlerSales implements ActionListener
{
public final String userName = "root";
private final String password = "";
private final String serverName = "localhost";
private final int portNumber = 3306;
private final String dbName = "alphapos";
public void actionPerformed(ActionEvent action)
{
Connection conn = null;
try
{
conn = this.getConnection();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
//System.out.println("Connected to database");
while(itemsList != null)
{
String[] list= null;
String command = "SELECT itemName FROM item";
try
{
list = viewTable(conn, command);
}
catch (SQLException e)
{
e.printStackTrace();
}
itemList = new JComboBox(list);
}
}
private String[] viewTable(Connection con, String command) throws SQLException
{
String list[] = null;
Statement stmt = null;
try
{
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(command);
int i=0;
while (rs.next())
{
list[i] = rs.getString("itemName");
i++;
}
}
catch (SQLException e )
{
e.printStackTrace();
}
finally
{
if (stmt !=
null) { stmt.close(); }
}
return list;
}
private Connection getConnection() throws SQLException
{
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
conn = DriverManager.getConnection("jdbc:mysql://"
+ this.serverName + ":" + this.portNumber + "/" + this.dbName,
connectionProps);
return conn;
}
}//end of class
I'm not getting any errors.. the code compiles.. but im not getting any output (list is empty)..
Am i doing something wrong here?
Any help is really appreciated... ( im not looking for straight up codes )
Problem 1
In your viewTable method String list[] = null;. You never initialize it with a new String[..]. So you will new a NullPointerException. But it would be better to use an ArrayList, since you may not know exactly how many values will be returned
private List<String> viewTable(Connection con, String command) {
List<String> list = new ArrayList<>();
...
while (rs.next()) {
list.add(rs.getString("itemName"));
}
return list;
}
Problem 2
You are creating the JComboBox in the ActionListener. So you can't add the combo before the action is performed. With combo boxes, it's preferred to work with it's model, rather then the component, when working with the data. JComboBox has a ComboBoxModel. We can use the concrete DefaultComboBoxModel. You can pass an array to its constructor. List, has the method toArray we can call to create an array from the List. Then just pass the array to the DefaultComboBoxModel constructor and call the combo box setModel
List<String> list = null;
String command = "SELECT itemName FROM item";
try {
list = viewTable(conn, command);
} catch (SQLException e) {
e.printStackTrace();
}
ComboBoxModel model = new DefaultComboBoxModel(list.toArray());
itemList.setModel(model);
This way, you can initialize the combo box before the action is performed.
Update
If you want the combo box loaded on application start up, I don't see what the problem is. Just create a method in you class, using the code in the actionPerformed. Then just call that method, like in your main constructor or something. Maybe you could do something like below, where you have the method return a ComboBoxModel and you can use to set the model for the combo box
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Test {
private final JComboBox itemList;
public Test() throws SQLException {
itemList = new JComboBox(viewTable(getConnection(), command));
JButton button = new JButton("Populate");
button.addActionListener(new ButtonHandler());
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(itemList);
panel.add(button);
JOptionPane.showMessageDialog(null, panel);
}
private class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
try {
ComboBoxModel model = viewTable(getConnection(), command);
itemList.setModel(model);
} catch (SQLException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) throws SQLException {
Test test = new Test();
}
private ComboBoxModel viewTable(Connection con, String command) throws SQLException {
List<String> list = new ArrayList<>();
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(command);
while (rs.next()) {
list.add(rs.getString("itemName"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return new DefaultComboBoxModel(list.toArray());
}
public final String userName = "root";
private final String password = "";
private final String serverName = "localhost";
private final int portNumber = 3306;
private final String dbName = "alphapos";
private final String command = "select itemName from item";
private Connection getConnection() throws SQLException {
Connection conn = null;
Properties connectionProps = new Properties();
connectionProps.put("user", this.userName);
connectionProps.put("password", this.password);
conn = DriverManager.getConnection("jdbc:mysql://"
+ this.serverName + ":" + this.portNumber + "/" + this.dbName,
connectionProps);
return conn;
}
}
I want to connect with mysql db by using host, username, password from file aplikacja.properties. But I have problem bcs those method return null and I don't know why ?
getHost()
getUsername()
getPassword()
getDb()
package aplikacja.mysql;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class Mysql {
private String host;
private String username;
private String password;
private String db;
public void readConnectionParam() throws FileNotFoundException, IOException {
Properties mysqlAplikacjaProperties = new Properties();
FileInputStream mysqlPlik = new FileInputStream("aplikacja.properties");
mysqlAplikacjaProperties.load(mysqlPlik);
host = mysqlAplikacjaProperties.getProperty("jdbc.host");
username = mysqlAplikacjaProperties.getProperty("jdbc.username");
password = mysqlAplikacjaProperties.getProperty("jdbc.password");
db = mysqlAplikacjaProperties.getProperty("jdbc.db");
}
public String getHost() {
return host;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getDb() {
return db;
}
public static void main(String[] args) throws SQLException {
Mysql baza = new Mysql();
System.out.println(baza.getUsername());
Connection polaczenie = null;
String driver = "com.mysql.jdbc.Driver";
try {
Class.forName(driver).newInstance();
polaczenie = DriverManager.getConnection(
"jdbc:mysql://" + baza.getHost() + "/" + baza.getDb(),
baza.getUsername(), baza.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
Statement statement = polaczenie.createStatement();
String command = "INSERT INTO users (id, name, surname) VALUES (2, 'Tom', 'Suszek')";
statement.executeUpdate(command);
}
}
Thanks for help.
I don't see any code that calls the readConnectionParam method, which is the only thing that can initialize the variables that are returned in your methods that are returning null. Call it.
You have to call readConnectionParam() Method since thesse fields are initialized here.
Try:
Mysql baza = new Mysql();
baza.readConnectionParam();
System.out.println(baza.getUsername());
Include the above code in a try catch since the method readConnectionParam() throws Exceptions
You should first initialize your vars calling the method
readConnectionParam
inside the main
use -
baza.readConnectionParam();
after
Mysql baza = new Mysql();
statement.