I get an SQLexception error Coloumn Count does not match value count at row 1.
I have tried altering the databse as checked the statements accordinly but fail to recognise the issue. Anny suggestions please...
JButton btnNewButton_1 = new JButton("Save");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String PHN = textField_a.getText();
String Week1 = textField_4.getText();
String Week2 = textField_5.getText();
String Week3 = textField_6.getText();
String Week4 = textField_7.getText();
if (PHN.equals("") || (Week1.equals("") || (Week2.equals("") || (Week3.equals("") || (Week4.equals("") ))))) {
JOptionPane.showMessageDialog(frmTemplate, "Please enter values in all the fields.");
}
else {
try {
db.stmt.executeUpdate("INSERT INTO weight (PHN, Week1, Week2, Week3, Week4)"+"VALUES"+"("+"'"+PHN+"',"+"'"+Week1+"',"+"'"+Week2+"'"+"'"+Week3+"'"+"'"+Week4+"')");
JOptionPane.showMessageDialog(frmTemplate, "New Record Added");
textField_a.setText(null);
textField_4.setText(null);
textField_5.setText(null);
textField_6.setText(null);
textField_7.setText(null);
}
catch (SQLException e) {
JOptionPane.showMessageDialog(frmTemplate, "The value you have entered already exist");
e.printStackTrace();
}
}
}
});
It looks like you're missing a few commas. Try looking into the PreparedStatement class to create you're statements. It's a lot easier to work with than trying to build strings of your query and it protects you from sql injection. Good luck!
Related
I tried
if(jRadioButton1.isSelected() ||(jRadioButton2.isSelected()) {
jGenderGroup.getSelection().getActionCommand();
} else {
jGndrErrorLabel.setText("Select gender.")
}
But controller doesn't stop after highlighted line it does go ahead to final line and throw NullPointerException
customers.setGender(jGenderGroup.getSelection().getActionCommand());
Where customers is POJO class.
How I can get rid of this?
try this :)
jRadioButton1.setActionCommand("Male");
jRadioButton2.setActionCommand("Female");
if(!jGenderGroup.isChecked()){
jLable1.setText("Please Select Gender");
}
if(jRadioButton1.isSelected())
{
//Male
}
else if(jRadioButton2.isSelected())
{
//Female
}
else
{
// no radio button has been selected
}
or alter your code like
if(jGenderGroup.getSelection() != null)
{
customer.setGender(jGenderGroup.getSelection().getActionCommand())
} else {
jGndrErrorLabel.setText("Select gender.")
}
I simply removed ButtonGroup jGenderGroup
and perform conditions for jRadioButton1 and jRadioButton2 at last instead of middle and as I had commented I can not set String gender = new String(); as
gender = jRadioButton1.getActionCommand();
Within conditional block because of POJO
So I just tricked that put it at the end like this :
String gender = new String();
if (jRadioButton1.isSelected()) {
gender = jRadioButton1.getActionCommand();
} else if (jRadioButton2.isSelected()) {
gender = jRadioButton2.getActionCommand();
} else {
jGndrErrorLabel.setText("Select gender.");
jGndrErrorLabel.setForeground(Color.red);
}
That's what I expected
Thanks for all of your time and efforts.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
i'm trying to disable some JButton with different account(something like permissions), here is my code to be more clear question...
try
{
stat = conn.prepareStatement(sql);
rs=stat.executeQuery();
while(rs.next())
{
System.out.println("found");
String _name= rs.getString("name");
String _pass = rs.getString("password");
String _stat = rs.getString("status");
if (_name == name && pass == _pass && _stat == "admin")
{
new SecondFrame().setVisible(true);//all buttons works as admin
}
else if(_name == name && pass == _pass && _stat == "moderator")
{
SecondFrame ob = new SecondFrame();
ob.admin_btn.setEnabled(false);//just user+moderator button works
}
else if(_name == name && pass == _pass && _stat == "user")
{
SecondFrame ob = new SecondFrame();
ob.admin_btn.setEnabled(false);
ob.moderator_btn.setEnabled(false);
// just user button works
}
}
}
catch (SQLException SQLe)
{
System.out.println("not executed"+SQLe);
}
... but i can't disable buttons like this(syntax is wrong), is there a way to make buttons disabled from this class?
thanks for help
1. String comparison error
Your main error is that you compare Strings with == in your code. In Java, this comparator will only work properly with basic types like long, double, boolean etc. therefore : use _stat.equals("moderator").
The reason why == won't work is that it compares the object's memory address instead of the inner values.
here's a code you can use :
try {
stat = conn.prepareStatement(sql);
rs=stat.executeQuery();
while(rs.next()) {
System.out.println("found");
String _name= rs.getString("name");
String _pass = rs.getString("password");
String _stat = rs.getString("status");
if (_name.equals(name) && pass.equals(_pass) && _stat.equals("admin")) {
new User().setVisible(true);//all buttons works as admin
} else if(_name.equals(name) && pass.equals(_pass) && _stat.equals("moderator")) {
SecondFrame ob = new SecondFrame();
ob.admin_btn.setEnabled(false);//just user+moderator button works
} else if(_name.equals(name) && pass.equals(_pass) && _stat.equals("user")) {
SecondFrame ob = new SecondFrame();
ob.admin_btn.setEnabled(false);
ob.moderator_btn.setEnabled(false);
// just user button works
}
}
} catch (SQLException SQLe) {
System.out.println("not executed"+SQLe);
}
2. Access related issue
After that, your code may still not work since you may have an access issue. Check if your SecondFrame class's button attributes are public. If they are not, you would better create a method that will set enabled inside that class for you with the user's access. Something like this :
public void setButtonAccess (String pAccess) {
user_button.setEnabled(false);
moderator_btn.setEnabled(false);
admin_btn.setEnabled(false);
if (pAccess.equals("user")) {
user_btn.setEnabled(true);
} else if (pAccess.equals("moderator")) {
user_btn.setEnabled(true);
moderator_btn.setEnabled(true);
} else if (pAccess.equals("admin")) {
user_button.setEnabled(true);
moderator_btn.setEnabled(true);
admin_btn.setEnabled(true);
}
}
Although the use of an enum would suit this situation pretty well... But for more information, I suggest the following readings :
Enum Types in Java
The switch statement
Whenever I enter a password under 10 characters it gives me Password cannot exceed 10 characters.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String Username = uName.getText().toString();
String Pass1 = uPass.getPassword().toString();
String Confirm = uConfirm.getPassword().toString();
String Status = "OFFLINE";
int PassLen = Pass1.length();
if (Username.equals("") || Pass1.equals("") || Confirm.equals("") || name.equals(""))
{
JOptionPane.showMessageDialog(null, "You cannot leave any fields blank when creating an Account. Please Try Again");
}
else if ((uPass.getPassword().toString()).length()>10)
{
uPass.setText("");
uConfirm.setText("");
JOptionPane.showMessageDialog(null, "Password cannot exceed a maximum of 10 characters.");
}
else if (!Pass1.equals(Confirm))
{
uConfirm.setText("");
lblError1.setText("Passwords Do Not Match.");
lblError2.setText("Please re-enter your Password.");
}
else
{
try {
DB_Connect connect = new DB_Connect();
ResultSet rs = connect.queryTbl("SELECT * FROM ACOUNTS");
boolean AlreadyUser = false;
String User;
while (rs.next())
{
User = rs.getString("Username");
if(Username.equals(User))
{
AlreadyUser = true;
}
}
if (AlreadyUser==false)
{
connect.updateTbl("INSERT INTO NBUSER.ACCOUNTS (USERNAME,PASSWORD,STATUS,NAME)VALUES ('"+Username+"','"+Pass1+"','"+Status+"','"+name+"')");
JOptionPane.showMessageDialog(null, "Account Created Successfully !");
this.dispose();
new Topics().setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null, "The Username you have selected already exists. Please select a different Username");
uPass.setText("");
uConfirm.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(CreateAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Since you're obviously using Swing, it is also very likely that you use a JPasswordField for your passwords. So let's see, what getPassword really does:
public char[] getPassword()
Returns the text contained in this TextComponent. If the underlying document is null, will give a NullPointerException. For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero.
Returns: the text
As you can see, it returns your password in a char[] and since this class doesn't override toString your call of uPass.getPassword().toString() results in something like:
[C#1d44bcfa
which is the result of calling Object#toString.
The length of this String is 11 and therefore larger then 10 and your else if block (else if ((uPass.getPassword().toString()).length()>10)) will be entered.
To fix that, call the String constructor String(char[]) like:
String Pass1 = new String(uPass.getPassword());
Please use this just as a "quick fix" for your current problem and try to find a way to use the originally returned char[]. As mentioned by the quoted JavaDoc it is recommened the "clean" the char array after using it, so the password won't be stored there anymore. By creating a String from the array, using new String(uPass.getPassword()), you're creating another object in the heap which contains the password and which also needs to be removed from there. So it would add more work for you.
I am trying to learn Java so I apologize if this is a rookie question. I have researched enough before asking this question here. I appreciate your time and guidance here.
I have written a simple application where I am asking user to enter information like "Serverprocessorspeed", "RAM" etc
I need the information entered by the user in the fields "Serverprocessorspeed", "RAM" to be passed to Action Listener. These values are in turn sent to a database server.
Cloudbroker() {
f1 = new JFrame("Cloud Broker");
serverprocessorspeed = new JLabel("serverprocessorspeed :");
RAM = new JLabel("RAM :");
serverstorage = new JLabel("serverstorage :");
latency = new JLabel("latency :");
Region = new JLabel("Region");
txtserverprocessorspeed = new JTextField(60);
txtRAM = new JTextField(60);
txtserverstorage = new JTextField(60);
txtlatency = new JTextField(60);
txtRegion = new JTextField(60);
btnClose = new JButton("Close");
btnSave = new JButton("Save");
btnDelete = new JButton("Delete");
btnUpdate = new JButton("Update");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The information you entered has been saved");
Connection conn1 = null;
try {
String dbURL1 =
"jdbc:sqlserver://localhost\\SQLEXPRESS:1433;"
+ "databaseName=dbcloudbroker;user=XXX;password=XXXX";
System.out.println("this is connection inside the SAVE button");
conn1 = DriverManager.getConnection(dbURL1);
Statement stmt1 = conn1.createStatement();
// I need these values to be the ones the user
// enters in the feilds serverprocessorspeed and RAM.
stmt1.executeUpdate(
"INSERT INTO cloudbrokertable " + "VALUES(XXXX, XXXXX)");
} catch (SQLException e1) {
e1.printStackTrace();
} finally {
try {
if (conn1 != null && !conn1.isClosed()) {
conn1.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Based upon the suggestion I received, I edited my code accordingly
String speed = txtserverprocessorspeed.getText();
String ram = txtRAM.getText();
String storage = txtserverstorage.getText();
String latency = txtlatency.getText();
String region = txtRegion.getText();
System.out.println(speed);
stmt1.executeUpdate("INSERT INTO cloudbrokertable VALUES ('"+speed +"','"+ram+"','"+storage+"','"+latency+"','"+region+"')");
Now get the following error - com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ')'.
The value is correctly passed into the variable speed and I can print it out.
I need the information entered by the used in the fields "Serverprocessorspeed", "RAM" to be passed to Action Listener. These values are in turn sent to a database server.
No, you don't, this isn't how this works (sorry). But, based on you code snippet, I would suggest you already have access to the information you need, for example...
btnSave.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String ram = txtRAM.getText();
String speed = txtserverprocessorspeed.getText();
String storage = txtserverstorage.getText();
String latency = txtlatency.getText();
String region = txtRegion.getText();
//...
It's the problem with your SQL statement. You need to check if it does work.
Simply open your DB to test it with a sample statement like:
INSERT INTO cloudbrokertable VALUES ('100','DDR2','500','1000','US')
If this doesn't work it means you need to fix your statement.
I hope this help.
I am building java project in inventory management. following is the code i used for inserting color in database using equalsIgnorecase but it continuous showing Already exist. Please some one fix my code.
thanks
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
if(txtNewColor.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Fields should not be empty");
}
else
{
try {
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(cl));
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
if (color==0)
{
String strdata="Insert into color_details (Color)values(?)";
ps=DbConnection.cn.prepareStatement(strdata);
ps.setString(1, txtNewColor.getText());
ps.execute();
JOptionPane.showMessageDialog(null, "New Color Added Successfully");
cleartext();
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
refreshTable();
}
Try change if(cl.equalsIgnoreCase(cl)); to if(c.equalsIgnoreCase(cl))
Had not spotted the semi-colon at the end of your if statement
You are comparing the same String again. So It always results in a true, also the ; will skip even if they match. Remove it.
String c = txtNewColor.getText();
ps =DbConnection.cn.prepareStatement("Select Color from color_details");
rs = ps.executeQuery();
int color = 0;
while (rs.next())
{
String cl= rs.getString("Color");
if(cl.equalsIgnoreCase(c))
{
JOptionPane.showMessageDialog(null, "Aready Exist");
txtNewColor.setText("");
color=1;
}
}
You used same two strings to compare. so change c.equalsIgnoreCase(c1). Also make sure you have removed trailing spaces when getting input from text fields. it may makes your comparison fail.
String c = txtNewColor.getText().trim();
Remove the semi colon after if clause
if(cl.equalsIgnoreCase(cl)); ---> if(cl.equalsIgnoreCase(cl))