Error PLS-00201 Identifier 'REG_PACK.DELUSER' must be declared - java

I'm getting an error stated above.
I've tried granting the user to execute but no luck.
Here's my SQL code:
create or replace PACKAGE BODY reg_pack AS PROCEDURE ADDUSER( c_fname IN user_profile.firstname%type, c_lname IN user_profile.lastname%type, c_cnum IN user_profile.contactno%type, c_dob IN USER_PROFILE.DOB%type, c_address IN user_profile.address%type, c_city IN user_profile.city%type, c_state IN user_profile.state%type, c_country IN user_profile.country%type, c_email IN user_profile.emailid%type, c_password IN user_profile.password%type, c_usertype IN user_profile.usertype%type, c_username IN user_profile.username%type) IS BEGIN INSERT INTO USER_PROFILE (userid,firstname ,lastname,contactno,dob,address,city,state ,country,emailid,password,usertype,username) VALUES (userid_seq.NEXTVAL, c_fname, c_lname, c_cnum, c_dob, c_address, c_city, c_state, c_country, c_email, c_password, c_usertype, c_username); END ADDUSER;
PROCEDURE DELUSER(c_id IN user_profile.userid%type) IS BEGIN DELETE FROM USER_PROFILE WHERE user_profile.userid = c_id; END DELUSER;
PROCEDURE SELECTUSER(c_id IN user_profile.userid%type, c_fname OUT user_profile.firstname%type, c_lname OUT user_profile.lastname%type, c_cnum OUT user_profile.contactno%type, c_dob OUT USER_PROFILE.DOB%type, c_address OUT user_profile.address%type, c_city OUT user_profile.city%type, c_state OUT user_profile.state%type, c_country OUT user_profile.country%type, c_email OUT user_profile.emailid%type, c_password OUT user_profile.password%type, c_usertype OUT user_profile.usertype%type, c_username OUT user_profile.username%type) AS BEGIN
SELECT FIRSTNAME ,LASTNAME ,CONTACTNO ,DOB ,ADDRESS ,CITY ,STATE , COUNTRY ,EMAILID ,PASSWORD ,USERTYPE ,USERNAME INTO c_fname, c_lname, c_cnum, c_dob, c_address, c_city, c_state, c_country, c_email, c_password, c_usertype, c_username
FROM USER_PROFILE
WHERE user_profile.userid = c_id; END SELECTUSER;
END reg_pack;
As you can see there are three procedures namely DELUSER, ADDUSER and SELECTUSER. I'm using JDBC to execute these queries, the ADDUSER query worked but the other two returned PLS-00201.
Here's my JAVA code:
For insert:
sql2 = "{call REG_PACK.ADDUSER(?,?,?,?,?,?,?,?,?,?,?,?)}";
callable = con.prepareCall(sql2);
callable.setString(1, fname);
callable.setString(2, lname);
callable.setString(3, cnum);
callable.setString(4, dob);
callable.setString(5, address);
callable.setString(6, city);
callable.setString(7, state);
callable.setString(8, country);
callable.setString(9, email);
callable.setString(10, password);
callable.setString(11, utype);
callable.setString(12, username);
callable.executeQuery();
for delete:
int userID = Integer.parseInt(jTextField1.getText());
System.out.println(userID);
try{
String sqlDelete = "{CALL REG_PACK.DELUSER(?)}";
callable = con.prepareCall(sqlDelete);
callable.setInt(1, userID);
callable.executeQuery();
JOptionPane.showMessageDialog(this, "User deleted!");
}catch(SQLException e){
JOptionPane.showMessageDialog(this, e.getMessage());
}

Related

Error: Cannot insert the value NULL into column 'username', table 'FERA_ONL_LEARNING.dbo.Account'; column does not allow nulls. UPDATE fails

I have the following code:
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);
}
}
But when I change something like username, fullname in my web, they are still not updated and show the following error:
Severe: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into
column 'username', table 'FERA_ONL_LEARNING.dbo.Account'; column does not allow nulls. UPDATE
fails. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:328)
at dao.AccountDao.updateAccount(AccountDao.java:142)
at controller.UserProfileController.doPost(UserProfileController.java:91)
I'm sure I changed their values and it can't be NULL.
How to fix this error?
Have you tried printing the result of your dynamic query? You could add a system.out.println(sql) before ps.executeUpdate(), to verify that your variables are being assigned the value correctly.
I estimate by how the sql is concatenated that it is not taking the positions correctly and by default the setString returns NULL.

