private void Update_table(){
try {
String sql= "select Firstname, Lastname,ID_number from regmembers";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
jTable_regMembers.setModel(DbUtils.resultSetToTableModel(rs));
jTable_regMembers.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jTable_regMembers.getTableHeader().setReorderingAllowed(false);
jTable_regMembers.getTableHeader().setResizingAllowed(false);
} catch(Exception e){
JOptionPane.showMessageDialog(null, e+"");
}
}
how can i display the data of registered members of my database and put it into jtextfield, newbie question?
iterate over the resultset object and set the values obtained
ResultSet resultSet = ps.executeQuery();
if (resultSet.next()) {
do {
// perform your logic
yourTextfield.setText(rs.getString("yourColumnName"));
} while(resultSet.next());
You should be able to execute a simple query and use the value in the Result set to set your textfield.
String sql = "Select count(*) from regmembers";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
textfield.setText(rs.getInt(1));
Hope this works the way you wanted it to
Related
UPDATE
i changed sql query (just test it and it works on sql but still not working with java dont no why :(
Hi how to add get result on jLabel with this code? and is it possible to show results on jTable?
private void searchTeacherActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = ("select student_ID, firstName, afterName FROM student JOIN studentHom ON course = studentHom_ID WHERE prefect = ?
try {
pst = connection.prepareStatement(sql);
pst.setString(1, larareSoka.getText());
pst.execute();
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, e);
}
}
First don't use (?) you can just use ?:
select ... where course.courseStart = ? and course.corse.end = ?
Second you have to set parametters to your query in your case you have tow, so you have to use :
pst.setString(1, value_of_courseStart);
pst.setString(2, value_of_corse.end);
Third to get results you have to use ResultSet like this :
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
String firstname = result.getString(1);
//----------------------------------^
//...same for the other columns
}
or you can use the name of column like this:
ResultSet result = preparedStatement.executeQuery();
if (result.next()) {
String firstname = result.getString("firstName");
//--------------------------------------^^
//...same for the other columns
}
Note
If you want to get multiple result you ca use while instead of if.
Your query is a little wired why you are using :
course.courseStart = (?) and course.corse.end = (?)
//no point---^ ^------Why this point here
Did you mean course.courseStart = ? and course.corseEnd = ?
ResultSet rs = pst.executeQuery();
String firstname = rs.getString("firstname");
..
jLable.setText(firstname);
...You need to read the data from the resultset
The function below will pick the highest value and it will display value which are in column place1(in table placeseen) as output based on the ID.So far I only can get the highest value but not the value in place1.
I don't know what's wrong with my coding because the output is always shows empty.
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0+1];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
String sql ="Select* from placeseen where ID =aa[i]";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
ps.close();
rs.close();
conn.close();
}
}
System.out.println(highest);
}
instead of
String sql ="Select * from placeseen where ID =aa[i]";//aa[i] taking a value
use
String sql ="Select place1 from placeseen where ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]);
passing aa[i] variable value .
Avoid sql injection
You can try this
// as you are using preparedStatement you can use ? and then set value for it to prevent sql injection
String sql = "Select * from placeseen where ID = ?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]); // 1 represent first attribute represented by ?
System.out.println(ps); // this will print query in console
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("Inside rs.next()"); // for debug purpose
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
// remaining code
I have a database with the following layout
databasename:macfast
table name:users
columns
id,
user_name,
password,
fullName
I want to retrieve all the values from the column user_name and check each values with another one string which is already retrieved from a TEXTFIELD.But I can't(NullpointerException). Please help me.
public void deleteFclty() {
PreparedStatement stmt = null;
ResultSet rs = null;
String username=removeText.getText();
String qry = "SELECT user_name From users ";
try {
stmt = (PreparedStatement) connection.prepareStatement(qry);
rs = stmt.executeQuery();
while (rs.next()) {
String check=(rs.getString("user_name"));
System.out.println(check);
if(check.equals(username)){
Util.showErrorMessageDialog("EQUAL");
}else{
Util.showErrorMessageDialog("NOT EQUAL");
}
}
}catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}
Problem is with the prepared statement (you don't put id into statement, which should be there instead of question mark).
Also I would recommend to do condition as "username.equals(check)", that can prevent null pointer exception.
"SELECT user_name From users where id=?"
This query has a parameter and you're not setting any value to it. Use PreparedStatement#setInt() or similar to set it, e.g.:
stmt.setInt(1, 1);
The problem is with PreparedStatement as you are using Question mark ? in your query for that you have to set the Id value.
String qry = "SELECT user_name From users where id=?";
stmt = (PreparedStatement) connection.prepareStatement(qry);
stmt.setInt(1,1001);
rs = stmt.executeQuery();
For your question in comment below:
List<String> values = new ArrayList();
while (rs.next()) {
values.add(0,rs.getString(<>))
}
// here do whatever you want to do...
// for example
for ( String value: values )
{
// check if value == TEXTFIELD
// if true then do something..
// else don't do anything
}
I am trying to get a count from a particular table in my derby database, but when I run the code I keep getting Invalid operation at current cursor position
public int getNumUsers(){
ResultSet rs = null;
int size = -1;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("select count(*) from USERS");
while(rs.next()){
size = rs.getInt("COUNT");
}
stmt.close();
} catch (SQLException sqe) {
sqe.printStackTrace();
}
return size;
}
Change your query to
select count(*) As COUNT from USERS
or change your function call to
rs.getInt(1);
give an alias to count(*) in your select statement. in mysql we use as to give alias name.I dunno about derby though, but think it'd be similar.
rs = stmt.executeQuery("select count(*) as count from USERS");
while(rs.next()){
size = rs.getInt("count");
}
I am using following method for calculating payroll by using jdbc but "ORA-01008: not all variables bound" error is not removing.
Any idea please?
I am using following code
public double getPayroll(){
ResultSet rs = null;
ResultSet rs1 = null;
ResultSet rs2 = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getDBConnection();
double dailyPay=0,basicPay=0,payroll2=0;
int houseRent=0,convAllow=0,noOfPresents=0,empId=0;
String q = "select e_id from employee";
pstmt = conn.prepareStatement(q);
rs = pstmt.executeQuery();
while (rs.next()) {
empId=rs.getInt(1);
String q1 = "select count(att_status) from attendance where att_status='p'";
pstmt = conn.prepareStatement(q1);
rs1 = pstmt.executeQuery(q1);
while(rs1.next()){
noOfPresents=rs1.getInt(1);
String q2 = "select e_salary,e_house_rent,e_conv_allow from employee where e_id=?";
pstmt = conn.prepareStatement(q2);
pstmt.setInt(1,empId);
rs2 = pstmt.executeQuery(q2);
while(rs2.next()){
dailyPay=rs2.getInt(1)/22;
houseRent=rs2.getInt(2);
convAllow=rs2.getInt(3);
basicPay=dailyPay*noOfPresents;
payroll2+=basicPay+houseRent+convAllow;
}
}
}
return payroll2;
}catch (Exception e) {
e.printStackTrace();
return 0.0;
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Your problem is here:
rs2 = pstmt.executeQuery(q2);
You're telling the PreparedStatement to execute the SQL q2, rather than executing the SQL previously prepared. This should just be:
rs2 = pstmt.executeQuery();
This is a fairly common mistake, caused mainly by the bad class design of java.sql.Statement and its subtypes.
As #RMT points out, you make the same mistake here:
rs1 = pstmt.executeQuery(q1);
This doesn't matter so much, since there are no placeholders in q1, so the SQL executes as-is. It's still wrong, though.
Lastly, you should consider calling close() on the first PreparedStatement, before re-assigning the pstmt variable to another one. You risk a leak if you don't do that.
pstmt = conn.prepareStatement(q2);
pstmt.setInt(1,empId);
rs2 = pstmt.executeQuery(q2);
You have already created the prepared statement with the query q2 and bound the variable empId to it. if you now invoke pstmt.executeQuery(q2), the variable binding is lost. The JDBC driver probably parses the unbound sql q2 when you execute pstmt.executeQuery(q2).
One reason might be that you cannot re-use the instance of pstmt like that. You have to use a separate PreparedStatement instance in each level of the loop.
Are you aware that this can be done with just a single statement as well?
Edit:
Assuming there is a relation between employee and attendance, something like this would return the sum in a single request:
select sum( (e_salary / 22) * att_count + e_house_rent + e_conv_allow )
from (
select emp.e_salary
emp.e_house_rent,
emp.e_conv_allow,
(select count(att.att_status) from attendance att where att.e_id = mp.e_id) s att_count
from employee emp
) t
If indeed attendance is not linked to employee, just leave out the where clause in the nested select.
UPDATE TESTCP SET CP_KEY2 =?, CP_DESC =?, CP_MAKER =?, CP_MAKER_DT =SYSDATE, CP_STATUS ='M' WHERE CP_LANGUAGE = ? AND CP_ENG_CODE = ? AND CP_KEY1 =? AND CP_LANGUAGE =?
In the above query we have 7 in parameter but if in your java code PreparedStatement you have set only 6 parameter values .
That time also this error will occur.