Below is my Code..
while(obt.hasNext()){
try{
Object itrvalue = obt.next();
String sql2 ="select entryDt,Student_Name,Class_Div_Name,ReceiptNo from test where ReceiptNo = '"+itrvalue+"'";
System.out.println("Receipt No --"+itrvalue);
stat = con.prepareStatement(sql2);
rs=stat.executeQuery();
rs.next();
Date datevalue = rs.getDate(1);
String name = rs.getString(2);
String CDN = rs.getString(3);
String RNO = rs.getString(4);
System.out.println("Date is ---"+datevalue);
System.out.println("Student Name ---"+name);
System.out.println("Coloumn Div No ---"+CDN);
System.out.println("Receipt No ---"+RNO);
rs.close();
}
catch(Exception ex){};
}
Output : -
Receipt No --S00000001234
Date is ---2013-06-10
Student Name ---ABC XYZ
Coloumn Div No ---VI - C
Receipt No ---S00000001234
Receipt No --S00000001234
Receipt No --S00000001235
Receipt No --S00000001236
Receipt No --S00000001237
Receipt No --S00000001238
Receipt No --S00000001239
Every iteration value's are getting changed. But in Current SQL query it's getting passed only 1st value remaining iteration values are getting displayed, but not getting passed in SQL Query. As per output you can see I have received data only S00000001234 and I want same details of all Receipt No.
You may have raised an exception. Try this code instead:
String sql2 = "select entryDt,Student_Name,Class_Div_Name,ReceiptNo from test where ReceiptNo = ?";
PreparedStatement stat = con.prepareStatement(sql2);
try {
while (obt.hasNext()) {
try {
Object itrvalue = obt.next();
System.out.println("Receipt No --" + itrvalue);
stat.setObject(1, itrvalue);
rs = stat.executeQuery();
rs.next();
Date datevalue = rs.getDate(1);
String name = rs.getString(2);
String CDN = rs.getString(3);
String RNO = rs.getString(4);
System.out.println("Date is ---" + datevalue);
System.out.println("Student Name ---" + name);
System.out.println("Coloumn Div No ---" + CDN);
System.out.println("Receipt No ---" + RNO);
rs.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} finally {
if (stat != null) {
stat.close();
}
}
Related
I'm trying to retrieve all the values stored in a database where it matches the sensor name.
The code runs however, it only outputs the final value in the database.
String info = "test info"
String sensorNameStr = "test sensor name";
String sensorValueStr = "test sensor value";
String selectSQL = "select sensorvalue from sensorUsage where "+
" sensorname = '" + sensorNameStr +
"' order by TimeInserted asc";
String retrievedSensorData = "no data available";
try {
PreparedStatement pst = conn.prepareStatement(selectSQL);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
retrievedSensorData = rs.getString(1);
}
} catch (SQLException ex) {
System.out.println("Error in SQL " + ex.getMessage());
}
String json = "{\"sensor\": {\"" + sensorNameStr +
"\": \"" + retrievedSensorData + "\"}}";
System.out.println("DEBUG: json return: "+json);
Do I have to create a for loop so all values are returned and outputted on a webpage? As that's how I am viewing the data without manually going into the server. Also, if I do this, is it possible to only receive the last few inserted sensor values?
Help will be appreciated!
In your SQL query you retrieve only rows from column sensorvalue and all belong to specific sensorname. There are no other condition.
So it should be easy to make an Json with the Java EE API
// ...
JsonObject model = null;
try
{
// ...
ResultSet rs = stmt.executeQuery();
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
while(rs.next())
{
jsonArrayBuilder.add(rs.getString("sensorvalue"));
}
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("sensorvalues", jsonArrayBuilder);
model = jsonObjectBuilder.build();
}
catch (Exception e)
{
System.out.println(e);
}
response.setContentType("application/json; charset=utf-8");
StringWriter stWriter = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(stWriter);
jsonWriter.writeObject((JsonObject) model);
jsonWriter.close();
response.getWriter().append(stWriter.toString());
The output should be something like:
{"sensorvalues":["1","2"]}
I am trying to complete my Java Code to execute a SELECT Query that will write the Results into Sysout.
Here is my Code:
public void PullFromDB() {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
String sql = "SELECT * FROM " + Name + ";";
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
Integer ID = rs.getInt("id");
System.out.println("ID = " + ID.toString());
String entry = rs.getString(Properties.get(j));
System.out.println(Properties.get(j) + "=" + entry);
j++;
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
When I sysout my SQL Query it looks like this:
CREATE TABLE IF NOT EXISTS Cars(ID INTEGER PRIMARY KEY AUTOINCREMENT,AnzSitze TEXT,Marke TEXT,Pferdestärke TEXT);
INSERT INTO Cars(AnzSitze,Marke,Pferdestärke) VALUES('vier','Audi','420');
SELECT * FROM Cars;
Those are just some examples I put in.
maybe create and propabley insert has failed, i see none-ascii characters in filed name Pferdestärke try to use valid names
check this
Permitted characters in unquoted identifiers:
ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,
underscore)
Extended: U+0080 .. U+FFFF
so replace the filed name Pferdestärke to Pferdestarke in all qrys and try again
I'm writing a program where the user has to sign in. I've reviewed my code again and again but I keep getting "null" as the error. This is not only the case for the sign in part of the program, but also for the part where the user can create an account. Basically, wherever I've implemented JDBC, a "null" error pops up. How do I fix this?
String user_name_check = user_name.getText().trim();
char[] pass = password_enter.getPassword();
String password_check = Arrays.toString(pass);
String query = "SELECT * FROM USER_INFO WHERE USERNAME = '" + user_name_check + "';";
try{
rs = st.executeQuery(query);
if(rs.next()){
//changing the panel (start)
if(password_check.equals(rs.getString("PASS"))){
MAIN.removeAll();
MAIN.add(news_feed);
MAIN.repaint();
MAIN.revalidate();
//changing the panel (end)
//giving values to class level field variables (start)
username = user_name_check;
firstname = rs.getString("FIRST_NAME");
lastname = rs.getString("LAST_NAME");
dob = rs.getString("DOB");
gender = rs.getString("GENDER");
bio = rs.getString("BIO");
home_user_name.setText(username);
set_dp(home_user_dp, username);
}
}
else sign_in_message.setVisible(true);
}
catch(Exception e){
System.out.println(e.getMessage() + " #jButton2ActionPerformed SIGN IN");
}
The error : null #jButton2ActionPerformed SIGN IN
EDIT
Here's the JDBC connection method :
public void JDBC_Connect(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/socialnetwork", "root", "mukundrox");
st = con.createStatement();
}
catch(Exception e){
System.out.println(e.getMessage() + " #JDBC_connect");
}
}
I have code like this
String sql_kode_kategori = "select kategori from data_kategori \n" +
"where kode_kategori = ?";
try{
pst = (PreparedStatement) koneksiMySQL.GetConnection().prepareStatement(sql_kode_kategori);
pst.setString(1, (String)cbKategori.getSelectedItem());
rst2 = pst.executeQuery();
rst2.next();
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
+ ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
stat.executeUpdate(sql_insert);
javax.swing.JOptionPane.showMessageDialog(null, "Data CES Berhasil Ditambahkan");
ClearField();
TampilTabel();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
i tried to get kode_kategori with kategori but that error appear, please help me
If rst2.next() returns false, there is no data for rst2.getString(1). You need to check for result as
if(rst2.next()) {
stat = (Statement) koneksiMySQL.GetConnection().createStatement();
String sql_insert = "INSERT INTO data_pasal VALUES ('"+jTPasal.getText() + "','"+jTIsi_Pasal.getText()+"'"
+ ",'"+jTHukuman.getText()+"','"+jTDenda.getText()+"','"+rst2.getString(1)+"')";
stat.executeUpdate(sql_insert);
} else {
// handle invalid category
}
Remove \n from your query:
String sql_kode_kategori = "select kategori from data_kategori where kode_kategori = ?";
Try to verify this (String)cbKategori.getSelectedItem() variable does contain right value.
i have a label and i want to upload with text from database, i wrote a method but its show just the first item from database, i want to see all item in column
try {
String sql="SELECT * FROM Arlista";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
while(rs.next()) {
arlab1.setText(rs.getString("nev"));
}
}catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
while(rs.next()) {
arlab1.setText(rs.getString("nev"));
}
...overwrites the content of arlab each iteration. What you probably want to do is some kind of append to the result for each row;
String result = "";
while(rs.next()) {
if(result.isEmpty()) result = rs.getString("nev");
else result = result + "/" + rs.getString("nev");
}
arlab1.setText(result);