How to fix ORA-01008 : Not all variables bound - java

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.

Related

java.sql.SQLException: Column 'Max(category_id' not found

Here is my code. It gives me an exception error says "java.sql.SQLException: Column 'Max(category_id' not found.". Please help. Thanks in advance.
enter code here
public class Category extends javax.swing.JFrame {
/**
* Creates new form Category
*/
public Category() {
initComponents();
DisplayTable();
autoID();
}
//Display Table
private void DisplayTable() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
String sql = "SELECT * FROM category";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public void autoID() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT Max(category_id) from category");
rs.next();
rs.getString("Max(category_id)");
if(rs.getString("Max(category_id") == null) {
CategoryIDField.setText("C0001");
}
else {
Long id = Long.parseLong(rs.getString("Max(category_id").substring(2, rs.getString("Max(category_id").length()));
id++;
CategoryIDField.setText("C0" + String.format("%03d", id ));
}
}
catch(ClassNotFoundException e) {
Logger.getLogger(Category.class.getName()).log(Level.SEVERE, null, e);
}
catch(SQLException e) {
Logger.getLogger(Category.class.getName()).log(Level.SEVERE, null, e);
}
}
The column has a default name but it isn't the same as the function, the easiest option would be to change all
rs.getString("Max(category_id)");
to
rs.getString(1);
Alternatively, name the column in your query. Like,
ResultSet rs = s.executeQuery("SELECT Max(category_id) AS FRED from category");
then use
rs.getString("FRED");
for example. Finally, you should be using getInt or getLong if the column is of those types (which I suspect because you are taking the MAX).
I think in the line
if(rs.getString("Max(category_id") == null) {
CategoryIDField.setText("C0001")
the quote should be after the round bracket.
use alisa
select Max(category_id) as xxx from category

MySQL Prepared Statement not reading from JavaFX Textfield

I am stuck with this for a while and I am not sure how to fix this. The problem is my SQL query does not get the input from javaFX textfield and passwordfield(I am building a login window).
If I enter the values manually rather than getting them from a textfield the program work fine, otherwise nothing happens when you press login button. The problem occurs at the following lines, of course with no error messages:
preparedStatement.setString(1,txtUserName.getText());
preparedStatement.setString(2,txtPassword.getText());
Here is the full code:
public class LoginWindow implements Initializable{
#FXML
private TextField txtUserName;
#FXML
private PasswordField txtPassword;
#FXML
private Button btnLogin;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
// Setting the login button.
#FXML
private void setBtnLogin(ActionEvent event) {
try {
connection = DBUtilities.getConnection();
String sqlQuery = "SELECT * FROM user_login_details WHERE User_Name = ? AND User_Password = ?";
preparedStatement = connection.prepareStatement(sqlQuery);
preparedStatement.setString(1,txtUserName.getText());
preparedStatement.setString(2,txtPassword.getText());
resultSet = preparedStatement.executeQuery();
if(resultSet.next()) {
DBUtilities.showInforMsg("Logged in:", "You have logged in!");
} else {
DBUtilities.showErrorMsg("Error:", "Invalid username or password");
}
}catch (Exception exception) {
exception.printStackTrace();
}finally {
DBUtilities.closePreparedStatement(preparedStatement);
DBUtilities.closeResultSet(resultSet);
DBUtilities.closeConnection(connection);
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
btnLogin.setOnAction(this::setBtnLogin);
}
}
Thank you very much. I simply did not gave any ID to the passwordfield.
You can debug by first trying to print the string from your input fields:
String username = txtUserName.getText();
String password = txtPassword.getText();
System.out.println("User name = " + username);
System.out.println("Password = " + password);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
If the username and password are null then make sure, those fields controller are well bound to the FXML document.

SQLite is busy, Database is locked

I need help, I'm trying to insert something into the existing Database, but I can't get it going. I get The database file is locked (database is locked). I have tried closing the preparedStatement, but no luck. I used executeUpdate() instead executeQuery(), no help.
public class tableController {
Connection connection;
#FXML
private TextField txtId;
#FXML
private TextField txtName;
#FXML
private TextField txtLastName;
#FXML
private TextField txtAge;
#FXML
private TextField txtUsername;
#FXML
private TextField txtPassword;
#FXML
private Button save;
public tableController() {
connection = SQLiteConnection.connector();
if(connection == null) {
System.out.println("Test");
System.exit(1);
}
}
public boolean isDBConnected() {
try {
return !connection.isClosed();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
public void Insert(ActionEvent event) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet;
String query = "insert into employee (id, name, lastName, age, username, password) values (?,?,?,?,?,?)";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, txtId.getText());
preparedStatement.setString(2, txtName.getText());
preparedStatement.setString(3, txtLastName.getText());
preparedStatement.setString(4, txtAge.getText());
preparedStatement.setString(5, txtUsername.getText());
preparedStatement.setString(6, txtPassword.getText());
Alert aleret = new Alert(AlertType.INFORMATION);
aleret.setTitle("Information dialog");
aleret.setHeaderText(null);
aleret.setContentText("User has been created");
aleret.showAndWait();
preparedStatement.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
} finally {
if(preparedStatement != null) {
preparedStatement.close();
}
}
}
}
I have found the solution.
#CL. was right, there was other connection object running in the background.
Problem was that I did not closed preparedStatement and resultSet when logging into the app.
PreparedStatement preparedStatement;
ResultSet resultSet;
String query = "select * from employee where username = ? and password = ?";
try {
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, user);
preparedStatement.setString(2, pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
preparedStatement.close(); // after closing this, it works
resultSet.close(); // closed this one also
return true;
} else {
return false;
}
} catch (Exception e) {
// TODO: handle exception
return false;
}

