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;
}
}
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 want to get the list of all database names from a Sybase DB server. I can connect the Sybase db through Java, but don't know how to get the list of database names. I am using jconn4 jar file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.SybDriver;
public class ConnectToSybase {
public static Connection conn = null;
public static Statement stmt = null;
public static SybDriver sybDriver = null;
public static ResultSet rs = null;
public static String dbServerIP = "10.10.10.11";
public static String portNo = "5000";
public static String dbName = "NewDB";
public static void main(String[] args) {
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
conn = DriverManager.getConnection("jdbc:sybase:Tds:" + dbServerIP + ":" + portNo, "usrname", "password");
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("In exception");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}
}
I found myself a working code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.SybDriver;
public class ConnectToSybase {
public static Connection conn = null;
public static Statement stmt = null;
public static SybDriver sybDriver = null;
public static ResultSet rs = null;
public static String dbServerIP = "10.10.10.11";
public static String portNo = "5000";
public static String dbName = "NewDB";
public static void main(String[] args) {
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
conn = DriverManager.getConnection("jdbc:sybase:Tds:" + dbServerIP + ":" + portNo, "usrname", "password");
stmt = conn.createStatement();
List<String> dbList = new ArrayList<String>();
// getting list of DB names from the DB server
ResultSet rs = conn.getMetaData().getCatalogs();
while (rs.next()) {
dbList.add(rs.getString(1));
}
for (String list : dbList) {
System.out.println(list);
}
} catch (Exception e) {
System.out.println("In exception");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}
}
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.
Edited Question
When I click the delete button, The row in the table gets deleted in GUI but not from database in mysql server.
Here's the code:
// DatabaseStore. This part runs fine.
public class DatabaseStore {
private final String server = "jdbc:mysql://localhost/";
private final String database = "music_magic";
private final String user_name = "root";
private final String pass_word = "";
private final String driver = "com.mysql.jdbc.Driver";
public Connection doConnection() {
Connection c;
try {
//load the driver
Class.forName(driver);
c = DriverManager.getConnection(server + database, user_name, pass_word);
// JOptionPane.showMessageDialog(null, "Database connected");
} catch (Exception e) {
c = null;
JOptionPane.showMessageDialog(null, "Error : " + e.getMessage());
}
return c;
}
//
// Imports
import Database_music.DatabaseStore; //main database page where i connect to database
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import magic_music.Items; //ignore this
//...
// Subject method
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(jTable1.getSelectedRow() >=0){
try{
DatabaseStore dtbs = new DatabaseStore();
Connection cn = dtbs.doConnection();
Statement stat = cn.createStatement();
String sql = "DELETE FROM products_info WHERE Product_id ='"+jTable1.getSelectedRow() +"'";
stat.executeUpdate(sql);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.removeRow(jTable1.getSelectedRow());
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
JOptionPane.showMessageDialog(null, "sql err");
}
} else {
JOptionPane.showMessageDialog(null, "Please select an item to delete");
}
}
Please tell me what am I doing wrong?
I'm trying to build a class that retrieves each row from a MySQL table and store it to a List but my code doesn't compile and throws me an error
Error: Main method not found in class
MySQLAccountsDatabankReader,
please define the main method as: public static void main(String[]
args)
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.logging.Level;
import java.util.logging.Logger;
public class MySQLAccountsDatabankReader {
private static List<String[]> accounts;
public MySQLAccountsDatabankReader(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "mysql";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM test.accounts;");
if (rs.next()) {
ArrayList<String[]> accounts = new ArrayList<String[]>();
rs = st.executeQuery("SELECT * FROM test.accounts;");
int columnCount = rs.getMetaData().getColumnCount();
while (rs.next()) {
String[] row = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
row[i] = rs.getString(i + 1);
}
accounts.add(row);
}
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MySQLAccountsDatabankReader.class
.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MySQLAccountsDatabankReader.class
.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
return accounts;
}
}
Revision 0.2 - I've got the following compilation error - Exception in thread "main" java.lang.Error: Unresolved compilation problems:
accounts cannot be resolved
accounts cannot be resolved to a variable
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.logging.Level;
import java.util.logging.Logger;
public class MySQLAccountsDatabankReader {
public static void main(String[] args) {
MySQLAccountsDatabankReader reader = new MySQLAccountsDatabankReader();
List<String[]> accounts = reader.getAccounts();
}
public List<String[]> getAccounts() {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "mysql";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM test.accounts;");
if (rs.next()) {
rs = st.executeQuery("SELECT * FROM test.accounts;");
int columnCount = rs.getMetaData().getColumnCount();
while (rs.next()) {
String[] row = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
row[i] = rs.getString(i + 1);
}
accounts.add(row);
}
return accounts;
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MySQLAccountsDatabankReader.class
.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MySQLAccountsDatabankReader.class
.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
Compiler errors are usually a good indicator of what is wrong - you need a main method.
Also, non-declarative statements need to be in a method, constructor or static initializer rather than in the class code block. Place your JDBC code within a method. Here you need a method that will return accounts to match your return statement. Also you need to create an instance of List, e.g. ArrayList to return.
private List<String[]> getAccounts() {
List<String[]> accounts = new ArrayList<String[]>();
...
return accounts;
}
and add a main method entry point:
public static void main(String[] args) {
MySQLAccountsDatabankReader reader = new MySQLAccountsDatabankReader();
List<String[]> accounts = reader.getAccounts();
...
}
Add main method:
public static void main(String [] args) {
new MySQLAccountsDatabankReader(args);
}