I cannot insert value in the table using textfield - java

I need to create a program in which values can be inserted using textfield in Java.
database getting connected ...
bt Cannot insert values using JTextfield ....need help..
shows error ..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
package youtubetest;
import java.sql.*;
import java.awt.event.*;
import javax.swing.*;
public class YouTubeTest extends JFrame{
private static final String USERNAME = "root";
private static final String PASSWORD = "****";
private static final String CONN_STRING = "jdbc:mysql://localhost:3306/youtube";
Connection conn;
PreparedStatement stmt;
JButton b1,b2;
JTextField t1,t2;
JLabel l1,l2;
String Fname;
String Lname;
public YouTubeTest()
{
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayout(null);
add(t1 = new JTextField(30));
t1.setBounds(10,10,200,50);
add(t2 = new JTextField(30));
t2.setBounds(10, 100, 200, 50);
add(l1 = new JLabel("First Name : "));
l1.setBounds(220, 10, 200, 50);
add(l2 = new JLabel("Last Name : "));
l2.setBounds(220, 100, 200, 50);
add(b1 = new JButton("Submit"));
b1.setBounds(10, 400, 60, 60);
add(b2 = new JButton("Clear"));
b2.setBounds(100, 400, 60, 60);
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
System.out.println("Database Connected Succesfully ..... ");
stmt = conn.prepareStatement("Insert into user(Fname,Lname) values('"+Fname+"','"+Lname+"')");
}catch(Exception e){
e.printStackTrace();
}
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae){
try{
Fname = t1.getText();
Lname = t2.getText();
stmt.setString(1, Fname);
stmt.setString(2, Lname);
stmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t1.setText("");
t2.setText("");
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
try{
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
setVisible(true);
}
public static void main(String[] args)throws Exception {
new YouTubeTest();
}
};

Related

I can't populate a JComboBox with an ArrayList

I have two classes, one has an ArrayList called "clanovi" which is populated by data from SQL database and I want to display that data in the "clanComboBox" in another class. I have been trying for two days but I can't figure it out.
Class with the list:
String cnnString;
String user;
String password;
public ArrayList<String> clanovi = new ArrayList<String>();
public ArrayList<String> getList(){
return clanovi;
}
public void Connect(String cnnString, String user, String password){
this.cnnString = cnnString;
this.user = user;
this.password = password;
ResultSet res = null;
try {
Connection connection = DriverManager.getConnection(cnnString, user, password);
System.out.println("Connection successful");
Statement stm = connection.createStatement();
String sql = "select Ime, Prezime from Clanovi";
res = stm.executeQuery(sql);
while(res.next()) {
clanovi.add(res.getString("Ime") + " " + res.getString("Prezime"));
}
System.out.println(clanovi);
} catch (SQLException e) {
System.out.println("An unexpected error occurred.");
e.printStackTrace();
}
}
The GUI class with the combobox:
public class PosuditiFilmFrame implements ActionListener{
SQLConnection con = new SQLConnection();
JFrame posuditiFilmFrame = new JFrame();
JButton posuditiFilmButton = new JButton();
JComboBox clanoviComboBox = new JComboBox();
JComboBox filmoviComboBox = new JComboBox();
JLabel clanLabel = new JLabel("Clan:");
JLabel filmLabel = new JLabel("Film:");
ArrayList<String> cBox = con.getList();
PosuditiFilmFrame(){
posuditiFilmButton = new JButton();
posuditiFilmButton.setBounds(200, 270, 200, 50);
posuditiFilmButton.addActionListener(this);;
posuditiFilmButton.setText("Posuditi Film");
posuditiFilmButton.setFocusable(false);
clanLabel.setBounds(50, 50, 70, 50);
clanLabel.setFont(new Font("Arial", Font.PLAIN, 25));
filmLabel.setBounds(50, 125, 70, 50);
filmLabel.setFont(new Font("Arial", Font.PLAIN, 25));
clanoviComboBox.setBounds(150, 50, 300, 50);
filmoviComboBox.setBounds(150, 125, 300, 50);
posuditiFilmFrame.setTitle("Posuditi Film");
posuditiFilmFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
posuditiFilmFrame.setLayout(null);
posuditiFilmFrame.setSize(600, 400);
posuditiFilmFrame.setVisible(true);
posuditiFilmFrame.add(posuditiFilmButton);
posuditiFilmFrame.add(clanoviComboBox);
posuditiFilmFrame.add(filmoviComboBox);
posuditiFilmFrame.add(clanLabel);
posuditiFilmFrame.add(filmLabel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==posuditiFilmButton) {
JOptionPane.showMessageDialog(null, "Film je posuden");
}
}
Of course, I also want the data to be displayed in that combobox

how to set values from sql database to java textbox?

When I try to access data from SQL Server, the data column is of type varchar. But I try to set it into textbox, I got these type of exception
Conversion failed when converting the varchar value '09ran01' to data type int
package src.ui;
import src.ui.ImageHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
public class AddAccount extends JPanel implements ActionListener, DocumentListener, KeyListener {
String imagefolder = ImageHandler.returnimagepath();
Image bgImage = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/src/ui/images/bgc.jpg"));
private static final long serialVersionUID = 1L;
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
String iden[] = {"Student","Others"};
String type[] = {"Account User", "Walkthrough User"};
JLabel userid = new JLabel("USER ID");
JLabel name = new JLabel("FULL NAME");
JLabel pswrd = new JLabel("PASSWORD");
JLabel ident = new JLabel("IDENTIFICATION");
JLabel idno = new JLabel("ID NUMBER");
JLabel Add = new JLabel("ADDRESS");
JLabel acctype = new JLabel("ACCOUNT TYPE");
JTextField userFld = new JTextField(10);
JTextField nameFld = new JTextField(10);
JPasswordField pswrdFld = new JPasswordField(10);
JComboBox identC = new JComboBox(iden);
JComboBox actype = new JComboBox(type);
JTextField idFld = new JTextField(10);
JTextArea addArea = new JTextArea(10, 10);
JButton okButton = new JButton("OK");
JButton exitButton = new JButton("RESET");
JButton b1 = new JButton("SEARCH");
JScrollPane scroll = new JScrollPane(addArea);
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1/cybman", "root", "");
} catch (Exception e) {
//System.out.println(e);
}
return conn;
}
public static Connection getConnection1() {
Connection con = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection("jdbc:sqlserver://localhost\\BCA1:1433;databaseName=Old_Bhandarkars;user=sa;password=1234");
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"SERVER ERROR");
//System.out.println(e);
}
return con;
}
public void changedUpdate(DocumentEvent ev) {
}
public void removeUpdate(DocumentEvent ev) {
}
public void insertUpdate(DocumentEvent ev) {
}
public void paintComponent(Graphics g) {
g.drawImage(bgImage, 0, 0, this);
}
public void init() {
setLayout(null);
okButton.addActionListener(this);
b1.addActionListener(this);
exitButton.addActionListener(this);
pswrdFld.addActionListener(this);
pswrdFld.setEchoChar('*');
addArea.getDocument().addDocumentListener(this);
identC.addActionListener(this);
actype.addActionListener(this);
userid.setBounds(270, 20, 120, 20);
userFld.setBounds(470, 20, 140, 20);
b1.setBounds(670, 20, 100, 20);
name.setBounds(270, 70, 120, 20);
nameFld.setBounds(470, 70, 140, 20);
pswrd.setBounds(270, 120, 120, 20);
pswrdFld.setBounds(470, 120, 140, 20);
ident.setBounds(270, 170, 120, 20);
identC.setBounds(470, 170, 140, 20);
idno.setBounds(270, 220, 120, 20);
idFld.setBounds(470, 220, 140, 20);
acctype.setBounds(270, 270, 120, 20);
actype.setBounds(470, 270, 140, 20);
Add.setBounds(270, 320, 320, 20);
scroll.setBounds(470, 320, 140, 60);
okButton.setBounds(270, 410, 100, 20);
okButton.addKeyListener(this);
exitButton.setBounds(510, 410, 100, 20);
}
public AddAccount() {
init();
add(userid);
add(userFld);
add(name);
add(nameFld);
add(pswrd);
add(pswrdFld);
add(ident);
add(identC);
add(idno);
add(idFld);
add(acctype);
add(actype);
add(Add);
add(b1);
add(scroll);
add(okButton);
add(exitButton);
}
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
public class Function
{
Connection con=getConnection1();
ResultSet rs;
public ResultSet find(String s)
{
int a=Integer.parseInt(s);
try{
Statement sta = con.createStatement();
String s1 = "select * from Members where Fld_Member_Id="+a+"";
rs = sta.executeQuery(s1);
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,"No connection");
//JOptionPane.showMessageDialog(null,ex.getMessage());
}
//JOptionPane.showMessageDialog(null,rs);
return rs;
}
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
char[] pass;
String uid;
String nam;
String add;
String id;
String idnum;
String actyp;
int amt = 0;
String datE;
if (str.equals("SEARCH")) {
Function f=new Function();
ResultSet rs=null;
String n1="Fld_First_Name";
String i1="Fld_Member_Id";
String address="Fld_PAddr";
uid = userFld.getText();
if(uid.equals(""))
{
JFrame msg=new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the user id", "Error Message", JOptionPane.ERROR_MESSAGE);
}
// simple.main();
else
{
//idFld.setText(userFld.getText());
rs=f.find(userFld.getText());
// System.out.println("Fld_First_Name");
try{
if(rs.next()){
// int i = Integer.parseInt(rs.getString("Fld_First_Name"));
// int j = Integer.parseInt(rs.getString("Fld_Member_Id"));
// int k = Integer.parseInt(rs.getString("Fld_PAddr"));
nameFld.setText(rs.getString("Fld_First_Name"));
idFld.setText(rs.getString("Fld_Member_Id"));
addArea.setText(rs.getString("Fld_PAddr"));
}
else
{
JOptionPane.showMessageDialog(null,"No data");
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
}
if (str.equals("OK")) {
try {
uid = userFld.getText();
nam = nameFld.getText();
pass = pswrdFld.getPassword();
add = addArea.getText();
idnum = idFld.getText();
id = (String) identC.getSelectedItem();
actyp = (String) actype.getSelectedItem();
datE = getDateTime();
String pwrd = new String(pass);
Connection conn = getConnection();
/*ERROR CHECKING*/
boolean success = true;
if (uid.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the user id", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (nam.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the name", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (pwrd.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the password", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if ((!id.equals("Student")) && (idnum.equals(""))) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the identification number", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
} else if (add.equals("")) {
JFrame msg = new JFrame();
JOptionPane.showMessageDialog(msg, "Please enter the address", "Error Message", JOptionPane.ERROR_MESSAGE);
success = false;
}
/*end of ERROR CHECKING*/
if (success == true) {
///////////ENSURE/////////
JFrame msg = new JFrame();
int choice;
choice = JOptionPane.showConfirmDialog(msg, "Are you sure?", "Select your choice", JOptionPane.OK_CANCEL_OPTION);
/////////////////////////
if (choice == JOptionPane.OK_OPTION) {
str = "insert into account(userid,name,password,address,identification,identificationnum,amount,dates,acctype" + ") values (?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(str);
ps.setString(1, uid);
ps.setString(2, nam);
ps.setString(3, pwrd);
ps.setString(4, add);
ps.setString(5, id);
ps.setString(6, idnum);
ps.setInt(7, amt);
ps.setString(8, datE);
ps.setString(9, actyp);
int count;
count = ps.executeUpdate();
count++;
count--;
//////////////////////////////
ReportPanel.userC.addItem(uid);
ViewAccount.userC.addItem(uid);
if (actyp.equals("Account User")) {
RechargePanel.userC.addItem(uid);
}
//////////////////////////////
JFrame msg1 = new JFrame();
JOptionPane.showMessageDialog(msg1, "An account has been successfully created", "Information", JOptionPane.INFORMATION_MESSAGE);
} else if (choice == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(msg, "Account Creation Aborted", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
//conn.close();
} catch (SQLException e1) {
String error;
JFrame msg = new JFrame();
//error=e1.toString();
error = "Your entry for user id already exists";
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
} catch (Exception e1) {
// TODO Auto-generated catch block
String error;
JFrame msg = new JFrame();
error = e1.toString();
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
///////////////////////////////////////////////////////////////////////////
if (str.equals("RESET")) {
try {
userFld.setText("");
nameFld.setText("");
pswrdFld.setText("");
addArea.setText("");
idFld.setText("");
} catch (Exception e2) {
String error;
JFrame msg = new JFrame();
error = e2.toString();
JOptionPane.showMessageDialog(msg, error, "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
}
///////////////////////////////////////////////////////////
public void keyPressed(KeyEvent key) {
//
}
/////////////////////////////////////////////////////
public void keyReleased(KeyEvent key) {
if (key.getSource() == pswrdFld) {
if (key.getKeyCode() == KeyEvent.VK_ENTER) {
}
}
}
/////////////////////////////////////////////////
public void keyTyped(KeyEvent key) {
//
}
//////////////////////////////////////////////
}
How to set all values to textbox?
field name data type
---------------------------------------------------------------------
Fld_First_Name varchar
Fld_Member_Id varchar
Fld_PAddr nvarchar
SELECT * FROM Members where Fld_Member_Id='14932';
_____________________________________________________________________________
Fld_Member_Id Fld_First_Name Fld_PAddr
______________________________________________________________________________
14932 abc abc
In WHERE clause of a SQL query a varchar variables should be within a single quotes. Try String s1 = "select * from Members where Fld_Member_Id='"+a+"'";
add Single quotes into the statement.And i think it should work setText method that you mentioned if you pass a varchar value correctly.
If you are not sure what is the type of memberID, then use
idFld.setText(String.valueOf("Your value"));

how to dedug in eclipse and solve Unknown Source erros

/*this is my java code which when i compile they don not show exactly error */
public class Login {
public JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conections;
private JTextField textField;
private JPasswordField passwordField;
public Login() {
initialize();
conections = SqliteConnectio.dbConnection();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 581, 411);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(266, 112, 193, 45);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnLOGIN = new JButton("LOGIN");
Image jn=new ImageIcon(this.getClass().getResource("/Ok.png")).getImage();
btnLOGIN.setIcon(new ImageIcon(jn));
btnLOGIN.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select *from customer.sqlite where username=? and password=? ";
PreparedStatement pre = conections.prepareStatement(query);
pre.setString(1, textField.getText());
pre.setString(2, passwordField.getText());
ResultSet res = pre.executeQuery();
int count = 0;
while (res.next()) {
count++;
}
if (count == 1) {
JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
} else if (count > 1) {JOptionPane.showInternalMessageDialog(null, "username and password has sucseeful inserted");
}
else {
JOptionPane.showInternalMessageDialog(null, "username and password has been failed to be entered");
}
res.close();
pre.close();
} catch (Exception e) {
JOptionPane.showInternalMessageDialog(null, "you have failed to asses the database");
}
}
});
btnLOGIN.setBounds(321, 256, 125, 36);
frame.getContentPane().add(btnLOGIN);
JLabel userNAME = new JLabel("USERNAME");
userNAME.setBounds(156, 127, 85, 14);
frame.getContentPane().add(userNAME);
JLabel passLABEL = new JLabel("PASSWORD");
passLABEL.setBounds(156, 191, 85, 14);
frame.getContentPane().add(passLABEL);
passwordField = new JPasswordField();
passwordField.setBounds(266, 188, 193, 20);
frame.getContentPane().add(passwordField);
JLabel lblNewLabel = new JLabel("New label");
Image im=new ImageIcon(this.getClass().getResource("/login.png")).getImage();
lblNewLabel.setIcon(new ImageIcon(im));
lblNewLabel.setBounds(10, 21, 136, 205);
frame.getContentPane().add(lblNewLabel);
}
}
//this is my connection to database which it seems to work just fine by prompting "username and password has sucseeful inserted"
package mi;
import java.sql.*;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SqliteConnectio {
Connection conect=null;
public static Connection dbConnection(){
try {
Class.forName("org.sqlite.JDBC");
Connection conect=DriverManager.getConnection(
"jdbc:sqlite:E:\\JAVA WORLD\\sgliteDatabase\\customer.sqlite");
JOptionPane.showMessageDialog(null, "sucessful login to database");
return conect;
} catch (Exception e) {
JOptionPane.showConfirmDialog(null, "failed to login in database");
return null;
}
}
}

generating a unique string on pressing JButton and storing it into database table

I need to generate sequential number between 0-9 and want to display it in the JTextfield combined with the value from JCombobox(i.e.element of jcombobox+count)
as a string after pressing the JButton
When I select the first value from combobox and press the JButton the count should start from 0 and again when the second element from the combobox is selected the count should again start from 0 for second element and this should be the case for all other element of combobox.
For example-- when element 1 is selected and button is pressed the combined output should be 10,11,12,13... but,if in between this element 2 is selected
the output displayed in textfield should again start from 0 i.e.20,21,22...
and for element 3 the count should again start from 0 i.e. 30,31,32...
The combined output should be displayed in textfield
import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class Test extends JFrame implements ActionListener {
JButton b1, b2;
JComboBox jc;
String name;
JTextField t1;
Connection con, conn;
Statement st;
PreparedStatement pst;
ResultSet rs, rs1;
Test() {
setLayout(null);
JLabel l1 = new JLabel("USER SELECTION :");
l1.setBounds(100, 100, 150, 60);
add(l1);
jc = new JComboBox();
jc.setBounds(230, 114, 120, 30);
jc.addItem("SELECT");
jc.addActionListener(this);
add(jc);
JButton b1 = new JButton("GENERATE PART NO. :");
b1.setBounds(70, 340, 170, 30);
b1.addActionListener(this);
add(b1);
t1 = new JTextField(10);
t1.setBounds(270, 340, 200, 30);
add(t1);
JButton b2 = new JButton("BACK");
b2.setBounds(190, 420, 120, 30);
b2.addActionListener(this);
add(b2);
setSize(500, 500);
setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select Userdata from user1";
rs = st.executeQuery(s);
while (rs.next()) {
String name = rs.getString("Userdata");
jc.addItem(rs.getString("Userdata"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR");
}
finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("GENERATE PART NO. :")) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select value from user1 where Userdata='" + jc.getSelectedItem() + "'";
rs = st.executeQuery(s);
t1.getText();
if (rs.next()) {
String add1 = rs.getString("value");
t1.setEditable(false);
t1.setText("B" + add1);// B is the default value here which
// is also concatenated
}
}
catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
if (str.equals("BACK") == true) {
new categ();
setVisible(false);
}
}
public static void main(String[] args) throws IOException {
Test td = new Test();
}
}

how to show output from console to JTextArea

I am beginner in Java Programming. How can i show my output from console to JTextArea. Here my code only show the output console. Anyone could tell or show me how can i do it.Thanks.
import java.sql.*;
public class Route
{
public void routeList()
{
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "YarraTram";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "abc123";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
PreparedStatement statement = conn.prepareStatement("Select rid,route from route");
ResultSet result = statement.executeQuery();
while(result.next())
{
System.out.println(result.getString(1)+" "+result.getString(2));
}
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
here is another file
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI
{
public void createAndShowGUI()
{
JButton button2 = new JButton("Route");
//create a frame
JFrame frame = new JFrame("Yarra Tram Route Finder");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(button2);
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
showNewFrame();
Route route = new Route();
route.routeList();
}
public void showNewFrame()
{
JFrame frame = new JFrame("Yarra Tram Route Finder (Route)" );
JTextArea textArea = new JTextArea();
frame.add(textArea);
frame.setSize(500,120);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
textArea.setEditable( false );
}
});
frame.pack();
frame.setSize(350,100);
frame.setVisible(true);
}
}
Modified changes in your existing code. Check this
public class GUI extends JFrame {
JButton button2;
JTextArea textArea;
public GUI() {
super("Yarra Tram Route Finder");
}
public void routeList() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "YarraTram";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "abc123";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement statement = conn.prepareStatement("Select rid,route from route");
ResultSet result = statement.executeQuery();
StringBuilder strBuilder = new StringBuilder();
while (result.next()) {
strBuilder.append(result.getString(1)).append(" ").append(result.getString(2));
strBuilder.append("\n");
}
textArea.setText(strBuilder.toString());
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void createAndShowGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
button2 = new JButton("Route");
textArea = new JTextArea(20, 20);
add(textArea);
add(button2);
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
routeList();
}
});
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI gui = new GUI();
gui.createAndShowGUI();
}
});
}
}

Categories