I'm in my last chapter of Java up at Francis Tuttle. For this chapter, I was taught how to make a stock-checking program with a password interface, database manipulation via JDBC-ODBC and all that jazz. The book provides all the code and I basically copy it down while reading about how that particular chunk of code works. Weird thing is, I'm getting a weird 'no connection' issue whenver I try to run the program. Its not seeing the database, which is in the same place the program and all its components are in. I asked my teacher for help, and he copypasta'd the de-facto files and whatnot to my folder. It worked for that day and I got started on the next project. Next day I try to run the original program and I get picture related.
I've got to make 6 different programs using this program as a base, but I can't do jack until I figure out why
the program isn't working right. My google-fu is weak, so I come to SP for help.
Information
Picture of the issue in question
Code:
/*
Chapter 11: The MakeDB Class
Programmer: Myles Brown
Date: November 30, 2012
Filename: MakeDB.java
Purpose: To build an initial database for the StockTracker application
*/
import java.sql.*;
import java.io.*;
H:> java -classpath H:\Java I\Chapter 11\Programs\JBDC\StockTracker.mdb;
public class MakeDB
{
public static void main(String[] args) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:StockTracker";
Connection con = DriverManager.getConnection(url);
Statement stmt = con.createStatement();
// The following code deletes each index and table, if they exist.
// If they do not exist, a message is displayed and execution continues.
System.out.println("Dropping indexes & tables ...");
try
{
stmt.executeUpdate("DROP INDEX PK_UserStocks ON UserStocks");
}
catch (Exception e)
{
System.out.println("Could not drop primary key on UserStocks table: "
+ e.getMessage());
}
try
{
stmt.executeUpdate("DROP TABLE UserStocks");
}
catch (Exception e)
{
System.out.println("Could not drop UserStocks table: "
+ e.getMessage());
}
try
{
stmt.executeUpdate("DROP TABLE Users");
}
catch (Exception e)
{
System.out.println("Could not drop Users table: "
+ e.getMessage());
}
try
{
stmt.executeUpdate("DROP TABLE Stocks");
}
catch (Exception e)
{
System.out.println("Could not drop Stocks table: "
+ e.getMessage());
}
///////// Create the database tables /////////////
System.out.println("\nCreating tables ............");
// Read and display all User data in the database.
ResultSet rs = stmt.executeQuery("SELECT * FROM Users");
System.out.println("Database created.\n");
System.out.println("Displaying data from database...\n");
System.out.println("Users table contains:");
Password pswdFromDB;
byte[] buf = null;
while(rs.next())
{
System.out.println("Logon ID = "
+ rs.getString("userID"));
System.out.println("First name = "
+ rs.getString("firstName"));
System.out.println("Last name = "+rs.getString("lastName"));
System.out.println("Administrative = "+rs.getBoolean("admin"));
System.out.println("Initial password = "+initialPswd);
// Do NOT use with JDK 1.2.2 using JDBC-ODBC bridge as
// SQL NULL data value is not handled correctly.
buf = rs.getBytes("pswd");
if (buf != null)
{
System.out.println("Password Object = "
+ (pswdFromDB=(Password)deserializeObj(buf)));
System.out.println(" AutoExpires = "+ pswdFromDB.getAutoExpires());
System.out.println(" Expiring now = "+ pswdFromDB.isExpiring());
System.out.println(" Remaining uses = "
+ pswdFromDB.getRemainingUses()+"\n");
}
else
System.out.println("Password Object = NULL!");
}
rs = stmt.executeQuery("SELECT * FROM Stocks");
if(!rs.next())
System.out.println("Stocks table contains no records.");
else
System.out.println("Stocks table still contains records!");
rs = stmt.executeQuery("SELECT * FROM UserStocks");
if(!rs.next())
System.out.println("UserStocks table contains no records.");
else
System.out.println("UserStocks table still contains records!");
stmt.close(); // closing Statement also closes ResultSet
} // end of main()
// Method to write object to byte array and then insert into prepared statement
public static byte[] serializeObj(Object obj)
throws IOException
{
ByteArrayOutputStream baOStream = new ByteArrayOutputStream();
ObjectOutputStream objOStream = new ObjectOutputStream(baOStream);
objOStream.writeObject(obj); // object must be Serializable
objOStream.flush();
objOStream.close();
return baOStream.toByteArray(); // returns stream as byte array
}
// Method to read bytes from result set into a byte array and then
// create an input stream and read the data into an object
public static Object deserializeObj(byte[] buf)
throws IOException, ClassNotFoundException
{
Object obj = null;
if (buf != null)
{
ObjectInputStream objIStream =
new ObjectInputStream(new ByteArrayInputStream(buf));
obj = objIStream.readObject(); // throws IOException, ClassNotFoundException
}
return obj;
}
} // end of class
// Enable Enter key for each JButton
InputMap map;
map = jbtLogon.getInputMap();
if (map != null){
map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,false), "pressed");
map.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0,true), "released");
}
pack();
if( width < getWidth()) // prevent setting width too small
width = getWidth();
if(height < getHeight()) // prevent setting height too small
height = getHeight();
centerOnScreen(width, height);
}
public void centerOnScreen(int width, int height)
{
int top, left, x, y;
// Get the screen dimension
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// Determine the location for the top left corner of the frame
x = (screenSize.width - width)/2;
y = (screenSize.height - height)/2;
left = (x < 0) ? 0 : x;
top = (y < 0) ? 0 : y;
// Set the frame to the specified location & size
this.setBounds(left, top, width, height);
}
private boolean validUser(String userID,String password)
throws PasswordException,SQLException,IOException,ClassNotFoundException
{
boolean userOK = false;
user = db.getUser(userID); // get user object from DB for this ID
if(user != null)
{
user.validate(password); // throws PasswordException
userOK = true;
if(user.pswdAutoExpires()) // if tracking uses
db.updUser(user); // update DB for this use
}
return userOK;
}
private void doStockActivity()throws PasswordException,SQLException,
IOException,ClassNotFoundException
{
StockTracker f = new StockTracker(user,this,db);
f.pack();
this.setVisible(false);
f.setVisible(true);
}
public void activate()
{
this.setVisible(true);
userIDField.setText("");
userIDField.requestFocus();
user = null;
}
public void actionPerformed(ActionEvent e)
{
try
{
userID = userIDField.getText();
if(userID.equals(""))
{
JOptionPane.showMessageDialog(this,
"Please enter a valid user ID.",
"Missing User ID.",
ERROR_MESSAGE); // updated for v5.0
userIDField.requestFocus();
}
else
{
password = new String(passwordField.getPassword());
if(password.equals(""))
{
JOptionPane.showMessageDialog(this,
"Please enter a valid password.",
"Missing Password.",
ERROR_MESSAGE); // updated for v5.0
passwordField.requestFocus();
}
else
{
try
{
// See if userID exists and validate password
if(validUser(userID,password))
{
if(user.pswdIsExpiring())
JOptionPane.showMessageDialog(this,
user.getUserID()+" logon successful; "
+user.getPswdUses()+" use(s) remaining.");
if(e.getSource() == jbtLogon)
doStockActivity();
}
else
JOptionPane.showMessageDialog(this, "Invalid user.");
}
catch (PasswordExpiredException ex)
{
JPasswordField pf1 = new JPasswordField();
JPasswordField pf2 = new JPasswordField();
Object[] message1 = new Object[]
{"Password has expired. Please enter a new password.", pf1};
Object[] options = new String[] {"OK", "Cancel"};
JOptionPane op1 = new JOptionPane(message1,
WARNING_MESSAGE, // updated for v5.0
OK_CANCEL_OPTION, null, options); // updated for v5.0
JDialog dialog1 = op1.createDialog(null, "Change Password");
dialog1.setVisible(true); // updated for v5.0
if(op1.getValue() != null && options[0].equals(op1.getValue()))
{
String pswd1 = new String(pf1.getPassword());
if(pswd1 != null)
{
Object[] message2 = new Object[]
{"Please verify new password.", pf2};
JOptionPane op2 = new JOptionPane(message2,
WARNING_MESSAGE, // updated for v5.0
OK_CANCEL_OPTION, // updated for v5.0
null, options);
JDialog dialog2 = op2.createDialog(null, "Verify Password");
dialog2.setVisible(true); // updated for v5.0
if(op2.getValue() != null && options[0].equals(op2.getValue()))
{
String pswd2 = new String(pf2.getPassword());
if(pswd2 != null)
{
if(pswd1.equals(pswd2))
{
user.changePassword(password, pswd1);
db.updUser(user);
doStockActivity();
}
else
JOptionPane.showMessageDialog(this,
"Both passwords are not identical.",
"Password not changed",
ERROR_MESSAGE); // updated for v5.0
}
}
}
}
}
}
}
userIDField.setText("");
passwordField.setText("");
userIDField.requestFocus();
}// end of try
catch (PasswordUsedException ex)
{
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Password Previously Used. Try again.",
ERROR_MESSAGE); // updated for v5.0
}
catch (PasswordSizeException ex)
{
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"Invalid password size. Try again.",
ERROR_MESSAGE); // updated for v5.0
}
catch (PasswordInvalidFormatException ex)
{
if(ex.getCount() > 2) // allows only 3 tries, then exits program
System.exit(0);
else
JOptionPane.showMessageDialog(this,ex.getMessage()+", count:"+ex.getCount(),
"Invalid password format. Try again.",
ERROR_MESSAGE); // updated for v5.0
}
catch (PasswordInvalidException ex)
{
if(ex.getCount() > 2) // allows only 3 tries, then exits program
System.exit(0);
else
JOptionPane.showMessageDialog(this,ex.getMessage()+", count:"+ex.getCount(),
"Invalid password. Try again.",
ERROR_MESSAGE); // updated for v5.0
}
catch (PasswordException ex)
{
JOptionPane.showMessageDialog(this,
ex.getMessage(),
"PasswordException.",
ERROR_MESSAGE); // updated for v5.0
}
public static void main(String[] argv)
{
final STLogon f = new STLogon();
f.setVisible(true);
}
}
What I think is mucking it up part 2
Bonus issues - Edit 1
I dunno how to phrase it, but I wanna get better at programming. Like a lot better. Like 'look at any language and able to do pomegranate' better. I like coding and computing and all that shiz, but being terrible at it is getting to me. Plus, college'll be rough if I don't get some practice in when I'm out doing fu'ck-all this summer. I just don't know where to look. I'll add on to this once I get more time.
EDIT 1: The plan now is to go back and basically do what Polantaris said and go back and mess around with my old projects. Then branch out from there, possibly making a simple 'indie platformer #204556546'. When I go to college, I plan to go for Software Engineering instead of Comp Sci since I hate math. Question is: No idea where a college with a good course is in the OKC OSU is my best bet for now. Hoo-ray.
You may be better off using Eclipse or a similar IDE (NetBeans is another one. I personally prefer Eclipse). Eclipse is 100x better, in my opinion, especially when it comes to file management.
I think the issue is simply that everything isn't properly managed in TextPad. Eclipse should help with that.
That's just my opinion, I could be completely off with it being the issue, however I think getting off of TextPad now will help you in the future. I've made this recommendation to many people in my own classes, and most of them have thanked me afterwards.
About the bonus issue: Honestly, programming is a major example of "learn by doing." You can look at books and copy book code all day, but it doesn't help if you don't do anything yourself. Even these examples that you have from books, manipulate them. Do things to them that are not part of the project. Anything you can think of, even if it sounds simple in your head.
Then, after you've done a decent amount of manipulating other people's codes, try making your own projects. Think of something random, it doesn't need to be something super cool or something super sophisticated. Just make a program that does something, takes user input, uses files, etc. Then, when you get it all working, think about how you can make it more efficient code. For example, if you have the same code multiple times, wouldn't it be better to separate this code into a single method and just call that method multiple times instead of copying the same code over and over? Always think about error checking. All that kind of stuff.
One of the great things about Java is that it has a TON of two things: Information and Libraries. Java Commenting has the ability to work in comment resource pages in them (/** initiates this). Anyone who makes anything important that they release to other people make use of this. Why is this helpful? Well... There's a library for just about everything, the hard work is often done for you by someone else already. Make use of that. It's a powerful resource in Java. If you don't understand what something is doing or does, you open the comment resource page, and it's all described (hopefully in a helpful way).
Polantaris Wrote:You may be better off using Eclipse or a similar IDE (NetBeans is another one. I personally prefer Eclipse). Eclipse is 100x better, in my opinion, especially when it comes to file management.
I think the issue is simply that everything isn't properly managed in TextPad. Eclipse should help with that.
That's just my opinion, I could be completely off with it being the issue, however I think getting off of TextPad now will help you in the future. I've made this recommendation to many people in my own classes, and most of them have thanked me afterwards.
About the bonus issue: Honestly, programming is a major example of "learn by doing." You can look at books and copy book code all day, but it doesn't help if you don't do anything yourself. Even these examples that you have from books, manipulate them. Do things to them that are not part of the project. Anything you can think of, even if it sounds simple in your head.
Then, after you've done a decent amount of manipulating other people's codes, try making your own projects. Think of something random, it doesn't need to be something super cool or something super sophisticated. Just make a program that does something, takes user input, uses files, etc. Then, when you get it all working, think about how you can make it more efficient code. For example, if you have the same code multiple times, wouldn't it be better to separate this code into a single method and just call that method multiple times instead of copying the same code over and over? Always think about error checking. All that kind of stuff.
One of the great things about Java is that it has a TON of two things: Information and Libraries. Java Commenting has the ability to work in comment resource pages in them (/** initiates this). Anyone who makes anything important that they release to other people make use of this. Why is this helpful? Well... There's a library for just about everything, the hard work is often done for you by someone else already. Make use of that. It's a powerful resource in Java. If you don't understand what something is doing or does, you open the comment resource page, and it's all described (hopefully in a helpful way).
Hope this helps.
A friend mentioned Eclipse to me as well last year. He gave me the files for it, but I lost them due to last-minute-shenanigans. I only work in TextPad because thats what I use up at my class, and I dunno if Eclipse stores or converts the files differently since I have to send them to my teacher when I'm done with all the projects. I'll definitely start using it at home, however.
Piggy 2.0 Wrote:A friend mentioned Eclipse to me as well last year. He gave me the files for it, but I lost them due to last-minute-shenanigans. I only work in TextPad because thats what I use up at my class, and I dunno if Eclipse stores or converts the files differently since I have to send them to my teacher when I'm done with all the projects. I'll definitely start using it at home, however.
Other than that, holy hot damn is that helpful.
Glad I could help.
Eclipse doesn't really store them differently, other than giving some structure to your project. For example, all your java files end up in a src folder, and all your class files(compiled code, not what you want to give to your teacher) end up in a bin folder.
If you want a file to be run directly in the project without a path, you would put it in the main folder.
So for example, let's say your project folders are in "C:/Java/Workplace/ProjectNameHere/".
Your Source (.java) files would be in "C:/Java/Workplace/ProjectNameHere/src"
Your Compiled (.class) files would be in "C:/Java/Workplace/ProjectNameHere/bin"
Typically, libraries you add would be in a lib folder so: "C:/Java/Workplace/ProjectNameHere/lib"
And any files you want to execute directly would be in the base folder, "C:/Java/Workplace/ProjectNameHere/whatever.extension".
I imagine that's where you would put your database information and what not. Then you can just access it by "whatever.extension" in your code.
In the future, if you wish to add a library to Eclipse, it's EXTREMELY easy.
All you do, is add said library to your project, and as specified earlier, preferably in a lib folder. Then, when you refresh the tree path in the project explorer on the left of Eclipse, you will see that folder. Open it, select the library, right click it, and hit Build Path -> Add to Build Path. It does all the work for you in configuring it correctly. Then you can just import it like a regular library, and you're good to go.
You can always look up file access stuff on the web if you want further details on how Eclipse manages files, but if you just put everything in the root directory of your project, you should be perfectly fine when your teacher tries to access it if s/he uses TextPad.
As for your new question: Good luck...I haven't exactly been lucky with schools myself so I have no recommendations. Sorry.