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.
}
}
Related
my textfield is called pruebamax
With this function I make the connection with the database
public ResultSet getmax() {
ResultSet r = null;
try {
String sql = "select count(*) as Cantidad from tbl_padre";
System.out.println(sql);
Statement st = cx.createStatement();
r = st.executeQuery(sql);
System.out.println(st.executeQuery(sql));
} catch (SQLException ex) {
Logger.getLogger(Tmrptryone.class.getName()).log(Level.SEVERE, null, ex);
}
return r;
}
his method in the event of a button, with this method I want to print in the textfield the data I receive from the database but I got an error.
public void actualizatext() {
try {
ResultSet r = mrp.getmax();
if (r.next()) {
String ID = r.getString("Cantidad");
pruebamax.setText(ID);
}
} catch (SQLException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
Now, I don't know what pruebamax means but the SQL statement you used:
String sql = "SELECT COUNT(*) AS Cantidad FROM tbl_padre";
is specifically used to count the total number of records currently maintained within the specified database table (tbl_padre). The value from that count will be held in the specified temporary field named: Cantidad. When you Use the SQL COUNT statement you are not going to be returned a String data type value. You will be expected to try and acquire a Integer value.
It will not acquire a value from your table ID field as what it looks like you expect.
To properly retrieve the records count from your applied SQL string then it should be used in this fashion:
int count = 0;
try {
String sql = "SELECT COUNT(*) AS rCount FROM tbl_padre";
Statement st = cx.createStatement();
ResultSet r = st.executeQuery(sql);
while (r.next()) {
count = r.getInt("rCount");
}
r.close();
st.close();
// Close your DB connection as well if desired.
// yourConnection.close();
//To apply this value to your JTextField:
pruebamax.setText(String.valueOf(count));
System.out.println("Total number of records in the tbl_padre " +
" table is: " + count);
}
catch (SQLException ex) {
ex.printStackTrace();
}
Try not to use actual table field names for temporary field names.
If you want to be more specific with your count then your SQL statement must be more specific as well. For example, let's assume that we want to count the number of records maintained in our table where a field named Age contains a value which is greater than 30 years old, our sql statement would look like this:
String sql = "SELECT COUNT(*) AS rCount FROM tbl_padre WHERE Age > 30";
You will of course have noticed the use of the SQL WHERE clause.
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 :)
I am having some trouble in returning the NEXT record within the database, my code currently only returns the last record entered. I have tried creating an instance of a List/ArrayList, tried adding statements to my createStatement(); and just tried everything. I've searched the web, however, I always seem to get the last value returned. I was hoping as to whether someone could help me out. I am using .Swing and this is all executed within an ActionListener.
Essentially I want this function to get the next record in the database. As opposed to returning the last record.
nextEmployee.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connection connection = null;
Statement statement = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:employeeDatabase.sqlite");
connection.setAutoCommit(false);
System.out.println("Read operation - database successfully opened");
statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
ResultSet resultset = statement.executeQuery( "SELECT * from employees" );
while (resultset.next()) {
ArrayList<Employee> selectAllEmployees = new ArrayList<Employee>();
String id = resultset.getString("id");
String name = resultset.getString("name");
String email = resultset.getString("email");
String gender = resultset.getString("gender");
String dob = resultset.getString("dob");
String Address = resultset.getString("address");
String Postcode = resultset.getString("Postcode");
String NIN = resultset.getString("NIN");
String JobTitle = resultset.getString("JobTitle");
String StartDate = resultset.getString("StartDate");
String Salary = resultset.getString("Salary");
idTextField.setText(id);
nameTextField.setText(name);
genderTextField.setText(gender);
dobTextField.setText(dob);
addressTextField.setText(Address);
postcodeTextField.setText(Postcode);
ninTextField.setText(NIN);
jobtitleTextField.setText(JobTitle);
startdateTextField.setText(StartDate);
salaryTextField.setText(Salary);
emailTextField.setText(email);
}
resultset.close();
statement.close();
connection.close();
} catch ( Exception e1 ) {
System.err.println( e1.getClass().getName() + ": " + e1.getMessage() );
System.exit(0);
}
}});
Thank you for your time and effort.
One of two things is happening. Either:
You have a bug in the code which populates the database, so you think you have rows A, B, and C in the database, but in fact you only have row C
Or:
Your code as listed populates your controls with the contents of row A, then it repeats to populate the exact same controls with contents of row B, and then the exact same controls once more with the contents of row C. So, naturally, the values you are left with are the values of the last row.
It helps to think precisely what it is that you are trying to do, precisely what is happening, precisely what you expected to happen instead, and most importantly, what makes you believe that the code should do that which you expect it to do rather than what it actually does.
I'm trying to get category name from combobox and then insert it to my database
This is my code, but I don't know how to write the code to make this work. Any ideas ?
The below code is my add button (trying to make work String value, String query). However, the code is really wrong I think.
String value=jComboBox_Category2.getSelectedItem().toString();
String qquery="INSERT INTO Products ( Cat_products) VALUES ('"+Cat_products.getText()+" ') ";
String query="INSERT INTO Products(Pro_Id ,Pro_Name,Pro_Price,Pro_Quantity,Pro_Supplier_id,Pro_Tax)VALUES ('"+Pro_Id.getText()+" ','"+Pro_Name.getText()+" ','"+Pro_Price.getText()+" ','"+Pro_Quantity.getText()+" ','"+Pro_Supplier_id.getText()+" ','"+Pro_Tax.getText()+" ') ";
executeSQLQuery(query,"Inserted");
Here is the code that my other elements get the data. So where do I have to write the code? And how should it be like?
public ArrayList<Update_del_insert_products> getproList() {
ArrayList<Update_del_insert_products> proList =new ArrayList<Update_del_insert_products> ();
Connection connection =getConnection();
String query ="SELECT * FROM Products";
Statement stt;
ResultSet rss;
try{
stt = connection.createStatement();
rss = stt.executeQuery(query);
Update_del_insert_products update_del_insert_products ;
while(rss.next()) {
update_del_insert_products = new Update_del_insert_products (rss.getString("Pro_Id"),rss.getString("Pro_Name"),rss.getString("Pro_Price"),rss.getString("Pro_Quantity"),rss.getString("Pro_Supplier_id"),rss.getString("Pro_Tax"));
proList.add(update_del_insert_products);
}
}catch (Exception e){
e.printStackTrace();
}
return proList;
}
String qquery="INSERT INTO Products (Cat_products) VALUES (Cat_products.getText()");
Connection connection = (see below)
Statment stmt = connection.createStatement();
stmt.executeUpdate(qquery)
But you can concatenate insert statements if you use the same table
In order to retrieve data from database, first of all have to set the connection properly
Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost;databaseName=YourDatabseName;integratedSecurity=true;")//without authentication
You should not use * in sql statement.
Make setter and getter methods in Update_del_insert_product class (Auto-generated methods) and use them.
while(rss.next()){
update_del_insert_products product = new Update_del_insert_products();
int i = 1
product.setPro_ID(rss.getString(Pro_ID, i++));
product.setPro_Name(rss.getString(Pro_Name, i++));
...
prolist.add(product);
}
private void btgetinvActionPerformed(java.awt.event.ActionEvent evt) {
//JOptionPane.showMessageDialog(null, "REMITTANCE ID IS VALID!");
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement("select bk_det.rm_id from bk_det WHERE dbo.bk_det.rm_id = ?");
ResultSet rs;
String rm = tf_rmid.getText().trim();
stmt.setInt(1, Integer.parseInt(rm));
rs = stmt.executeQuery();
while (rs.next()) {
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
I am actually trying to search value from my database table called dbo.bk_det. I am taking the value of WHERE from my textfield tf_rmid. Everything goes on well without error but once i insert the rm_id and click on button btgetinv it says 123 which is my rm_id is out of range cant understand where the error is and what is the problem.
The problem is with the following statements:
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
The first statement won't work the way you want because there's no column named "box_no" in the select clause. It will throw an exception. Let's assume you change the code to have box_no in the select clause. Then, the second statement will try to retrieve the nth column where the column is the value of box_no. I think you just want:
tfbrname.setText(rs.getString("box_no"));
Again, the above only will work if your SELECT statement includes box_no in the field list.
rs.next() returns false if it does not contain any more records. So if you want to behave something when no records found, you have to check record count.
for example,
int recordCount = 0;
while (rs.next()) {
recordCount++;
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
if(recordCount == 0) {
// do something : report an error or log
}
for further information, see http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#next()