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();
}
});
}
}
Related
The only thing remotely similar to my issue that I could find was this, however his problem seemed to be from a user error.
Reset cursor position after ResultSet updateRow
My problem is the following: After updating a row I am not able to access any other rows in my ResultSet. The update itself works fine, but if I want to continue I have to restart the application.
Here's the code:
package database;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Gui extends MyDB {
JFrame f;
JLabel FName;
JLabel LName;
JLabel Age;
JTextField t;
JTextField t2;
JTextField t3;
JButton next = new JButton("next");
JButton update = new JButton("Update");
public Gui() {
frame();
start();
btnAction();
}
public void frame() {
f = new JFrame();
f.setVisible(true);
f.setSize(680, 480);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FName = new JLabel("Name");
LName = new JLabel("Anrede");
Age = new JLabel("age");
t = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
JPanel p = new JPanel();
p.add(FName);
p.add(t);
p.add(LName);
p.add(t2);
p.add(Age);
p.add(t3);
p.add(b1);
p.add(update);
public void btnAction() {
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String FName = t.getText();
String LName = t2.getText();
String Age = t3.getText();
try {
System.out.println(rs.getRow());
rs.updateString("FName", FName);
rs.updateString("LName", LName);
rs.updateString("Age", Age);
rs.updateRow();
//System.out.println(rs.getString("FName"));
System.out.println(rs.getRow());
JOptionPane.showMessageDialog(null, "Record updated ");
} catch (Exception ex) {
System.out.println("no");
}
}
});
}
public void start() {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
}
Also:
package database;
import java.sql.*;
public class MyDB {
Connection con;
Statement st;
ResultSet rs;
public MyDB() {
connect();
}
public void connect() {
try {
String db = "jdbc:ucanaccess://Datenbank1.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select * from Tabelle1";
rs = st.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace(System.out);
}
}
public static void main(String[] args) {
new Gui();
}
}
Output of System.out.println(rs.getRow()); is '0'.
If I want to click on the 'next' button after updating, the message "no next records" is displayed.
I have tried using rs.first(), rs.beforeFirst() and rs.isBeforeFirst(), none of which have worked.
If it helps, I am following this tutorial, which does not run into the same problem:
https://www.youtube.com/watch?v=NPV2o6YjP10
private void update_table(){
try{
DefaultTableModel df=(DefaultTableModel)jTable1.getModel();
Conn c=new Conn();
Statement s=c.createConn().createStatement();
// df.getDataVector().removeAllElements();
String sql="Select * from leave_taken";
ResultSet rs=s.executeQuery(sql);
while(rs.next()){
Vector v=new Vector();
df.addRow(v);
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
} catch (Exception e) {
e.printStackTrace();
}
This is what i wrote. i want to lad data to the table by this method. but it loads only the table headings. how can i load table data to the table? Is there some thing need to add to this code?
Your v variable happens to be empty vector when you do df.addRow(v). Seems like you don't need df in your code.
Full example working with data
package javaapplication2;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class JavaApplication2
{
public static void main(String[] args)
{
Runnable r = new Runnable()
{
#Override
public void run()
{
JFrame f = new JFrame();
JPanel p = new JPanel();
f.setContentPane(p);
f.setPreferredSize(new Dimension(600, 600));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable t = new JTable();
p.add(new JScrollPane(t), BorderLayout.CENTER);
JButton b = new JButton("Run");
p.add(b, BorderLayout.WEST);
b.addActionListener(
new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection c = DriverManager.getConnection("jdbc:sqlserver://localhost;integratedSecurity=true;databaseName=stackoverflow");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("SELECT * FROM leave_taken");
t.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (SQLException es)
{
es.printStackTrace();
}
catch (ClassNotFoundException ecn)
{
ecn.printStackTrace();
}
}
});
f.pack();
f.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}
Result on application start.
Result after button "Run" pressed.
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();
}
};
Trying to set up a JDBC that checks a database for a matching username and password, and they when the login button is pressed if matching the user is granted access, I've got my current code here, but I'm unsure what is missing when I launch the program it seems like its not checking the database for the correct information.
Updated:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class NewClass extends JFrame {
private JTextField jtfUsername, jtfPassword;
private JButton backButton, loginButton;
private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;
NewClass() {
//create menu bar
JMenuBar jmb = new JMenuBar();
//set menu bar to the applet
setJMenuBar(jmb);
//add menu "operation" to menu bar
JMenu optionsMenu = new JMenu("Options");
optionsMenu.setMnemonic('O');
jmb.add(optionsMenu);
//add menu "help"
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
jmb.add(helpMenu);
//add menu items with mnemonics to menu "options"
optionsMenu.add(jmiLogin = new JMenuItem("Login", 'L'));
optionsMenu.addSeparator();
optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));
//panel p1 to holds text fields
JPanel p1 = new JPanel(new GridLayout(2, 2));
p1.add(new JLabel("Username"));
p1.add(jtfUsername = new JTextField(15));
p1.add(new JLabel("Password"));
p1.add(jtfPassword = new JPasswordField(15));
//panel p2 to holds buttons
JPanel p2 = new JPanel(new FlowLayout());
p2.add(backButton = new JButton("Back"));
p2.add(loginButton = new JButton("Login"));
//Panel with image??????
//add panels to frame
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(p1, BorderLayout.CENTER);
panel.add(p2, BorderLayout.SOUTH);
add(panel, BorderLayout.CENTER);
setTitle("Main Page");
//listners for exit menuitem and button
jmiBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
//listner for about menuitem
jmiAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This is the login panel"
+ "\n Assignment for University",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
//action listeners for Login in button and menu item
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText()); {
System.out.println("User is validated");
}
} catch (SQLException se) {
}
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
jmiLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
}
public static void main(String arg[]) {
log frame = new log();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class usernamecheck {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/test";
static final String USERNAME = "root";
static final String PASSWORD = "root";
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
}
Make your checkLogin method return boolean type and return true inside if (orPass.equals(password)) { block. Check whether the method true if so grant access.
You are missing a return type in your checkLogin method. You may return a boolean value to validate the user. Also add some logging/sysout to make sure what is happening in your code.
Update your method as :
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
rs.close();
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
And then update your user check as
try {
if(usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText())) {
System.out.println("User is validated");
} else {
return;
}
} catch (SQLException se) {
}
I'm trying to make a authorization JFrame to MS Access DB, but query does'nt seems to wirk properly. The idea is to intup login and password, and if one of them isn't correct, get a message. My code always sends me to the exception. Here is my code, maybe someone can help me.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class First {
JFrame frame;
JPanel txt, but;
JButton log, ext;
JTextField login;
JLabel l, p;
JPasswordField pass;
PreparedStatement prepst;
ResultSet res;
public First() {
frame = new JFrame("Authorization");
txt = new JPanel();
but = new JPanel();
log = new JButton("Login");
ext = new JButton("Quit");
login = new JTextField(10);
l = new JLabel("Login:");
p = new JLabel("Password:");
pass = new JPasswordField(10);
frame.setSize(400,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt.add(l);
txt.add(login);
txt.add(p);
txt.add(pass);
frame.add(txt,BorderLayout.NORTH);
but.add(log);
but.add(ext);
frame.add(but,BorderLayout.SOUTH);
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String PathToDataBase = "D:/workspace2/MicrosoftAccessConnection/db";
String DataBase = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
DataBase += PathToDataBase.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection(DataBase,"","");
prepst = con.prepareStatement("SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?");
String lll = login.getText();
String ppp = pass.getText();
prepst.setString(1,lll);
prepst.setString(2, ppp);
res = prepst.executeQuery();
if((test(con,lll,ppp)) == true) {
while(res.next()) {
if((lll.equals(res.getString("LOGIN"))) && (ppp.equals(res.getString("PASSWORD")))) {
lol();
} else {
JOptionPane.showMessageDialog(null, "Wrong data");
}
}
}
res.close();
prepst.close();
con.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error with connection");
}
}
});
ext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
frame.dispose();
}
});
frame.setVisible(true);
}
public void lol() {
JFrame f = new JFrame("SUCCESS");
f.setSize(200,200);
frame.dispose();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
boolean test(Connection con, String login, String pass) throws SQLException {
int rez = 0;
PreparedStatement st = con.prepareStatement("SELECT COUNT(*) FROM USERS WHERE LOGIN=? AND PASSWORD=?");
st.setString(1, login);
st.setString(2, pass);
ResultSet res = st.executeQuery();
while (res.next()) {
rez = res.getInt(1);
}
st.close();
return rez == 1;
}
public static void main(String[] args) {
new First();
}
}
You're missing a PreparedStatement placeholder character from your SQL, replace
SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?
with
SELECT * FROM USERS WHERE LOGIN=? AND PASSWORD=?
^
If you're getting an Exception, its always best to display the exception content. You could add this to the exception block:
e.printStackTrace();