I can't connect to my database using java - java

Connection conn = null;
Statement stmt=null;
ResultSet rset=null;
String jdbc_url="jdbc:oracle:thin:hr/hr#bassam-desktop:1521:XE";
String query="";
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
conn=DriverManager.getConnection(jdbc_url);
stmt=(Statement) conn.createStatement();
query="select first_name" +"from employees"+"where employeed_id=100";
rset=stmt.executeQuery(query);
System.out.println(rset.getString(1));
}
catch(SQLException | NumberFormatException e)
{
System.out.println("result error");
}
finally{
try{
rset.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Error in closing");
}
}
I'm getting both errors in the results window, what is the problem? hr password is correct, my host name is correct, isn't it the one you get from "Computer Name" after you right click on "My Computer" in windows xp ?
Edit: After using e.getMessage(), i got this..
result error, ResultSet.next was not called

The error message of the exception, that you have put in the comments, tells you what's wrong:
result error, ResultSet.next was not called
You forgot to call ResultSet.next() before accessing the first row of the result set:
if (rset.next()) {
System.out.println(rset.getString(1));
}

Because you're using Netbeans IDE, you can try connecting with their built in tool. That should help you get the jdbc_url right (which is almost certainly the problem). Also, don't forget to download and include in your classpath the ojdbc6.jar (which would definitely be the problem if you're not including it).

The e variable represent the exception. try to print the e.getMessage() or print the stack trace with e.printStackTrace() to understand better the problem.

ResultSet rset = stmt.executeQuery();
while(rset.next()){
//Code that works with results
}

Related

Unable to execute the update query in java servlet

I am doing Change password i need to update the old password. based on old password i need to get record and then updating record but here is the problem when i got record i trying to update it shows null in message
My code:
public String ResetPwd(String NewPwd, String name,String oldpwd)
{
String Pass="Select * from Users where Password='"+oldpwd+"' and UserId='"+name+"'";
String UpdateQuery="update Users set Password='"+NewPwd+"' where UserId='"+name+"'";
try{
currentCon = ConnectionManager.getConnection();
st=currentCon.createStatement();
rs = st.executeQuery(Pass);
if(rs.next())
{
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
int i=ps.executeUpdate();
ps.close();
if(i>=1)
{
msg="Password Changed Successfully";
}
}
else{
msg="Old Password Not Match Please Enter Correct Password..!";
return msg;
}
}catch(Exception ex){}
return msg;
}
msg is null because probably some exception is being thrown and it doesn't get set to anything. As #CraigR8806 said don't just ignore the exceptions you catch but print them at least.
The exception being raised is probably SQLException since you are calling
executeUpdate on an already closed preparedStatament in this point
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
ps.executeUpdate();
ps.close();
int i=ps.executeUpdate();
ps.close();
Since there is no reason for a second update change it to:
PreparedStatement ps=currentCon.prepareStatement(UpdateQuery);
int i=ps.executeUpdate();
ps.close();
as a side note use try with resources as it helps with closing those resources

how to validate a username value with mysql and java to avoid duplicate user name

good day, i have a problem with this method, for some reason it gives me an error. "Java.sql.SqlException: statement is not executing". But it checks if the value is duplicate and prompts the error as the method below show. This has stopped my registration from completing. thanks for your help
public static void UserExists(String y){
try{
query = " select * from MailRegister where Username=?";
pst = connect.prepareStatement(query); //passes my query to java predefined prepared statement
pst.setString(1, Username.getText()); //passes the value of the username to the prepared statement
rs = pst.executeQuery(); //this would execute the query passed in the prepared statement
if(rs.next()){
JOptionPane.showMessageDialog(null, " Sorry This Username is Taken");
}
pst.close();
rs.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);//shows error dialog
}
}
You probably get this error because your objects are not closed properly all the time. Your connect is breaking. A good practice is to open and close the connection when required to prevent leaks.
In the code above, pst.close(); and rs.close(); should be in a finally.
Or even cleaner, the prepared statement should go inside a :
try (pst = connect.prepareStatement(query)) {...}
That way you don't have to close it yourself, the JVM will handle it for you.

Null Pointer Exception in Method Which Sets the Parameters for Prepared Statement

