Check String to see if its Numeric
Here is the code
if (e.getSource() == addRec)// Add button clicked
{// Create an INSERT INTO SQL command
listOfItems.setText(" ");
sqlCommand ="INSERT INTO INVENTORY " +
"VALUES('" + ItemID.getText().trim() +"', " +
"'" + ItemName.getText().trim() +"', " +
"'" + ItemLocation.getText().trim() +"', " +"'" +ItemValue.getText().trim() +"', " +
"'" + ItemDescription.getText().trim() +"' )";
sttmnt.executeUpdate(sqlCommand);// Execute SQL
ItemID.setText(" ");
ItemName.setText(" ");
ItemLocation.setText(" ");
ItemValue.setText(" ");
ItemDescription.setText(" ");
}// end of if
How can I check Item ID to see if It is a numric field before I enter it into the Database.
> How can I check Item ID to see if It is a numric field before I enter it into the Database.
1) Parse the text as a number, handling any exceptions
2) Bounce it against a regular expression
3) Modify it so it only accepts numbers in the first place
4) Search the forums and the web as this question has been asked (and answered) more times than we can count
It's an extremely important skill to learn how to [url=http://www.google.com/]search the web[/url]. Not only will it increase your research and development talents, it will also save you from asking questions that have already been answered numerous times before. By doing a little research before you ask a question, you'll show that you're willing to work and learn without needing to have your hand held the entire time; a quality that is seemingly rare but much appreciated by the volunteers who are willing to help you.
If you've done the research, found nothing useful, and decide to post your question, it's a great idea to tell us that you've already searched (and what methodologies you used to do your research). That way, we don't refer you back to something you've already seen.
Depending on what kind of number you expect it to be, Integer.parseInt, Long.parseLong, or Double.parseDouble would be the easiest way. If no exception is thrown, it's numeric.
But what will you do if it's non-numeric? If it's required to be a number, then the DB column should be defined as such, and when you try to insert a non-number, you'll get an exception anyway.
On a side you, you really should be using PreparedStatement. You'll save yourself a lot of headaches with escaping and formatting if you do.
sqlCommand = "INSERT INTO INVENTORY VALUES(?, ?, ... etc. ...)";
ps = con.prepareStatement(sqlCommand);
ps.setInt(1, Integer.parseInt(ItemID.getText().trim()));
ps.setString(2, ItemLocation.getText().trim());
... etc. ..
ps.executeUpdate(); // I think -- check the docs for the right method name
jverda at 2007-7-13 18:12:25 >

> > On a side you, you really should be using
> PreparedStatement.
>
> And refactoring data transaction logic away from
> display code. :o)
And praying for the starving pygmies down in New Guinea. Amen.
And depositing large sums of money into my checking account.
jverda at 2007-7-13 18:12:25 >
