I have a login form which if is success to login. I want to get a name of the logged, here see my code:
try {
if(jTextField1.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Pleass Input Username");
}
else if(jPasswordField1.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Please Input Password");
}
else
{
rs = con.executeQuery("SELECT * FROM MsEmployee WHERE EmployeeID='"+jTextField1.getText()+"' And Password='"+jPasswordField1.getText()+"'");
if (rs.next())
{
help.IDemployee = jTextField1.getText();
JOptionPane.showMessageDialog(null, "Login Success! welcome "+ help.IDemployee);
MainMenu mm = new MainMenu(true);
mm.setVisible(true);
this.dispose();
}else
{
JOptionPane.showMessageDialog(null, "Username not found!!");
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
So I want to display the EmployeeName from MSEmployee which it got from EmployeeID.
I think something like this:
String qry;
qry = "Select EmployeeName From MsEmplyee WHERE EmployeeID = '" + jtextField1.gettext() + "'" ;
But when I compile, its just print the text above, not get the value. Can anyone help please?
As suggested in a comment, please check which name, MsEmplyee/MsEmployee, is correct.
This is not related to your problem but I think there can be one (possible) improvement in your code.
Instead of using
if(jTextField1.getText().equals(""))
It is better to use trim() method before using equals() method. So if user enters a space in jTextField1, your check will be bypassed in this case. So better to use trim() method to remove all first and last space characters from the string.
if(jTextField1.getText().trim().equals(""))
Same can be done for password field.
You did not read the result set value.
// help.IDemployee = jTextField1.getText();
help.IDemployee = rs.getString(1);
The column index is from 1 for the first column. Not from 0
You Can Try This !
String EmployeeName = rs.getString("Column Label In Database (Like EmployeeName)");
System.out.println(EmployeeName);
Related
I'm currently working on a project with CSV. In the task, I am supposed to type a country name in the tester method, and when I call the tester method, it will print the information of the country. For example, "Germany Chemical 32000." However, no matter what country name I put(I'm sure that country exists in the spreadsheet), it always prints out "NOT FOUND," which I don't understand how. I'm guessing the problem is in the if statement of the countryInfo method. However, I can't find the problem probably due to a lack of domain knowledge, so I hope someone can inform me or give me a hint.
public void tester(){
FileResource fr = new FileResource();
CSVParser parser = fr.getCSVParser();
String GermanyInfo = countryInfo(parser,"Peru");
System.out.println(GermanyInfo);
}
public String countryInfo(CSVParser parser, String country){
String countryInfo = " ";
for (CSVRecord record : parser){
String nation = record.get("Country");
if (nation.contains(country)){
String countryExport = record.get("Exports");
String exportValue = record.get("Value (dollars)");
countryInfo = country + ": " + countryExport + " " + exportValue;
}else{
countryInfo = "NOT FOUND";
}
}
return countryInfo;
}
Debug Process:
Hey guys, after more testing and trying, I found out the problem is really part of the if statement. My for-each loop is running through the parser, one row at a time. The way I have this written, my if statement is checking to see whether that row contains any matching country name in the Country column, but once it finds it, it just keeps going and doesn't stop because I haven't told it to do so. It would find Germany but then move on to the next rows and bypass it until the end of the file, where it will return "not found." In order for me to fix this, I need to have a return statement following the exportValues = record.get line instead of the end of my method, OR simply type in a line that says "break;" after the money line, which will end the loop and then go to the return statement at the bottom.
If you're sure that the country search in your loop works fine, just add the return statement in the right place. I would suggest to change your method like this:
public String countryInfo(CSVParser parser, String country) {
for (CSVRecord record : parser) {
String nation = record.get("Country");
if (nation.contains(country)) {
String countryExport = record.get("Exports");
String exportValue = record.get("Value (dollars)");
return country + ": " + countryExport + " " + exportValue;
}
}
return "NOT FOUND";
}
In this case - as soon as the country is found - the method will return information about it. If no country is found - the method will return String "NOT FOUND"
Basically, a have a sign-up interface THAT should empty fileds and certain conditions and if record exist in data basewhere first it checks if text fields are empty as written below :
private void confirmActionPerformed(java.awt.event.ActionEvent evt) {
// String f= "jdbc:derby://localhost:1527/BStest";
String name=username.getText();
String gender=null;
String passw=String.valueOf(pass.getPassword());
String repassw=String.valueOf(repass.getPassword());
String phone2=phone.getText();
String emaill=email.getText();
boolean checkage=false,checknum=false,checkcap=false,checklaw=false,checkemail=false,checkdomain=false;
boolean checklen=false,checkbfat=false,checkpass=false,checkchar=false,checkgender=false;
boolean checkempty=true;
if(name.isEmpty()){//is text field empty
checkempty=false;
JOptionPane.showMessageDialog(null,"Add a username!");}
if(passw.isEmpty()){//is text field empty
checkempty=false;
JOptionPane.showMessageDialog(null,"Add a Password!");}
if(!repassw.equals(passw)){//confirmed password is the same for password
checkempty=false;
JOptionPane.showMessageDialog(null,"Type password Again!");
}
if(phone2.isEmpty()){//is text field empty
checkempty=false;
JOptionPane.showMessageDialog(null,"Add Phone number !");
}
if(emaill.isEmpty()){//is text field empty
checkempty=false;
JOptionPane.showMessageDialog(null,"Add email please !");
}
if (!m.isSelected()&& !female.isSelected()){//no gender selected
checkempty=false;
JOptionPane.showMessageDialog(null,"Choose a gender !!");}
else if (m.isSelected()&& female.isSelected()){//both selected it shoud be only one
checkempty=false;
JOptionPane.showMessageDialog(null,"Select only One !!");}
if(age.getText().isEmpty()){//is age text field has no input
checkempty=false;
JOptionPane.showMessageDialog(null,"Enter your age !!");}
Secondly checks the criteria for each text field as indicated in the comments below
if (m.isSelected()){// is female or male selected
checkgender=true;
gender="Male";
}
else if (female.isSelected()){
checkgender=true;
gender="Female";
}
int agee =Integer.parseInt(age.getText());
char c,c2=emaill.charAt(0);
String zereofive=phone2.substring(0, 2);//start with 05
String bfat = emaill.substring(0,emaill .indexOf("#"));//digits berfore #
String domain = emaill.substring(emaill .indexOf("#") + 1);//check domain
if(Character.isLetter(c2))//is first char off email iis letter
checkchar=true;
else
JOptionPane.showMessageDialog(null,"Emails only start with letters");
if (phone2.length()==10 && zereofive.equals("05"))//check length of phone number
checklen=true;
else
JOptionPane.showMessageDialog(null,"enter 10 digits for the phone number and starts with 05");
if(bfat.length()>=6 || bfat.length()<=15){//check digits before #
checkemail=true;
}
if(domain.equals("gmail.com") || domain.equals("hotmail.com")){//check domain of email
checkdomain=true;
}
else
JOptionPane.showMessageDialog(null,"Email domain is wrong");
if(agee>=18)//only can register in 18 or above
checkage=true;
else
JOptionPane.showMessageDialog(null,"You can't register because you are under 18. ");
if(passw.length()>7){// password at least 8 digit at least one captial and one small letter
checklen=true;
for (int i=0;i<passw.length();i++){
c=passw.charAt(i);
if(Character.isDigit(c))
checknum=true;
else if (Character.isUpperCase(c))
checkcap=true;
else if (Character.isLowerCase(c))
checklaw=true;
if(checknum && checkcap && checklaw )
checkpass=true;
}}
if(checkpass)//check of all 3 crietria of pass word is coorrect
checkpass=true;
else
JOptionPane.showMessageDialog(null,"password must be at least 8 digits \n at least 1 Upper Case letter \n at least 1 Lower Case letter \n at least 1 number \n");
and lastly stores in the database if criteria is meet and record is not exists
PreparedStatement reg,exist;
String query="INSERT INTO customer (Cu_name, Cu_password, Cu_age, Cu_gender, Cu_email, Cu_phone) VALUES (?, ?, ?, ?, ?, ?)";//enter user info in database
String record_exists="SELECT * FROM customer where Cu_name=? and Cu_password= ? and Cu_age=? and Cu_gender=? and Cu_email=? and Cu_phone=?";
try{
String f= "jdbc:derby://localhost:1527/BStest";
Connection connection = DriverManager.getConnection(
f, "meme", "Moudhi102");
reg=connection.prepareStatement(query);
exist=connection.prepareStatement(record_exists);
reg.setString(1, name);
reg.setString(2, passw);
reg.setInt(3, agee);
reg.setString(4, gender);
reg.setString(5, emaill);
reg.setString(6, phone2);
exist.setString(1, name);
exist.setString(2, passw);
exist.setInt(3, agee);
exist.setString(4, gender);
exist.setString(5, emaill);
exist.setString(6, phone2);
rs=exist.executeQuery();
if(rs==null){
if(checkpass &&checkage && !checkdomain && !checkemail && !checklen && checkchar && !checkgender && checkempty ){//if all criteria justified then add it to database
reg.executeUpdate();
JOptionPane.showMessageDialog(null,"Complete! new user added !! ");
}
}else//else it can't be added
{
JOptionPane.showMessageDialog(null, "Record already exists");
}
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex);
}
the problem is it doesn't show a message if record already exists in database and if I entered empty text in age + phone + email it shows the message that it is empty but in the NetBeans itself shows an error message in the output area like below
at
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at event_system.Sign_up.confirmActionPerformed(Sign_up.java:275)
at event_system.Sign_up.access$000(Sign_up.java:20)
at event_system.Sign_up$1.actionPerformed(Sign_up.java:70)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
and doesn't do the coding part of these three fields and show their messages even for password if criteria is not meet and other field inputs are ok is shows a continuous message of record exists and Can't register check/fill you information.Please help me i'm stuck and can't figure it out
Deal with your exception first before even considereing to deal with your other problems since it will prevent the other portions of your code to be run from the point of exception and therefore be the root cause to all your problems at this time.
You can not pass a Null String ("") to the Integer#parseInt() method:
int agee = Integer.parseInt(age.getText());
If the Text Field that is to contain an age is empty then the JTextField#getText() method will return a Null String (""). If you supply this to the Integer#parseInt() method (as you've done in the above code) or anything other than an integer value then a NumberFormatException is generated. You need to take care of this possible condition and the use of a Ternary Operator (aka Conditional Operator) may be all you need:
int agee = age.getText().trim().equals("") ? 0 : Integer.parseInt(age.getText().trim());
This however doesn't cover the fact that a alpha character might accidently be supplied within the Age text field. To cover that problem it may be just better to do:
String theAge = age.trim().getText();
int agee = 0;
// Regular Expression used to ensure a Integer
// Numerical String value was supplied.
if (theAge.matches("\\d+")) {
agee = Integer.parseInt(theAge);
}
In the above line of code, IF the Age text-field contains nothing or blank spaces then the agee variable is supplied a integer 0 value ELSE the Integer.parseInt() method is used with the contents of the Text Field to fill the agee variable.
On a side note:
You utilize a lot of boolean flags for each of your text fields so as to ensure validity and other things. From what I can see you actually don't need any of them since you are checking all fields and your requirements are that all those fields actually be filled:
boolean checkage=false, checknum=false, checkcap=false, checklaw=false,
checkemail=false,checkdomain=false;
boolean checklen=false, checkbfat=false, checkpass=false, checkchar=false,
checkgender=false;
boolean checkempty=true;
I would get rid of all of them and and not use a flag at all. If at any time within your code any one of your Text Fields does not meet validity within the confirmActionPerformed() event then nothing should be read from or written to the database. As the fields are checked for validity and any of those fields fail you simply need to display the fact via Message Box then when the User selects the OK button we set focus on the Text Field currently being checked (age.requestFocus();) then exit the event with a return; statement. Database code can never be reached unless all your text fields passes validity. Your event code might look like this:
private void confirmActionPerformed(java.awt.event.ActionEvent evt) {
// String f= "jdbc:derby://localhost:1527/BStest";
String name = username.getText().trim();
String gender = null;
String passw = String.valueOf(pass.getPassword());
String repassw = String.valueOf(repass.getPassword());
String phone2 = phone.getText().trim();
String emaill = email.getText().trim();
// NAME
//is Name text field empty
if (name.isEmpty()) {
JOptionPane.showMessageDialog(null, "Add a username!");
username.requestFocus();
return;
}
// PASSWORD
//is Password field empty
if (passw.isEmpty()) {
JOptionPane.showMessageDialog(null, "Add a Password!");
pass.requestFocus();
return;
}
/* A Regular Expression is used here to ensure your desired
password rules apply - Minimum of 8 characters in length,
at least 1 Uppercase Letter, at least 1 Lowercase letter,
at least 1 digit. */
if (!passw.matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)[a-zA-Z\\d]{8,}$")) {
JOptionPane.showMessageDialog(null, "Password must be:\n\n"
+ "- At least 8 characters in length,\n"
+ "- Contain at least 1 Uppercase letter,\n"
+ "- Contain at least 1 Lowercase letter,\n"
+ "- Contain at least 1 number.");
pass.requestFocus();
return;
}
// confirmed password is the same for password
if (!repassw.equals(passw)) {
JOptionPane.showMessageDialog(null, "Type password Again!");
repass.requestFocus();
return;
}
// PHONE
//is phone text field empty
if (phone2.isEmpty()) {//is text field empty
JOptionPane.showMessageDialog(null, "Add Phone number !");
phone.requestFocus();
return;
}
// starts with 05
String zereofive = phone2.substring(0, 2);
// check length of phone number
if (phone2.length() != 10 && !zereofive.equals("05")) {
JOptionPane.showMessageDialog(null, "enter 10 digits for the phone number and starts with 05");
phone.requestFocus();
return;
}
// E-MAIL
//is E-Mail text field empty
if (emaill.isEmpty()) {
JOptionPane.showMessageDialog(null, "Add email please !");
email.requestFocus();
return;
}
// E-Mail
char c, c2 = emaill.charAt(0);
String bfat = emaill.substring(0, emaill.indexOf("#"));//digits berfore #
String domain = emaill.substring(emaill.indexOf("#") + 1);//check domain
// is first char off email a letter
if (!Character.isLetter(c2)) {
JOptionPane.showMessageDialog(null, "Emails can only start with letters!");
email.requestFocus();
return;
}
//check digits before #
if (bfat.length() < 6 || bfat.length() > 15) {
JOptionPane.showMessageDialog(null, "Invalid digits in Email address!");
email.requestFocus();
return;
}
//check domain of email
if (!domain.equals("gmail.com") && !domain.equals("hotmail.com")) {
JOptionPane.showMessageDialog(null, "Email domain is wrong!");
email.requestFocus();
return;
}
// GENDER
//no gender selected
if (!m.isSelected() && !female.isSelected()) {
JOptionPane.showMessageDialog(null, "Choose a Gender!!");
return;
}
//both Genders are selected where it shoud be only one
else if (m.isSelected() && female.isSelected()) {
JOptionPane.showMessageDialog(null, "Select only One Gender!!");
return;
}
// is female or male selected
if (m.isSelected()) {
gender = "Male";
}
else if (female.isSelected()) {
gender = "Female";
}
// AGE
//is Age text field empty
String theAge = age.trim().getText();
if (theAge.isEmpty()) {
JOptionPane.showMessageDialog(null, "Enter your age !!");
age.requestFocus();
return;
}
int agee = 0; // Default
// Regular Expression used to ensure a Integer
// Numerical String value was supplied.
if (theAge.matches("\\d+")) {
agee = Integer.parseInt(theAge);
}
// only 18 + can register
if (agee < 18) {
JOptionPane.showMessageDialog(null, "You can't register because you are under 18!");
age.requestFocus();
return;
}
// DATABASE
Connection connection = null;
PreparedStatement reg, exist;
ResultSet rs = null;
String query = "INSERT INTO customer (Cu_name, Cu_password, Cu_age, Cu_gender, Cu_email, Cu_phone) VALUES (?, ?, ?, ?, ?, ?)";//enter user info in database
String record_exists = "SELECT * FROM customer where Cu_name=? and Cu_password= ? and Cu_age=? and Cu_gender=? and Cu_email=? and Cu_phone=?";
try {
String f = "jdbc:derby://localhost:1527/BStest";
connection = DriverManager.getConnection(f, "meme", "Moudhi102");
reg = connection.prepareStatement(query);
exist = connection.prepareStatement(record_exists);
reg.setString(1, name);
reg.setString(2, passw);
reg.setInt(3, agee);
reg.setString(4, gender);
reg.setString(5, emaill);
reg.setString(6, phone2);
exist.setString(1, name);
exist.setString(2, passw);
exist.setInt(3, agee);
exist.setString(4, gender);
exist.setString(5, emaill);
exist.setString(6, phone2);
rs = exist.executeQuery();
if (rs == null) {
reg.executeUpdate();
JOptionPane.showMessageDialog(null, "Complete! new user added !! ");
}
// User Already Exists In Database
else {
JOptionPane.showMessageDialog(null, "User already exists");
}
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
finally {
if (reg != null) {
reg.close();
}
if (rs != null) {
rs.close();
}
if (connection != null) {
connection.close();
}
}
}
Age may not necessarily be a good piece of criteria to use in your query WHERE clause when checking database records for a duplicate record of a particular User. It only enforces the fact that each record is only valid for a single year. Things change and Age, E-Mails, Phone Numbers, etc are some of those things that can change often. There is obviously nothing wrong with the concept if only the Name and Password are used for access validity (which should suffice for most cases) and the remaining criteria is merely used for indicating that updating is required to the User data account.
You should consider Supplied Passwords to be hashed and it is the hash that is stored in database. When a User supplies a password then that password is hashed and compared to a hash already stored in database. No one, including yourself should ever know what the password truly is. Only the User should ever know what the password might be. jBCrypt works pretty good for this. To hash a password using this library:
Imports:
import org.mindrot.jbcrypt.BCrypt;
import static org.mindrot.jbcrypt.BCrypt.hashpw;
A Class Member Varaible:
// Define the BCrypt WORKLOAD to use when generating
// password hashes. 10-31 is a valid value.
private static final int WORKLOAD = 12;
To Hash a plaintext password so as to store in database:
/**
* This method can be used to generate a string representing an account
* password suitable for storing in a database. It will be an OpenBSD-style
* crypt(3) formatted hash string of length=60 The BCrypt WORKLOAD is
* specified in the above static variable, a value from 10 to 31. A WORKLOAD
* of 12 is a very reasonably safe default. This automatically handles
* secure 128-bit salt generation and storage within the hash.
*
* #param password_plaintext The account's plaintext password as provided
* during account creation, or when changing an
* account's password.
*
* #return String - a string of length 60 that is the bcrypt hashed password
* in crypt(3) format.
*/
public static String hashPassword(String password_plaintext) {
String salt = BCrypt.gensalt(WORKLOAD);
String hashedPassword = hashpw(password_plaintext, salt);
return hashedPassword;
}
To check a plaintext password with a stored hash from database:
/**
* This method can be used to verify a computed hash from a plaintext (e.g.
* during a login request) with that of a stored hash from a database. The
* password hash from the database must be passed as the second argument.
*
* #param passwordAsPlainText The accounts plaintext password, as provided
* during a login request
*
* #param storedEncryption The accounts stored password hash, retrieved
* from the authorization database
*
* #return boolean - true if the password matches the password of the stored
* hash, false otherwise
*/
/*
public static boolean checkPassword(String passwordAsPlainText, String storedEncryption) {
boolean passwordVerification;
if (null == storedEncryption || !storedEncryption.startsWith("$2a$")) {
throw new java.lang.IllegalArgumentException(
"Invalid encryption provided for comparison");
}
passwordVerification = checkpw(passwordAsPlainText, storedEncryption);
return passwordVerification;
}
Here's the table (tblemployees)
How can I convert my code that used text files to a code that will use database (tables).
int intcurrentLine = -1;
String[] strLineSplit = (sb.toString()).split("\\r?\\n"); // converts sb to string then splits it by line
int intNumElements = strLineSplit.length; // number of elements
while (intcurrentLine != (intNumElements - 1)) {
intcurrentLine++;
String[] strWords = (strLineSplit[intcurrentLine]).split(" ", 2); // splits the current line by the first instance(space)
if (strEmpID.equals(strWords[0])) { // checks if the employee ID is available
JOptionPane.showMessageDialog(null, "Welcome " + strWords[1] + ", you have successfully logged in.");
strCheck = 1; // to confirm and go to time in and out process
break;
}
if ((intcurrentLine + 1) == intNumElements) { // condition to state that ID cant be found from the employee list
JOptionPane.showMessageDialog(null, "No such employee, please check the ID No. that you entered.");
}
}
Now I would like to search a column if it contains an Employee number. How do I put it to a condition, I've been searching but unable to find a clear answer. They only put how to search like this
String queryCheck = "SELECT * from messages WHERE EmpIDNo = 'COMSCI0001'";
ResultSet res = st.executeQuery(queryCheck);
then I'm lost, how to make a condition where if the employee no. doesn't exists something would happen else something would happen. I'm just confuse how to make a condition for that.
You can do like this:
String queryCheck = "SELECT * FROM messages WHERE EmpIDNo = 'COMSCI0001' LIMIT 1";
ResultSet res = st.executeQuery(queryCheck);
boolean exists = res.next();
The boolean variable exists will indicate whether a matching record exists or not.
Notice that I added LIMIT 1 at the end of the SQL as an optimization to avoid fetching more data than you really need.
I'm fairly new to java and have been attempting to read a very difficult .txt file and input it into my MySQL DB.
To me, the file has some very weird delimiting rules. the delimiting seems to be all commas but other parts just do not make any sense. here is a few examples:
" "," "," "," "," "
" ",,,,,,," "
" ",0.00," "
" ",," ",," ",," "
What I do know is that all fields containing letters will be the normal ,"text", format.
all columns that only have numerals will follow this format: ,0.00, except for the first column which follows the normal format "123456789",
Then anything with no data will alternate between ,, or ," ",
I have been able to get the program to read correctly with java.sql.Statement but I need it to work with java.sql.PreparedStatement
I can get it to work with only a few columns selected but I need this to work with 100+ columns and some fields contain commas e.g. "Some Company, LLC"
Here is the code I currently have but I am at a loss as to where to go next.
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
public class AccountTest {
public static void main(String[] args) throws Exception {
//Declare DB settings
String dbName = "jdbc:mysql://localhost:3306/local";
String userName = "root";
String password = "";
String fileName = "file.txt";
String psQuery = "insert into accounttest"
+ "(account,account_name,address_1,address_2,address_3) values"
+ "(?,?,?,?,?)";
Connection connect = null;
PreparedStatement statement = null;
String account = null;
String accountName = null;
String address1 = null;
String address2 =null;
String address3 = null;
//Load JDBC Driver
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("JDBC driver not found.");
e.printStackTrace();
return;
}
//Attempt connection
try {
connect = DriverManager.getConnection(dbName,userName,password);
}
catch (SQLException e) {
System.out.println("E1: Connection Failed.");
e.printStackTrace();
return;
}
//Verify connection
if (connect != null) {
System.out.println("Connection successful.");
}
else {
System.out.println("E2: Connection Failed.");
}
BufferedReader bReader = new BufferedReader(new FileReader(fileName));
String line;
//import file into mysql DB
try {
//Looping the read block until all lines in the file are read.
while ((line = bReader.readLine()) != null) {
//Splitting the content of comma delimited file
String data[] = line.split("\",\"");
//Renaming array items for ease of use
account = data[0];
accountName = data[1];
address1 = data[2];
address2 = data[3];
address3 = data[4];
// removing double quotes so they do not get put into the db
account = account.replaceAll("\"", "");
accountName = accountName.replaceAll("\"", "");
address1 = address1.replaceAll("\"", "");
address2 = address2.replaceAll("\"", "");
address3 = address3.replaceAll("\"", "");
//putting data into database
statement = connect.prepareStatement(psQuery);
statement.setString(1, account);
statement.setString(2, accountName);
statement.setString(3, address1);
statement.setString(4, address2);
statement.setString(5, address3);
statement.executeUpdate();
}
}
catch (Exception e) {
e.printStackTrace();
statement = null;
}
finally {
bReader.close();
}
}
}
Sorry if it's not formatted correctly, I am still learning and after being flustered for several days trying to figure this out, I didn't bother making it look nice.
My question is would something like this be possible with such a jumbled up file? if so, how do I go about making this a possibility? Also, I am not entirely familiar with prepared statements, do I have to declare every single column or is there a simpler way?
Thanks in advance for your help.
EDIT : To clarify what I need is I need to upload a txt file to a MySQL database, I need a way to read and split(unless there is a better way) the data based on either ",", ,,,,, ,0.00, and still keep fields together that have commas in the field Some Company, LLC. I need to do this with 100+ columns and the file varies from 3000 to 6000 rows. Doing this as a prepared statement is required. I'm not sure if this is possible but I appreciate any input anyone might have on the matter.
EDIT2 : I was able to figure out how to get the messy file sorted out thanks to rpc1. instead of String data[] = line.split("\",\""); I used String data[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); I still had to write out each variable to link it to the data[] then write out each statement.setString for each column as well as write the replaceALL("\"", ""); for each column but I got it working and I couldn't find another way to use prepared statements. Thank you for all your help!
You can cycles
for example:
String psQuery = "insert into accounttest"
+ "(account,account_name,address_1,address_2,address_3,..,adrress_n) values"
+ "(?,?,?,?,?,?,..,?)"; //you have to put m=n+2 values
.....
//you can change separator
String data[] = line.replace("\",\"",";").replace("\"","").split(";");
for(int i=0;i<m;i++)
{
if(i<data.length) //if index smaller then array siz
statement.setString(i+1, data[i]);
else
statement.setString(i+1, ""); //put null
}
statement.executeUpdate();
P.S. if your csv file large use batch insert (addBatch())
and use Pattern to split string
Pattern p = Pattern.compile(";","");
p.split(st);
EDIT
Try this split function
private static Pattern pSplit = Pattern.compile("[^,\"']+|\"([^\"]*)\"|'([^']*)'"); //set pattern as global var
private static Pattern pReplace = Pattern.compile("\"");
public static Object[] split(String st)
{
List<String> list = new ArrayList<String>();
Matcher m = pSplit.matcher(st);
while (m.find())
list.add( pReplace.matcher(m.group(0)).replaceAll("")); // Add .replace("\"", "") to remove surrounding quotes.
return list.toArray();
}
for example
intput string: st="\"1212\",\"LL C ,DDD \",\"CA, SPRINGFIELD\",232.11,3232.00";
split on 5 item array:
1212
LL C ,DDD
CA, SPRINGFIELD
232.11
3232.00
EDIT2
this example solves all your problems (even empty values)
private static Pattern pSplit = Pattern.compile(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
public static String[] split2(String st)
{
String[] tokens = pSplit.split(st);
return tokens;
}
I was able to figure out both issues that I was having by this little bit of code. Again, thanks for all of your help!
for (String line = bReader.readLine(); line != null; line = bReader.readLine()) {
//Splitting the content of comma delimited file
String data[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
//Iterating through the file and updating the table.
statement = connect.prepareStatement(psQuery);
for (int i =0; i < data.length;i++) {
temp = data[i];
temp = temp.replaceAll("\"", "");
statement.setString(i+1, temp);
}
statement.executeUpdate();
}
I have a few buttons on my panel and everytime I click on it an input dialog box appears. It has an inbuilt cancel button. Now, when i click on the cancel button in the beginning of the code without entering the quantity in the dialog box, it says, "This is an invalid" number. This line has to only appear if the user enters alphabets or symbols, and not on pressing cancel. Can we solve this?
First you need a way to decide if a String represents a number; the method below uses Double.valueOf() to decide.
private Double valueOf(String s) {
try {
return Double.valueOf(s);
} catch (NumberFormatException e) {
return null;
}
}
Here's an example of how you might use the method:
private void display() {
String input = JOptionPane.showInputDialog(
null, "Enter a number?", "Number", JOptionPane.QUESTION_MESSAGE);
Double value = valueOf(input);
JOptionPane.showMessageDialog(null, "The value " + input
+ " is " + (value != null ? "valid" : "invalid") + ".");
}
See also How to Make Dialogs.
Try doing,
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if (Input.equals(""))
{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}
The following link explains it even better: Simple Data Validation.
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if
(Input.matches(("((-|\+)?[0-9]+(\.[0-9]+)?)+"))) {
JOptionPane.showMessageDialog(null,"valid number");
}
else{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}