I Have Looke over the internet that from Last 12 hours , and found that too many Users are facing that Problem , But None of them are Able to get Rid of That,
I hav Created a JDialog , Which have TextFields, and i am Trying to get Input From those text Fields, and Store That In DataBase,
But is Givi the Following Exception.
Exception occurred during event dispatching:
Connection ok
Adnan
java.lang.NullPointerException
at srvrDataBaseClass.setPersonStatement(srvrDataBaseClass.java:90)
at srvrDataBaseClass.insertPerson(srvrDataBaseClass.java:71)
at EnrollmentForm.setPerson(EnrollmentForm.java:90)
Here is the Code Where the StackTrac is Pointing ,
public void setPersonStatement(String nm,String fn,String cn,String add, byte[] fpt) {
String Sql = "INSERT INTO PERSON (NAME, FNAME, CNIC, ADDR, FPT) VALUES ( ?,?,?,?,?)";
try {
if(con==null){
System.out.println("Connection error"); <---------------- Connection is Not Closed
}
else {
System.out.println("Connection ok"); <------Connection ok
}
con.prepareStatement(Sql);
System.out.println(nm); <----- This is Line :90, But You can see its not Null, as the Value 'Adnan' is printed on cmd,
pst2.setString(1, nm);
pst2.setString(2, fn);
pst2.setString(3, cn);
pst2.setString(4, add);
pst2.setBytes(5, fpt);
pst2.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("SQL Error");
e.printStackTrace();
}
}
So Any One Who can tell me , Whats Wrong with my Code
Note: DataBase is SQL Server 2008,
Did you mean to do
pst2 = con.prepareStatement(Sql);
? It seems like pst2 is null and will remain so in
pst2.setString(1, nm);
which probably actually throws the NPE.
Check out the javadoc for the method you are trying to use.
con.prepareStatement(Sql);
is not assigned to a proper PreparedStatement Variable,
write as
pst2= con.prepareStatement(Sql);

SQL Exception: java.sql.SQLException: No data found

i get an error wherein it says SQL Exception: java.sql.SQLException: No data found, i cant seems to find the problem here. please help me, sorry for asking.
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:ict11";
Connection con = DriverManager.getConnection(url);
Statement statement = con.createStatement();
statement.executeUpdate( "DELETE from Employee where EmployeeID ="+txtId.getText()+"" );
statement.close();
con.close();
JOptionPane.showMessageDialog(rootPane, "Successfully Deleted");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
I can think about 2 issues
This could be because of unnecessary white spaces that getText() doesn't eliminate. Try txtId.getText().trim()
URL might be wrong.
Apart from that, do the following to improve the code.
Print complete stack trace
Use PreparedStatement instead of statement.
statement.executeUpdate( "DELETE from Employee where EmployeeID ="+txtId.getText()+"" );
try using this
statement.executeUpdate( "DELETE from Employee where EmployeeID ='"+txtId.getText()+"'" );
note the addition of single inverted comma at the start and end of txtId.getText()

Resultset not open

I get following error on Result set
java.sql.SQLException: ResultSet not open. Verify that autocommit is OFF.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.ResultSet.next(Unknown Source)
public ResultSet insertDb(int Id,String firstName,String lastName,String title) throws SQLException{
try {
try {
Class.forName(driver);
con = DriverManager.getConnection(connectionURL);
} catch (SQLException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(con.getAutoCommit());
statement = con.createStatement() ;
res = statement.executeQuery("SELECT * FROM CUSTOMER") ;
con.setAutoCommit(false);
System.out.println(con.getAutoCommit());
while(res.next()){
if(res.getString("ID").equalsIgnoreCase(Integer.toString(Id))){
UNIQUE = false;
error= "Duplicate Entry Found Please Enter New Data";
throw new SQLException("Duplicate info<br>ID " + Id );
}
}
// IF value to be added IS UNIQUE
if(UNIQUE){
String qry1= "insert into CUSTOMER(ID, FIRSTNAME,LASTNAME,TITLE) values(?,?,?,?)";
stm = con.prepareStatement(qry1);
String ID=Integer.toString(Id);
stm.setString(1, ID);
stm.setString(2, firstName);
stm.setString(3, lastName);
stm.setString(4, title);
stm.executeUpdate();
}
}
catch(Exception e){
String errorMessage = "Exception caught : ";
System.out.println(errorMessage + e.toString());
}finally{
if (con != null){
con.close();
}
}
return res;
}
Try moving the setAutoCommit() and getAutoCommit() to before you create and execute the statement. Changing it after you execute the statement may be invalidating the query.
The problem is that you have closed your query before reading your resultset. Closing the query, closes the resultset, hence why you get the "ResultSet not open" error. You should close the query right at the end, in a finally block:
i.e. con.setAutoCommit(false);
will close the query and along iwth it it closes the resultset also.
Not strictly related, but your code probably doesn't do what you expect. This kind of read-modify-write code doesn't work well when there are multiple concurrent invocations.
If you imagine two invocations running though the code, it becomes clear that sometimes, depending on the execution order, BOTH invocations could reach the insert statement.
In addition, selecting from a table without using a WHERE clause is not generally useful. In this case you select '*', then iterate over all the results to see if "ID" == Id. The database is much much better at that than java is. You should add a where clause. (Note that this still won't solve the above problem)
Its also generally a bad idea to 'select *' from any table. Just pick the columns that you need. This will 'fail fast' if the schema changes and the columns that you need are no longer available, and will allow the database optimiser to do the 'right thing' about its disk accesses.
Finally, if its just a numeric ID that you are looking to assign, its normal practice to use 'autonumber' for these, rather than get the program to pick them. Different databases call them different things, so you might also know them as IDENTITY, or have to use a sequence.
In case it helps anyone down the line, I had the same error with Derby 10.5.1.1 that turned out to be a bug in the driver itself that would appear some times and not others depending on the underlying data. Upgrading the driver to a newer version (10.8.2.2) resolved the problem.

Categories

Resources