Following code is to enable button greceived_btnwhen result set contain data.
But the button is not enabling when the SQL criteria met.
What is the error here?
public void enableBtn() throws SQLException{
greceived_btn.setEnabled(false);
if(poNo.getSelectedItem()!=null){
String no = poNo.getSelectedItem().toString();
String not="no";
String sql = "SELECT * FROM pointoinvoce WHERE PONo=? AND GoodsRecieved=?";
pst=conn.prepareStatement(sql);
pst.setString(1, no);
pst.setString(2, not);
rs=pst.executeQuery();
if(rs.next()){
greceived_btn.setEnabled(true);
}else{
greceived_btn.setEnabled(false);
}
}
}
Related
here is my code for the method that I created for my login form.
Everytime "login failed " message commes up even if I entered correct username and password.
What can be wrong here.
public class Controller {
#FXML
private Button cancelbutton;
#FXML
private Label loginmessagelabel;
#FXML
private PasswordField password1;
#FXML
private TextField username1;
PreparedStatement pst;
ResultSet rs;
public void validatelogin() throws SQLException, ClassNotFoundException {
String jdbcURL = "jdbc:mysql://localhost/medibase";
String username = "root";
String password = "0852";
Connection connection = DriverManager.getConnection(jdbcURL,username,password);
Class.forName("com.mysql.jdbc.Driver");
pst=connection.prepareStatement("SELECT * FROM user_account WHERE username=? and password=?");
pst.setString(1, String.valueOf(username1));
pst.setString(2, String.valueOf(password1));
rs = pst.executeQuery();
if(rs.next()){
loginmessagelabel.setText("Congratulations");
} else{
loginmessagelabel.setText("Login failed");
}
}
I found the mistake and fixed it
here are the changes that I made.
String uname = username1.getText();
String psd = password1.getText();
pst=connection.prepareStatement("SELECT * FROM user_account WHERE
username=? and password=?");
pst.setString(1, uname);
pst.setString(2, psd);
I took separate variables and assigned the vales form the textboxes by useing getText() method.
I have this method here - whenever I comment out the MySQL section, from String query to pst.close() - the code works fine. However, if I don't, then it gives me the error of Connection Reset. I am using a socket between a client and a server for your information. How would I fix this? Or it it a problem that does not deal with MySQL?
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
Connection connection = establishConnection();
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
String query = "insert into test(`username`, `password`, `email`, `fullname`) values (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered!";
}
return returnStatement;
}
You should probably have a connection.close() before the return.
Or, if you are in a relatively new version of JRE, you could possibly achieve the same with try-with-resource.
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
try (Connection connection = establishConnection()) {
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
String query = "insert into test(`username`, `password`, `email`, `fullname`) values (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered!";
}
}
return returnStatement;
}
This will ensure that your connection closes when the try block finishes. However, that would require that the Connection class implements the AutoCloseable interface.
I think the connection is getting established and not getting closed, might be the issue.
Here is what works for me, as suggested by #Binaek Sarkar (I modified it a little bit):
public static String doAddUser(String username, String password, String email, String fullname) throws SQLException {
String returnStatement = "";
try {
if(email.isEmpty() || password.isEmpty()) {
returnStatement = "CreateFailure: Some fields are left blank. Please note that all fields are required. Please try again";
}
else {
Connection connection = null;
connection = MySQLConnection.dbConnector();
String query = "INSERT INTO `test`(`username`, `password`, `email`, `fullname`) VALUES (?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
pst.setString(3, email);
pst.setString(4, fullname);
pst.executeUpdate();
pst.close();
returnStatement = "CreateSuccess: You are now registered! You will redirected to the login page now. ";
}
}catch(Exception e) {returnStatement = "Invalid. Please try again!";}
return returnStatement;
}
I have a problem with this piece of code. When I pass user and pass arguments to isLogin fucntion it throws ORA-01008 errror. I am connected to Oracle database using jdbc.
public boolean isLogin(Connection conn, String user, String pass) throws SQLException{
String sql = "SELECT * FROM PRACOWNIK WHERE imie =? AND nazwisko =? ";
PreparedStatement stmt;
ResultSet rs;
try {
stmt = conn.prepareStatement(sql);
stmt.setString(1, user);
stmt.setString(2, pass);
rs = stmt.executeQuery(sql);
if(rs.next()){
return true;
}
else {
return false;
}
} catch (SQLException e){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error ");
alert.setContentText(e.getMessage());
alert.showAndWait();
return false;
}
}
I use this function in Controller class
public class Controller implements Initializable{
public Pracownik pracownik = new Pracownik();
#FXML
private Label isConnected;
#FXML
private TextField txtUsername;
#FXML
private TextField txtPass;
private Connection conn;
// private ObservableList<Pracownik> lista = FXCollections.observableArrayList();
public void initialize(URL url, ResourceBundle rb){
conn = DBConnection.getConnection();
// lista = new Pracownik().getAll(conn);
}
public void login(ActionEvent event){
try {
if(pracownik.isLogin(conn, txtUsername.getText(), txtPass.getText())){
isConnected.setText("Correct");
}
else{
isConnected.setText("False");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And this is a error message
Caused by: Error : 1008, Position : 0, Sql = SELECT pesel FROM PRACOWNIK WHERE imie =:1 AND nazwisko =:2 , OriginalSql = SELECT pesel FROM PRACOWNIK WHERE imie =? AND nazwisko =? , Error Msg = ORA-01008: not all variables bound
When I use normal Select query just to print the table everything is fine.
You should NOT specify the SQL query again. It's already specified. Change the line:
rs = stmt.executeQuery(sql); // method from java.sql.Statement
to:
rs = stmt.executeQuery(); // method from java.sql.PreparedStatement
The first method does not take parameters into consideration and runs the SQL "as is"... and therefore you get the error you mention.
private void UpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Update
try{
if(!(jTextField1.getText().isEmpty())){
Connection myConn= null;
Statement myStmt= null;
ResultSet myRs= null;
String user= "root";
String pass= "passwd14";
//Get Connection to database
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/company",user, pass);
//Create a Statement
myStmt = myConn.createStatement();
//Prepared Statement
PreparedStatement pst=null;
try{
String on= jTextField1.getText();
//Prepare statement Execution
String sql2 = "UPDATE amazon SET name =?, mob =?, oddt =? FROM amazon WHERE odn ='"+on+"'";
pst=myConn.prepareStatement(sql2);
//pst.setString(4,jTextField1.getText());
pst.setString(1,jTextField2.getText());
pst.setString(2,jTextField6.getText());
pst.setString(3,jTextField5.getText());
pst.executeUpdate();
//Update ComboBox
String s= (String)jComboBox1.getSelectedItem();
jComboBox1.setSelectedItem(s);
String s2= (String)jComboBox2.getSelectedItem();
jComboBox1.setSelectedItem(s2);
JOptionPane.showMessageDialog(this,"Record Saved..");
}catch (Exception e){
JOptionPane.showMessageDialog(this,"Error");
}
}
}catch (Exception ex){
JOptionPane.showMessageDialog(this," This Error.. Keeps Showing up");
}
}
This is the database I want to update :
amazon(name, mob, iss, stat, oddt, odn)
that is (name, mobile, issue, status, order_details, orderno)
Update Query
It will work
String sql2 = "UPDATE amazon SET name =?, mob =?, oddt =? WHERE odn ='"+on+"'";
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
Connection conn=DbCon.conDB();
//String Mname =jComboBox1.getSelectedItem().toString();
String sql="delete Name from nowshowingmovie where Name = '"+jComboBox1.getSelectedItem().toString()+"'";
try{
pst=conn.prepareStatement(sql);
// pst.executeQuery();
pst.executeUpdate(sql);
JOptionPane.showMessageDialog(null,"Movie Deleted Sucessfully");
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null, e);
}
}
2 issues:
In general the syntax for DELETE is
String sql = "delete from nowshowingmovie where Name = '"+jComboBox1.getSelectedItem().toString()+"'";
PreparedStatement doesn't use the SQL String, i.e. just use pst.executeUpdate()
Side note: Since you're already using a PreparedStatement you can use a placeholder to avoid SQL injection attacks rather than using String concatenation.
String sql = "delete from nowshowingmovie where Name = ?";
pst.setString(1, jComboBox1.getSelectedItem().toString());
pst.executeUpdate();