Everything just worked don't know what I did ,but I keep getting the error when wanting to UPDATE information in my SQL database. Error : The column position '1' is out of range. The number of columns for this ResultSet is '0'
try
{
String em = EmailField.getText();
String na = NameField.getText();
String su = SurnameField.getText();
String i = IDField.getText();
String ce = CellField.getText();
String query2 = "UPDATE LouwDataBase.Table1Test "
+ "SET Email = "+"'"+em+"'"+" , "
+ "Name = "+"'"+na+"'"+" , "
+ "Surname = "+"'"+su+"'"+" , "
+ "ID = "+"'"+i+"'"+" , "
+ "Cell = "+"'"+ce+"'"
+ " WHERE Email = "+"'"+UserEmailID+"'";
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
stat = conn.createStatement();
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(query2))
{
pstmt.setString(1, em);
pstmt.setString(3, na);
pstmt.setString(4, su);
pstmt.setString(5, i);
pstmt.setString(6, ce);
pstmt.executeUpdate();
}
catch (SQLException e)
{
System.out.println(e.getMessage());
}
}
Since you're using PreparedStatement, I think you need to have question marks in the query and then use pstmt.setString().
try {
String em = EmailField.getText();
String na = NameField.getText();
String su = SurnameField.getText();
String i = IDField.getText();
String ce = CellField.getText();
String query2 = "UPDATE LouwDataBase.Table1Test "
+ "SET Email = ?, "
+ "Name = ?, "
+ "Surname = ?, "
+ "ID = ?, "
+ "Cell = ?"
+ " WHERE Email = ?";
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase", "LouwDataBase", "1234");
stat = conn.createStatement();
try (Connection conn = this.connect();
PreparedStatement pstmt = conn.prepareStatement(query2)) {
pstmt.setString(1, em);
pstmt.setString(3, na);
pstmt.setString(4, su);
pstmt.setString(5, i);
pstmt.setString(6, ce);
pstmt.executeUpdate();
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
}
Related
I have a function to update the user's information as follows:
public void updateAccount(String username, String name, String address, String aboutMe, String
id) {
String sql = "update Account set username = '?', \n"
+ " [Full_Name] = '?',\n"
+ " [Address] = '?',\n"
+ " [about_me] = '?'\n"
+ " where id = ?";
try {
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, name);
ps.setString(3, address);
ps.setString(4, aboutMe);
ps.setString(5, id);
ps.executeUpdate();
} catch (Exception ex) {
Logger.getLogger(AccountDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
and this code is giving me an error like this:
Severe: com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setterGetParam(SQLServerPreparedStatement.java:933)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setValue(SQLServerPreparedStatement.java:948)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.setString(SQLServerPreparedStatement.java:1578)
at dao.AccountDao.updateAccount(AccountDao.java:117)
at controller.UserProfileController.doPost(UserProfileController.java:91)
I don't understand why it gives me the error "The index 2 is out of range" and is there any
way to fix it?
Don't enclose ? parameter markers in quotes. These are typed by the appropriate setter:
String sql = "update Account set username = ?, \n"
+ " [Full_Name] = ?,\n"
+ " [Address] = ?,\n"
+ " [about_me] = ?\n"
+ " where id = ?";
In method save() I receive as input an instance of Employee, and I want to add it to the table employee and return this added instance. I read about this problem but I didn't find an answer to my problem.
public Employee save(Employee employee) throws SQLException {
Connection connection = ConnectionSource.instance().createConnection();
String sql = "insert into employee VALUES(" +employee.getId() + ", " + "'employee.getFullName().getFirstName()'" + ", " +"'employee.getFullName().getLastName()'"+ ", " +"'employee.getFullName().getMiddleName()'"+ ", " + "'employee.getPosition()'" + ", " +"'employee.getHired()'"+ ", " + employee.getSalary()+ ", " +employee.getManagerId()+ ", " +employee.getDepartmentId() + ")";
connection.prepareStatement(sql);
PreparedStatement ps2 = connection.prepareStatement("select * from employee");
ResultSet resultSet = ps2.executeQuery();
resultSet.next();
Employee emp = new Employee(... );
return emp;
}
First of all, better not use such approach:
String sql = "insert into employee VALUES(" +employee.getId() + ", " + "'employee.getFullName().getFirstName()'" + ", " +"'employee.getFullName().getLastName()'"+ ", " +"'employee.getFullName().getMiddleName()'"+ ", " + "'employee.getPosition()'" + ", " +"'employee.getHired()'"+ ", " + employee.getSalary()+ ", " +employee.getManagerId()+ ", " +employee.getDepartmentId() + ")";
you can have an sql injection in that case.
Instead use
String sql = "insert into employee values (?, ?, ...)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, employee.getId());
statement.setString(2, employee.getFullName().getFirstName());
...
For your problem you can try something like this:
public Employee save(Employee employee) throws SQLException {
try (Connection connection = ConnectionSource.instance().createConnection();;
PreparedStatement statement = connection.prepareStatement(SQL_INSERT,Statement.RETURN_GENERATED_KEYS);) {
statement.setInt(1, employee.getId());
statement.setString(2, employee.getFullName().getFirstName());
// ...
int affectedRows = statement.executeUpdate();
if (affectedRows == 0) {
throw new SQLException("Creating employee failed, no rows affected.");
}
try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
if (generatedKeys.next()) {
employe.setId(generatedKeys.getLong(1));
}
else {
throw new SQLException("Creating employe failed, no ID obtained.");
}
}
return employee;
}
}
I have just started with ucanaccess and I am attempting to work out how it works. I wanted to update my Access database's username from "Sutaciba" to "Evan" but it shows the following error:
"Exception occured:
UCAExc:::4.0.4 C:\Users\evanc\AppData\Roaming\IT PAT DataBase (Access is denied)".
Seems like Ucanaccess doesn't have permission to gain access to my database for some reason.
Thank you for any help!
public static void main(String args[])
{
int ID = 1;
String username = "Sutachiba";
String password = "Evanchui123";
String email = "evanchui34#gmail.com";
try
{
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\evanc\\AppData\\Roaming\\IT PAT DataBase");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [username], [password] FROM [tblUser] WHERE ID =" + ID);
while(rs.next())
{
username = rs.getString(1);
password = rs.getString(2);
email = rs.getString(3);
System.out.println("Username: " + username + '\n' + "Password: " + '\n' + "Email:" + email);
}
String newN = "Evan";
String updateQuery = "UPDATE userDB SET (username) = (?) WHERE ID =" + ID;
PreparedStatement st = conn.prepareStatement(updateQuery);
st.setString(1, newN);
st.executeUpdate();
System.out.println("Successfully updated userdata!");
conn.close();
}
catch(Exception ex)
{
System.err.println("Exception occured: ");
System.err.println(ex.getMessage());
}
I am trying to update some attributes with null values. But it always error. Here is my code
// deleting records of column overtime, medical, bonus, other and totalamount
try {
String deleteQuery = "update paydb.allowance set "
+ "overtime = ?, "
+ "medical = ?,"
+ "bonus = ?,"
+ "other = ?,"
+ "totalamount = ?"
+ "where emp_id = ?";
PreparedStatement dpst = conn.prepareStatement(deleteQuery);
dpst.setNull(1, java.sql.Types.DOUBLE);
dpst.setNull(2, java.sql.Types.DOUBLE);
dpst.setNull(3, java.sql.Types.DOUBLE);
dpst.setNull(4, java.sql.Types.DOUBLE);
dpst.setNull(5, java.sql.Types.DOUBLE);
dpst.setString(6, txt_search.getText());
dpst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record deleted successfully");
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e);
}
try {
String deleteQuery = "update paydb.allowance set "
+ "overtime = ?,"
+ "medical = ?,"
+ "bonus = ?,"
+ "other = ?, "
+ "totalamount = ? "
+ "where emp_id = ? ";
enter code here
PreparedStatement dpst = conn.prepareStatement(deleteQuery);
dpst.setNull(1, java.sql.Types.DOUBLE);
dpst.setNull(2, java.sql.Types.DOUBLE);
dpst.setNull(3, java.sql.Types.DOUBLE);
dpst.setNull(4, java.sql.Types.DOUBLE);
dpst.setNull(5, java.sql.Types.DOUBLE);
dpst.setString(6, txt_search.getText());
dpst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record deleted successfully");
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e);
}
I have the following function and I am trying to compare the number of students enrolled in a class with the class max. If the number enrolled is greater than the class max, I want to return a message that says, "The Class if Full".
public static void classFullCheck() {
try {
String currentNumberInClassAsString = ("SELECT class_id, COUNT(*) FROM ClassSelector.student_x_class WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(currentNumberInClassAsString);
int currentNumberInClassAsInt = 0;
if(rs.next()){
currentNumberInClassAsInt = rs.getInt(1);
}
String classSizeAsString = ("SELECT class_size FROM ClassSelector.classes WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(classSizeAsString);
int classSizeAsInt = 0;
if(rs.next()){
classSizeAsInt = rs.getInt("class_size");
}
if (currentNumberInClassAsInt > classSizeAsInt){
System.out.println("Sorry, this class is Full!");
}
} catch (java.sql.SQLException SQL) {
SQL.printStackTrace();
}
}
I am inserting the classFullcheck() function into the addClass() function like this:
public static void addClass() {
try {
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes");
while (rs.next()) {
String availableClasses = rs.getString("class_id") + "\t" + rs.getString("class_name") + "\t" + rs.getString("description");
System.out.println(availableClasses);
}
System.out.println("Enter Class ID from Classes Listed Above to Join: ");
selectedClass = sc.nextLine();
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
System.out.println(innerJoin);
String student_x_classJoin = "INSERT INTO student_x_class" + "(student_id, student_name, class_id, class_name)" + "VALUES (?, ?, ?, ?)";
PreparedStatement pStmt = con.prepareStatement(student_x_classJoin);
pStmt.setString(1, user_entered_student_id);
pStmt.setString(2, userEnterIdAsName);
pStmt.setString(3, rs.getString("class_id"));
pStmt.setString(4, rs.getString("class_name"));
pStmt.executeUpdate();
System.out.println("Would you like to enroll " + userEnterIdAsName + " into another class? (Y/N)");
String addAdditionalClass = sc.nextLine();
if (addAdditionalClass.equalsIgnoreCase("Y")) {
addClass();
} else if (addAdditionalClass.equalsIgnoreCase("N")) {
return;
}
}
}
catch (java.sql.SQLException SQL) {
System.out.println("Wait, This Student is already enrolled in this class!");
}
}
I am currently just getting both messages printed out, even if a class is not full. Any suggestions would help a lot.
if (currentNumberInClassAsInt >= classSizeAsInt) {
String updateStatus = "Update ClassSelector.classes SET status = ? WHERE class_id = " + selectedClass;
PreparedStatement pStmt = con.prepareStatement(updateStatus);
pStmt.setString(1, "Closed");
pStmt.executeUpdate();
System.out.println("Sorry, this class is Full! Select a different Class:");
System.out.println("\nSign Up For a Class\n");
addClass();
}
I think you want this:
currentNumberInClassAsInt = rs.getInt(2);
instead of:
currentNumberInClassAsInt = rs.getInt(**1**);
I don't think the ResultSet is 0 based...
Also is rs a global variable because it looks like you are changing your ResultSet rs when you call classFullCheck(). You may not have what you think you do in the ResultSet...
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();//****************result set changed here******************
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
You may think you have this: rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass); in your result set but you change rs in classFullCheck(). You may want to store the data in a different object that way when you run another query you can still access the data.