When I run this code, the code shows errors. Please help me to fix this problem.
Here is my Java code:
public void kirim(){
try{
koneksi();
String data ="select count(Number) from pbk";
ResultSet rs1 = cn.executeQuery(data);
while (rs1.next()){
rs1.getString(1);
}
int banyakData=Integer.parseInt(rs1.getString(1));
for (int i=0; i<=banyakData ;i++){
String sqi = "select Number from pbk";
ResultSet rs = cn.executeQuery(sqi);
while(rs.next()){
rs.getString(sqi);
}
String sql="insert into outbox (DestinationNumber, TextDecoded, CreatorID) values ("
+ "'"+sqi +"',"
+ "'" + jTextArea1.getText()+ "',"
+ "'1'"
+ ")";
cn.executeUpdate(sql);
} JOptionPane.showMessageDialog(null, "Pesan terkirim");
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Pesan gagal terkirim");
System.out.println(e.getMessage());
}
}
Here is stack trace output:
After end of result set
Change your code to
ResultSet rs1 = cn.executeQuery(data);
int banyakData;
while (rs1.next()){
banyakData= rs1.getInt(1);
}
and remove
int banyakData=Integer.parseInt(rs1.getString(1));
With you approach you have already iterated through the resultset and after the completition of the while loop you are again fetching from resultset giving you the error.
And also simply doing rs.getString(sqi); and rs1.getString(1); in a while loop doesnt make any sense if you dint put the result in any variable btw sqi is not a valid parameter.
Related
After a morning of research, I'm stumped on what should be an easy piece of code.
All I want is to get all records from our raw_material table in the test database.
Here is what I am doing:
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0");
do {
String result = rs.getString("raw_material_number").toString();
System.out.println("next item: " + result);
//ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Here are the results in mySQL:
so I would expect the first 'result' to be MAN-500-121200000, but it is showing as RAW-001485
I cannot see anywhere in the code that I am 'skipping' the first record, but if I let it go, it will skip the next one to MAN-500-056100000
Am I using the wrong user connection? That is the only thing I can see that affects this.
I thought user.getConnection() would do it for just the regular test database.
Your code seems to be incorrect, the expected loop is rather:
while(rs.next()) {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
Consider using try-with-resources statement to close properly your Connection, Statement and ResultSet as next:
try (Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id > 0")) {
// My code here
}
Try like this.
while(rs.next()){
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
}
public static void fetchIthos(ArrayList<String> ithosList, UserDto user) {
// TODO Auto-generated method stub
int i = 1;
//get our stuff first - raw materials and doc names and paths
try {
Connection conn = user.getConnection();
Statement st = conn.createStatement();
ResultSet rsCount = st.executeQuery("SELECT COUNT(*) from raw_material");
rsCount.first();
long r = (Long) rsCount.getObject(i);
for (i=1; i < r+1; i++) {
ResultSet rs = st.executeQuery("SELECT * FROM raw_material where object_id =" + i + "");
//moves to the first record
rs.first();
do {
String result = rs.getString("raw_material_number");
System.out.println("next item: " + result);
ithosList.add(rs.getString("raw_material_number"));
} while(rs.next());
}
}
catch (Exception e) {
ithosList.equals(null);
System.out.println("DB error : " + e);
}
}
Hacky way of doing it but it got it to work for now, at least until the senior developer returns from bereavement. Keep in mind I've had only 3 months of java, baptism by fire. lol.
I've searched around for the answer to this, but to no avail. When I compile this, it just returns the last row of my table in the database and not a list of the entire column as I expect. I believe the problem is from here.. If only I can make it list everything in that column, I'd be grateful for your help.
String query = "SELECT contact_id, first_name, last_name FROM my_contacts";
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
String name = rs.getString(2) + " " + rs.getString(3);
names = new JComboBox();
names.addItem(rs.getString("first_name"));
}//end while
When I compile this, it just returns the last row of my table in the
database and not a list of the entire column as I expect. I believe
the problem is from here..
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
String name = rs.getString(2) + " " + rs.getString(3);
names = new JComboBox();
names.addItem(rs.getString("first_name"));
}
your code created a new instance of JComboBox, in each of loop inside while (rs.next()){
create JComboBox as local variable, then just to add Items in while-loop to instance that already exist and is intialized
best of ways is by using DeafultComboBoxModel for add / remove / modify an Items for JComboBox
Got everything up and running with this code.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/recall", "username", "password");
Statement statement = connection.createStatement();
String query = "SELECT * FROM names";
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
String name = rs.getString("name");
names.addItem(rs.getString("name"));
}//end while
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
I am coding a simple CRUD Application in java and I have a Method to select Produkts that go with bills.
Here is my code:
public Rechnung selectProdukte(int target){
int tempProdukt;
int tempAnzahl;
try {
PreparedStatement ps1=hsqlmanager.getConnection().prepareStatement("SELECT produkt, anzahl from gekauftes_produkt " +
"WHERE rechnung= " + target + ";");
//ps1.setInt(1, target);
//Query 1wird executiert
PreparedStatement ps2 = hsqlmanager.getConnection().prepareStatement("SELECT * FROM rechnung WHERE id= " + target + ";");
//ps2.setInt(1, target);
ResultSet rs1 = ps1.executeQuery();
ResultSet rs2 = ps2.executeQuery();
Rechnung erg=new Rechnung();
erg.setId(rs2.getInt(1));
erg.setDatum(rs2.getDate(2));
erg.setSumme(rs2.getDouble(3));
while(rs1.next()){
tempProdukt=rs1.getInt(1);
tempAnzahl=rs1.getInt(2);
erg.addGekauftTupel(tempProdukt, tempAnzahl);
}
ps1.close();
ps2.close();
return erg;
} catch(Exception e) {
log.error("Fehler in DAO Rechnung - selectProdukte: " + e);
}
return null;
}
When I press the Button to execute the code I get:
java.sql.SQLException: invalid cursor state: identifier cursor not
positioned on row in UPDATE, DELETE, SET, or GET statement: ;
ResultSet is positioned before first row
I checked the db and all the tables and entities exist. So my question is:
What does that mean?
I appreciate your answer!!!
PS.: I am using hsql db!
you have not called rs2.next() before accessing erg.setId(rs2.getInt(1));
I have some problems with JDBC's rs.getString("column_name") basically it would not assign the value recieved from the query result, I have a String ris which is supposed to get the row name from rs.getString, for semplicity of the question I'm using ris and my query returns only one row. This is the code:
//It returns null, or any other values I use to initialize the variable
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
}
else {
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
I semplified the code, so it would be easy to focus on where the problem is.
Thanks in advance!
if (rs.last())
while (rs.next())
That won't work, because after you have called last , you are at the last row and next will always return false (it would return true and take you to the next row if there was one left).
And please use a prepared statement with bind variables!
And finally close ResultSet and Connection (or use Jakarta Commons DbUtils).
try this, just remove the rs.last() call in the if condition.. also i agree with #Thilo about using prepared statements.
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
rs.first(); // go to first record.
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();
I'm trying to get data from DB.
I must use to queries.
From the first query (In Loop) I get the code of Work codew and the I use it in the second query to get names.
Here's the code works without errors.
The first query fetch rows but the second is not executed.
int i=0;
c= new Connect().getCon();
try{
java.sql.Statement st = c.createStatement();
String sql= " SELECT distinct(s.codew), title, nberstat, desc_w, dated,datef" +
" FROM work w, employe e, stat s " +
" WHERE w.codew=s.codew " +
" and s.idemploye= e.idemploye " +
" and stat_w=0 " +
" and w.idcreator= 1";
System.out.println(sql);
ResultSet res = (ResultSet) st.executeQuery(sql);
String allW ="";
while (res.next())
{
String codew = res.getString("codew");
String title = res.getString("title");
String desc_w = res.getString("desc_w");
String dated = res.getString("dated");
String date = res.getString("datef");
int nberstat = res.getInt("nberstat"); String strnberstat = Integer.toString(nberstat);
///////////////////////////////////
try
{
java.sql.Statement st2 = c.createStatement();
q="SELECT distinct (name), lname From stat s, employe e WHERE codew LIKE '"+codew+"'";
ResultSet res2 = (ResultSet) st2.executeQuery(q);
while (res2.next())
{
String name = res.getString("name");
String lname = res.getString("lname");
allW = name + " "+lname+", "+allW;
}
}
catch (SQLException s)
{
System.out.println("SQL code does not execute.");
}
/////////////////////////////
........
}
c.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
I get this in the console for the second query! SQL code does not execute.
Thanks in advance.
Best regards,
Ali
First of all you should use PreparedStatement with sql parameters "?" to prevent Sql injections.
Secondly, you are using the wrong statement in the second loop. You should be using res2 not res.
This should be:
String name = res2.getString("name"); //not res
String lname = res2.getString("lname"); //not res
Thirdly, you should add a finally{} block and close your connection.