help needed (corejava) - java

I m getting except1 on running this code.Please see if there is any mistake within the try block....
Try
{
pst=con.prepareStatement("SELECT Name,Roll,Semester,Address,Phoneno," +
"E-mailId,Gender,DOB,Result FROM stud WHERE Roll = ?");
pst.setString(1,s2);
ResultSet rs=pst.executeQuery();
while(rs.next())
{
s2=rs.getString("Roll");
String s1=rs.getString("Name");
String s3=rs.getString("Semester");
String s4=rs.getString("Address");
String s5=rs.getString("Phoneno");
String s6=rs.getString("E-mailId");
String s7=rs.getString("Gender");
String s8=rs.getString("DOB");
String s9=rs.getString("Result");
t1.setText(s1);
t2.setText(s2);
t3.setText(s3);
t4.setText(s4);
t5.setText(s5);
t6.setText(s6);
t7.setText(s7);
t8.setText(s8);
t9.setText(s9);
}
con.commit();
con.close();
}
catch(SQLException e2)
{
System.out.println("except1");
}

caveat: my Java is rusty -
don't know if field names can contain hypens, depends on the database
print the exact exception that you're getting
why are you doing a commit on a SELECT?

Make Sure data type of "Roll" Atrribute in Database is Character(n).
if it is integer/number then use this
pst.setInt(1,Integer.parseInt(s2));

Make sure you use VARCHAR data type for all attributes in database. If it is not the case then change your code according to these data types.
And print exception stack trace (e2.printStackTrace()) in catch block for getting exact reason for the exception.
Thanks

Try
{
pst=con.prepareStatement("SELECT Name,Roll,Semester,Address,Phoneno," +
"E-mailId,Gender,DOB,Result FROM stud WHERE Roll = ?");
pst.setString(1,s2);
string s2 = '123123'; //pass the required value to Query
ResultSet rs=pst.executeQuery();
while(rs.next())
{
//String s2=rs.getString("Roll");
String s1=rs.getString("Name");
String s3=rs.getString("Semester");
String s4=rs.getString("Address");
String s5=rs.getString("Phoneno");
String s6=rs.getString("E-mailId");
String s7=rs.getString("Gender");
String s8=rs.getString("DOB");
String s9=rs.getString("Result");
t1.setText(s1);
t2.setText(s2);
t3.setText(s3);
t4.setText(s4);
t5.setText(s5);
t6.setText(s6);
t7.setText(s7);
t8.setText(s8);
t9.setText(s9);
}
con.commit(); // use commit only when you are doing create/update operations
con.close();
}
catch(SQLException e2)
{
System.out.println("Error Information");
e2.printStackTrace();// this method display the error information
}

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

Java method - Returning the contents of a Database column in a string