JSP: problems with multiple queries and generated keys

I have this java method:
public boolean insertAuthor(String userid, String password){
try{
String query1 = "INSERT INTO user (id, firstName, lastName, belonging, country) VALUES(?,?,?,?,?)";
PreparedStatement stmt = this.dbConn.prepareStatement(query1);
stmt.setInt(1,0);
stmt.setString(2,"default"); //Yes, it's correct with "default"
stmt.setString(3,"default");
stmt.setString(4,"default");
stmt.setString(5,"default");
//stmt.executeUpdate();
stmt.executeUpdate(query1, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
int key=0;
if ( rs.next() ) {
key = rs.getInt(1);
}
String query2 = "INSERT INTO authentication (id, address, password, user_id, login_id) VALUES(?,?,?,?,?)";
stmt = this.dbConn.prepareStatement(query2);
stmt.setInt(1,0);
stmt.setString(2,"default");
stmt.setString(2,password);
stmt.setInt(2,key);
stmt.setString(2,userid);
stmt.executeUpdate();
return true;
}catch(Exception e){
System.err.println(e.getMessage());
}
return false;
}
Let me explain: I would like to execute two queries and the second one need the key that is generated in the first query (I need the primary key of the table "user" because user-authentication is a 1:1 relationship).
So:
Is this the correct way to execute more than one query?
Am I missing something with the returning key? Because if I run ONLY executeUpdate() and I comment every row below it the method works fine, but when I run the code in the example (with the first executeUpdate() commented) I get false (only false, no exception). Do I have to check something in my database?
Thanks in advance.
EDIT:
I found a solution. It was an error in columns and not in the method for getting the generated key itself. I will choose Joop Eggen's answer for the improvements that he showed me. Thanks!
There were a couple of improvements needed.
String query1 = "INSERT INTO user (firstName, lastName, belonging, country)"
+ " VALUES(?,?,?,?)";
String query2 = "INSERT INTO authentication (address, password, user_id, login_id)"
+ " VALUES(?,?,?,?)";
try (PreparedStatement stmt1 = this.dbConn.prepareStatement(query1,
PreparedStatement.RETURN_GENERATED_KEYS);
stmt2 = this.dbConn.prepareStatement(query2)) {
stmt1.setString(1, "default");
stmt1.setString(2, "default");
stmt1.setString(3, "default");
stmt1.setString(4, "default");
stmt1.executeUpdate();
try (ResultSet rs = stmt1.getGeneratedKeys()) {
if (rs.next()) {
int userid = rs.getInt(1);
stmt2.setString(1, "default");
stmt2.setString(2, password);
stmt2.setInt(3, key);
stmt2.setString(4, userid);
stmt2.executeUpdate();
return true;
}
}
} catch (SQLException e) {
System.err.println(e.getMessage());
}
return false;
Try-with-resources close automatically, also on exception and return.
You have two prepared statements to close.
The executeUpdate with the SQL is for the parents class Statement, and does disrespect the parameter settings. You chose that for the generated keys parameter, but that goes into Connection.prepareStatement.
(SQL) The generated keys should not be listed/quasi-inserted.
It is debatable whether one should catch the SQLException here. throws SQLException is what works for me.
I'll advise you have a username field in your user table so after inserting you can simply do a Select id from user Where username...

[Java]Error when Inserting SQL, auto increment in the table - userId

So I am making a registration page and when I enter all the fields and click signup to submit, enterNewUser(,,,) is called and the fields userId, username,password and role are inserted into the table User. I confirm this by running select * from user; into MYSQL workbench.
Then enterUsername(,,,) is called and I get this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '(3,'Barry','Allen')' at line 1
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'(3,'Barry','Allen')' at line 1
public static int enterNewUser(String username,String password, String role){
//int userId = -1;
int ID = 0;
//int ID=-1;
try{
if(checkUserNameAvailable(username)==true){
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost/log", "root", "root");
String q0 = "Select userId from user ORDER BY userId DESC LIMIT 1"; //get ID of last
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(q0);
if(rs.next()){
ID = rs.getInt("userId");
ID++;
}
else
ID=1; // Empty Table, so start with ID 1
rs.close();
st.close();
String q1="insert into user values(?,?,?)";
PreparedStatement ps = cn.prepareStatement(q1);
//ps.setInt(1,ID);
ps.setString(1,username);
ps.setString(2,password);
ps.setString(3,role);
ps.executeUpdate();
ps.close();
}
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
DB_close();
//if(userId!=-1)
// return userId;
return -1;
}
public static boolean enterUsername(int userId, String firstname, String lastname){
try{
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost/log", "root", "root");
//String q1="INSERT INTO user_profile values(?,?,?)";
String q1 = "INSERT into user_profile (userId, firstname, lastname) VALUES (?,?,?)";
PreparedStatement ps = cn.prepareStatement(q1);
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
ps.executeUpdate();
ps.close();
return true;
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
DB_close();
return false;
}
Here is my database structure.
Edit: found the issue, database was not structured properly.
CREATE TABLE user ( userId int(3) NOT NULL AUTO_INCREMENT,
username varchar(20) DEFAULT NULL, password varchar(20) DEFAULT
NULL, role varchar(20) DEFAULT NULL, PRIMARY KEY (userId),
UNIQUE KEY username (username) );
CREATE TABLE user_profile ( userId int(3) NOT NULL DEFAULT '0',
firstName varchar(20) DEFAULT NULL, lastName varchar(20) DEFAULT
NULL, PRIMARY KEY (userId), CONSTRAINT FK FOREIGN KEY
(userId) REFERENCES user (userId) );
Shouldn't following section in method enterUsername
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
be like this
ps.setInt(1, userId);
ps.setString (2, firstname);
ps.setString (3, lastname);
I don't see the reason for the error message that you posted.
But I see some other things that look like a problem:
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
The indexes are wrong: instead of 1, 1, 2, it should be 1, 2, 3.
(Frankly, I don't see how the code could possibly work as posted.)
Btw, this also looks wrong in the other method:
insert into user values(?,?,?)
As the table has more than 3 columns, you need to specify their names,
like you did in enterUsername.
Use
String q1 = "INSERT into user_profile (firstname, lastname) VALUES (?,?)";
because your first field is auto increment..So it automatically increment values while inserting values.
I recommended this way,
Delete your current table and create a new one like this
id-->int(30) (AUTO INCREMENT) NOTNULL //Dont need to take care of this field
USER_ID-->int(30) NOT NULL //you should create your own ID and increment it before adding a new person
username-->varchar(100)
password-->varchar(100)
role-->varchar(100)
and usually, call userId exactly same like your code,
String q0 = "Select userId from user ORDER BY USER_ID DESC LIMIT 1"; //get ID of last
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(q0);
if(rs.next()){
ID = rs.getInt("USER_ID ");
ID++;
}

Getting SQL exception in where clause while inserting data in database through java

I want to store the password for required ID using java. Everything is working fine except that I am getting this Exception
"SQL Exception thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(Pass_word) set Pass_word = 'pass' where ID = 2' at line 1".
I am getting this exception only in update query but not in select query.I am using Eclipse. Can anyone tell me what I am doing is wrong?
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class information {
public static void main(String[] args) {
String password;
ResultSet rs;
String queryString;
int x=1;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://localhost/onlineexam","root", "batch12#nitap");
System.out.print("Database is connected !");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = null;
while(x==1)
{
System.out.println("Press 1 to enter student id");
System.out.println("Press 2 to exit");
Scanner s= new Scanner(System.in);
int choice = s.nextInt();
switch(choice)
{
case 1: System.out.println("Enter the ID of student");
int id = s.nextInt();
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID=" +id;
rs= stmt.executeQuery(queryString);
//System.out.println(rs.getInt("ID"));
while(rs.next())
{
if(rs.getInt("ID")== id)
{
String roll = rs.getString("Roll_no");
String date = rs.getString("Date");
String time = rs.getString("Time");
String c_name = rs.getString("Course_name");
String c_code = rs.getString("Course_code");
password pass1= new password(roll,date,time,c_name,c_code);
pass= pass1.passwd();
System.out.println(pass);
queryString =" Update student_reg(Pass_word) set Pass_word = 'pass' where ID = ?";
//queryString= "INSERT INTO student_reg(Password) VALUES ('password') where ID = ?";
//stmt.executeUpdate(queryString);
//PreparedStatemenet pstmt = conn.preparedStatement("INSERT INTO student_reg(Password) VALUES ('password') where ID = ?");
//pstmt.setLong(1, id);
pstmt = conn.prepareStatement(queryString);
pstmt.setInt(1, id);
int numberOfUpdatedRecords = pstmt.executeUpdate();
s.close();
}
}
break;
case 2: x=0;
}
}
if(conn!= null)
{
stmt.close();
pstmt.close();
conn.close();
conn = null;
}
}
catch(ClassNotFoundException cnf)
{
System.out.println("Driver could not be loaded: " + cnf);
}
catch(SQLException sqle)
{
System.out.println("SQL Exception thrown: " + sqle);
}
catch(Exception e)
{
System.out.print("Do not connect to DB - Error:"+e);
}
}
}
Your code has many problem:
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID= id";
This line you have condition where but you not set the value yet, you should set
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
Better if you take a look at PreparedStatement for prevent SQL Injection as well.
The last one:
queryString= "INSERT INTO student_reg(Password) VALUES ('password') where ID = id";
This line seem you want to update something. Please review it.
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID= id";
should be
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
This would fix the error, but it would be better to use a PreparedStatement, where the query String looks like "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = ?", and you pass the id as a parameter.
It is so obvious because you shouldn't include the 'id' in your query string:
queryString = "select ID,Roll_no, Course_name, Course_code, Date,Time from student_reg where ID = " + id;
Very good hint from #spencer: you can not use WHERE clause in your INSERT INTO statement. Probably you wanted to UPDATE a row with that id. Also it is better to do it using PreparedStatemenet to avoid such mistakes:
conn = DriverManager.getConnection("jdbc:mysql://localhost/onlineexam","root", "batch12#nitap");
PreparedStatemenet pstmt = conn.preparedStatement("UPDATE student_reg SET password = 'password' where ID = ?");
pstmt.setLong(1, id);
int numberOfUpdatedRecords = pstmt.executeUpdate();
I suggest you to rename the column name password, because it is a reserved word in mysql, so you may get strange results working with that column name. Change it to some other thing like: pass_word or passwd , ... . As you may know you can use keywords as column names in your queries using some quotes or other things but it is more safe to rename it to another name, just for hint.
if you use this connection without a connection-pool, you may want to close the Statement and the Connection.
Good Luck.

JDBC How can I use a place holder in a prepared statement with a where clause?

I'm having a hard time understanding why this wont work, if I type the exact same thing straight into a MySQL console it accepts it but when ever I try to run it, it reports a syntax error.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '6'' at line 1
All I'm trying to do is receive the data in the row with the member_id value of whatever the user inputs. For testing purposes the value is always 6, I have tried parsing it as int instead of a string, which gave the same error, and I tried just adding the ID variable onto the end of the string instead of using a place holder but it didn't like that much either.
Here is the code:
public class MemberDAO {
public PreparedStatement ps = null;
public Connection dbConnection = null;
public List<Member> getMembersDetails(String ID) throws SQLException{
List<Member> membersDetails = new ArrayList();
String getMembershipDetails = "SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM members"
+ "WHERE member_id = ?";
try {
DBConnection mc = new DBConnection();
dbConnection = mc.getConnection();
ps = dbConnection.prepareStatement(getMembershipDetails);
ps.setString(1, ID);
ps.executeQuery();
ResultSet rs = ps.executeQuery(getMembershipDetails);
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String phoneNumber = rs.getString("phone_number");
String email = rs.getString("email");
String over18 = rs.getString("over_18");
String dateJoined = rs.getString("date_joined");
String dateExpired = rs.getString("date_expire");
String fines = rs.getString("fines");
Member m;
m = new Member(firstName, lastName, phoneNumber, email, over18, dateJoined, dateExpired, fines);
membersDetails.add(m);
} catch (SQLException ex){
System.err.println(ex);
System.out.println("Failed to get Membership Details.");
return null;
} finally{
if (ps != null){
ps.close();
}
if (dbConnection != null){
dbConnection.close();
}
} return membersDetails;
}
This is what's calling it:
private void btnChangeCustomerActionPerformed(java.awt.event.ActionEvent evt) {
customerID = JOptionPane.showInputDialog(null, "Enter Customer ID.");
MemberDAO member = new MemberDAO();
try {
List membersDetails = member.getMembersDetails(customerID);
txtFullName.setText(membersDetails.get(0) + " " + membersDetails.get(1));
} catch (SQLException ex) {
System.err.println(ex);
System.out.println("Failed to get Details.");
JOptionPane.showMessageDialog(null, "Failed to retrieve data.");
}
}
Any input is appreciated.
Your query is missing a space:
...fines FROM members"
+ "WHERE...
Will result in
FROM membersWHERE
Which is invalid SQL
Change it to
+ " WHERE....
your query is:
SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM
members WHERE member_id = ?
So between member and where you need a blank character
SELECT first_name, last_name, phone_number, email, over_18, date_joined, date_expire, fines FROM members WHERE member_id = ?

Categories

Resources