User authentication from database

Please help me fix the error in this program. The problem is, even if I use the correct username and password, I can't create a verified login.
public class LoginDao {
public static boolean CheckUser(String Username,String Password)
{
boolean st =false;
String dbUsername, dbPassword;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DBConnection.getConnection();
String qry ="select *user where Username=? and Password=?";
PreparedStatement pst = con.prepareStatement(qry);
//pst.setString(1, Username);
//pst.setString(2, Password);
pst.executeQuery(qry);
ResultSet rs = pst.getResultSet();
while(rs.next()){
dbUsername = rs.getString("Username");
dbPassword = rs.getString("Password");
if(dbUsername.equals(Username) && dbPassword.equals(Password)){
System.out.println("Welcome");
st = true;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Check your SQL query? You are missing a FROM before * and user. Also you need to set the parameters when using a PreparedStatement, you have them commented out.
UPDATE
Try this:
public class LoginDao {
public static boolean CheckUser(final String username, final String password) {
final String qry ="SELECT * FROM user WHERE Username=? AND Password=?";
Connection con = null;
PreparedStatement pst;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DBConnection.getConnection();
pst = con.prepareStatement(qry);
pst.setString(1, username);
pst.setString(2, password);
pst.executeQuery(qry);
rs = pst.getResultSet();
// Notice I changed the 'while' by 'if'
if (rs.next()) {
return (username.equals(rs.getString("Username")) && password.equals(rs.getString("Password")));
}
} catch (final Exception e) {
e.printStackTrace();
} finally {
// close/release (database resources) 'con', 'pst', 'rs' here
}
return false;
}
}

radio button show values in combo box

I confused with this if-else because I'm new in Java & MySQL and I tried to make it by myself.
public Menu() {
initComponents();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurant", "root", "");
System.out.println("ODBC Connection Successful");
showCategory();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("ODBC Connection Failed" + e);
}
}
if - else
private void showCategory() {
try {
Statement stmt;
stmt = con.createStatement();
if (rbMFood.isSelected()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY02'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
} else {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY01'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Radio Button
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Food";
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Drink";
}
And I declare the function in the end of the program
private String type;
When I click drink / food, the category still drink's category.
The database
Any help would be greatly appreciated!
You are using rs.getString("menu_cat") But the format is rs.getString(<Column Name>) But you are using rs.getString(<Table Name>) As "menu_cat" is name of the table and not the name of the column.
AFTER POSTING CONSTRUCTOR
What I see from the code you have posted, is that You have called showCategory() in the constructor. This method is responsible for populating the JComboBox cmbMCat. Now the cmbMCat is being populated when you are creating the new Menu. After that the items list of the cmbMCat does not change.
So, What I suggest is that you call the showCategory() from the rbMFoodActionPerformed and rbMDrinkActionPerformed methods. I hope this will solve your problem.
Also add cmbMCat.removeAllItems() before Statement stmt; to remove all the items that are there in the cmbMCat and reset it with a fresh list of items.
After comment regarding the if-else
Change the showCatagory() as below:
private void showCategory() {
cmbMCat.removeAllItems();
try {
PreparedStatement stmt; //Used Prepared statement
String sql = "SELECT * FROM menu_cat WHERE type_id = ?";
stmt = con.prepareStatement(sql);
if (type.equals("Drink")) {
stmt.setString("TY01");
} else {
stmt.setString("TY02");
}
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Also note that you eventListener code should be:
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt){
type = "Food";
showCategory();
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt){
type = "Drink";
showCategory();
}

Categories