I'm new to Java so any help is appreciated! I've written a method that returns the contents of a table in my database. The table is called "messages".
I am trying to get the contents of this tables one column to be returned by my method as a string so I can then display it in an application.
Here is my method:
public String readData() {
try {
String query = "select * from messages";
PreparedStatement pstmt = ConnectionBuilder.buildConnection().prepareStatement(query);
ResultSet rs = pstmt.executeQuery("select * from messages");
while (rs.next()){
String data = rs.getString("MESSAGE");
System.out.println(data);
}
} catch (Exception e) {
System.out.println(e);
}
return data;
}
The System.out.println(data); line correctly displays what I want:
Hello!
Hello!
Hello!
Hello!
Hello!
Hello!
hio
hio
hio
Testerrr
But the return data; says that data "cannot be resolved to a variable"
Where am I going wrong! I tried to declare the variable at the top of the method but it is still returning null:
public String readData() {
String data = null;
try {
String query = "select * from messages";
PreparedStatement pstmt = ConnectionBuilder.buildConnection().prepareStatement(query);
ResultSet rs = pstmt.executeQuery("select * from messages");
while (rs.next()){
data = rs.getString("MESSAGE");
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println(data);
return data;
}
data is definitely out of scope when you try to use it to return. My first thought is that you should declare it sooner, but you say you've tried that. So I'll give you an alternative.
You could put the return data; line at the end of the try block, and just return an empty string or something at the end of the function. (The only way the return in the try block wouldn't execute is if an exception got thrown, and it's unlikely you'd have valid data anyway in that situation.)
From what I have understood, every time result loop iterates it overrides data value , You can use StringBuilder for desired output.Here is my solution.
public String readData() {
StringBuilder str = new StringBuider();
try {
String query = "select * from messages";
PreparedStatement pstmt = ConnectionBuilder.buildConnection().prepareStatement(query);
ResultSet rs = pstmt.executeQuery("select * from messages");
while (rs.next()){
str.append(rs.getString("MESSAGE"));
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println(str);
return str.toString();
}
Hope it helps :)

How to retrieve integer data from database and store in variable?

i am trying to an integer field from the product table and trying to store in the originalQty variable but there is an error.How do i store the result in an int variabe
public int prodQty( String prodid){
int originalQty = 0;
try {
String sql="select QUANTITY from PRODUCT where productid='"+prodid+"' '";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
originalQty=rs.getInt(7);
}
}
catch (SQLException ex) {
}
System.out.println(originalQty);
return originalQty;
}
Use
originalQty=rs.getInt("QUANTITY");
And you have a quote too much in your query
... where productid='"+prodid+"' '";
^--------here. Remove that
If the input is a number you can remove the quotes entirely.
And you should actually use Prepared Statements that handle escaping inputs automatically and prevent SQL injections.
Some advice.
Always use column name.
Use prepared statement.
Learn how to debug your program. That will tell you exactly why the error.

Set text of Text Field from content of ResultSet

i have been trying a lot of syntax but i can't figured it out.
I want to display "Invoice number" from my databases to the text field (The field "invoice" from table "transaksi" is already filled with number) But it won't show anything. Here's my code :
private void InvoiceActionPerformed(java.awt.event.ActionEvent evt) {
ResultSet aa = null;
try {
koneksi objKoneksi = new koneksi();
Connection kon = objKoneksi.bukaKoneksi();
Statement stat = kon.createStatement();
String query ="select invoice from transaksii";
String res = aa.getString(query);
Invoice.setText(res);
}
catch (SQLException e) {}
}
Note : - Invoice is Former JTextField1.
- transaksii = name of my table.
- invoice = name of the field.
Thank you. English is not my native language.
You did not execute the query. The value of aa is null and you might be getting a NullPointerException.
String query ="select invoice from transaksii";
aa=stat.executeQuery(query);
if(aa.next())
String res = aa.getString("invoice");
Note: Its not a good practice to have an empty catch because you would then end up without knowing about the exception like now. You should do e.printStackTrace(); in catch block.
There is only 1 problem in your original code. The result set that has returned in the line aa = stat.executeQuery(query); is presently at the a position before the 1st result returned. So When you call aa.getString it is not going to return any thing as it is before the 1st result. Also the ResultSet.getString takes a parameter of int or a parameter of String representing the column name. But in your case you have passed the query as the parameter.
So the corrected code should be if you only want to return the 1st item of the ResultSet would be :
private void InvoiceActionPerformed(java.awt.event.ActionEvent evt) {
ResultSet aa = null;
try {
koneksi objKoneksi = new koneksi();
Connection kon = objKoneksi.bukaKoneksi();
Statement stat = kon.createStatement();
String query ="select invoice from transaksii";
aa = stat.executeQuery(query);
String res = "";
if(aa.next()){ // checks and moves it to 1st position
res = aa.getString("invoice"); //column name of the column
}
Invoice.setText(res);
}catch(SQLException e){
e.printStackTrace();
}finally{
//The closing of connection, statement and resultset.
}
}

Updating Values Netbeans

I am trying to Update my data from my netbeans to sqlite. there is no problem with the query but when I run the program a message box will appear "java.sql.SQLException:query does not return results". What seems to be the problem?
try{
String value1=txtId.getText();
String value2=txtFirst.getText();
String value3=txtLast.getText();
String value4=txtUser.getText();
String value5=txtPass.getText();
String sql="Update account set id='"+value1+"', fname='"+value2+"', lname='"+value3+"',username='"+value4+"', password='"+value5+"' where id='"+value1+"' ";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
JOptionPane.showMessageDialog(null,"Data Updated");
}
catch(SQLException e){
JOptionPane.showMessageDialog(null,e);
}
int updateCount = pst.executeUpdate();
Instead of executeQuery.
Update query:
st.executeUpdate("update reservation set busname='"+jTextField10.getText()+"',busno='"+jTextField9.getText()+"',cusname='"+jTextField8.getText()+"',noofpass='"+jTextField7.getText()+"',amount='"+jTextField6.getText()+"' where cusname='"+jTextField8.getText()+"' ");
You can also try:
String strQuery = ("update visitor set name='"+jTextField10.getText()+"',bus_no='"+jTextField9.getText()+"',cus_name='"+jTextField8.getText()+"',Date='"+jTextField7.getText()+"',amount='"+jTextField6.getText()+"' where _ID='"+jTextField8.getText()+"' ");

Categories

Resources