Cannot insert data to Database Java without any error [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have tried to add stmt.executeUpdate(); to insert to the database, but it still not working!! After processing, no error is shown but no data is insert into the database.
try {
// do insert
String preparedSQL = "insert into abc (NUM, ID) VALUES (?,?)";
for(int i = 1; i < r.length; i++)
{
stmt = conn.prepareStatement(preparedSQL);
// SQL parameters
setString(stmt, i++, Num);
setString(stmt, i++, r[i]);
stmt.executeQuery();
}
stmt.executeUpdate();
stmt.close();
} catch (SQLException e) {
PrintWriter out = new PrintWriter(new OutputStreamWriter(res
.getOutputStream(), "Big5"), true);
res.setContentType("text/html; charset=utf-8");
res.setHeader("cache-control", "no-cache");
res.setHeader("Pragma", "no-cache");
res.setIntHeader("expiry", -1000);
out.println("..<!--" + RSCommonUtil.HTMLEncode(e.toString()) + "para in title not valid" +
RSCommonUtil.HTMLEncode(pDate.toString())
+ " " + RSCommonUtil.HTMLEncode(startPubDateAndEndPubDate[0].toString()) + " "
+ RSCommonUtil.HTMLEncode(startPubDateAndEndPubDate[1].toString()) + "-->");
debug.p("insert error" + e);
failed = true;
} finally {
try {
// finalize DB
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException sqle) {
}
}

executeUpdate is for create, drop, insert, update, delete etc., (i.e., updating your table), executeQuery is for select. It returns an instance of ResultSet.
See here for simple explanation: https://www.javatpoint.com/PreparedStatement-interface
Also, your setString has an incorrect number of parameters and it should be called as a method of the statement object, and the parameterIndex (first parameter of the setString method) should just be i, as you will otherwise increment three times for each iteration. I also changed the loop to start at 0, don't know why you would start at 1 as a normal array should start at 0.
So your main block would be something like this:
...
// do insert
String preparedSQL = "insert into abc (NUM, ID) VALUES (?,?)";
PreparedStatement stmt = conn.prepareStatement(preparedSQL);
for(int i = 0; i < r.length; i++)
{
// SQL parameters
stmt.setString(i, Num);
stmt.setString(i, r[i]);
stmt.executeUpdate();
}
stmt.close();
...

Inside the try block, try rewriting the code as follows:
String preparedSQL = "insert into abc (NUM, ID) VALUES (?,?)";
for(int i = 1; i < r.length; i++)
{
stmt = conn.prepareStatement(preparedSQL);
// SQL parameters
stmt.setString(1, Num);
stmt.setString(2, r[i]);
stmt.executeUpdate();
stmt.close();
}
The setString method takes only two parameters.
public void setString(int paramIndex, String value)
Here 'paramIndex' refers to the index of the parameter in your prepared statement and 'value' refers to which value you want to insert at that index.
The executeQuery() method of prepared statement interface is used for SELECT queries. But in your case, since the statement is an INSERT query, you will have to use executeUpdate() method. This method is used for CREATE, DROP, UPDATE, INSERT, etc. statements.
Refer this for more information regarding prepared statements and sample code.

The other Answers by yalda and by Nitish are both correct, with good advice. Ditto for some comments on the Question. I can add one more thought, plus a full working example app that writes and reads rows using the H2 Database Engine.
Try-With-Resources
Use the try-with-resources syntax to shorten your code, and guarantee your resources get closed appropriately.
Example app
package work.basil.example;
import org.h2.jdbcx.JdbcDataSource;
import java.sql.*;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.UUID;
public class H2DateTimeExample
{
public static void main ( String[] args )
{
H2DateTimeExample app = new H2DateTimeExample ();
app.demo ();
}
private void demo ( )
{
JdbcDataSource dataSource = new JdbcDataSource ();
dataSource.setURL ( "jdbc:h2:mem:offsetdatetime_example_db;DB_CLOSE_DELAY=-1" ); // Set `DB_CLOSE_DELAY` to `-1` to keep in-memory database in existence after connection closes.
dataSource.setUser ( "scott" );
dataSource.setPassword ( "tiger" );
// Create table.
String sql = "CREATE TABLE person_ ( \n" +
" pkey_ UUID NOT NULL DEFAULT RANDOM_UUID() PRIMARY KEY , \n" +
" name_ VARCHAR NOT NULL , \n" +
"first_contacted_ TIMESTAMP WITH TIME ZONE NOT NULL " +
") ;";
// System.out.println ( sql );
try (
Connection conn = dataSource.getConnection () ;
Statement stmt = conn.createStatement () ;
)
{
stmt.execute ( sql );
} catch ( SQLException e )
{
e.printStackTrace ();
}
// Insert row.
sql = "INSERT INTO person_ ( name_ , first_contacted_ ) \n";
sql += "VALUES ( ? , ? ) \n";
sql += ";";
try (
Connection conn = dataSource.getConnection () ;
PreparedStatement pstmt = conn.prepareStatement ( sql , Statement.RETURN_GENERATED_KEYS ) ;
)
{
OffsetDateTime odt = OffsetDateTime.now ( ZoneOffset.UTC );
pstmt.setString ( 1 , "Jesse Johnson" );
pstmt.setObject ( 2 , odt );
pstmt.executeUpdate ();
ResultSet rs = pstmt.getGeneratedKeys ();
// System.out.println( "INFO - Reporting generated keys." );
// while ( rs.next() ) {
// UUID uuid = rs.getObject( 1 , UUID.class );
// System.out.println( "generated keys: " + uuid );
// }
} catch ( SQLException e )
{
e.printStackTrace ();
}
// Query table.
sql = "TABLE person_ ;";
try (
Connection conn = dataSource.getConnection () ;
PreparedStatement pstmt = conn.prepareStatement ( sql ) ;
)
{
try ( ResultSet rs = pstmt.executeQuery () ; )
{
while ( rs.next () )
{
UUID pkey = rs.getObject ( "pkey_" , UUID.class );
String name = rs.getString ( "name_" );
OffsetDateTime firstContacted = rs.getObject ( "first_contacted_" , OffsetDateTime.class );
System.out.println ( "pkey: " + pkey + " | name: " + name + " | firstContacted: " + firstContacted );
}
}
} catch ( SQLException e )
{
e.printStackTrace ();
}
System.out.println ( "Done." );
}
}
pkey: 0819123b-5c7f-4859-bd1b-f9dac82b855f | name: Jesse Johnson | firstContacted: 2019-08-03T18:16:30.367840Z
Done.

Related

Why my data cannot be insert into database? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I cannot save the input into my database. Can anybody help me?
There's SSL problem but it is able to solve by setting SSL to false, but the data seems like only able to read but not save into my database.
package first;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Connection;
import javax.swing.JOptionPane;
public class CustomersForm extends javax.swing.JFrame {
public CustomersForm() {
initComponents();
}
private void jButton_addcusActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionURL = "jdbc:mysql://localhost:3308/java_his_db";
Connection con = DriverManager.getConnection(connectionURL, "root", "");
String sql = "Insert into customers ('fname') values (?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(2, jTextField_fname.getText());
ps.executeUpdate();
System.out.println("YES");
con.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(rootPane, "Blank or Wrong User Profile", "Insert Error", 2);
}
}
private void jTextField_fnameActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
The Answer by Andrew Vershinin looks correct. Your placeholder number 2 should be 1.
You commented that you still have errors, but neglected to describe those errors. The errors might be from your SQL for the INSERT statement. You should not make a string of the column name. You put single-quotes where they do not belong. As commented by Abra, this single quotes around 'fname' makes that text into a string literal rather than the name of a column. A string literal makes no sense in SQL where a column name is expected.
Your code:
String sql = "Insert into customers ('fname') values (?)";
…should be:
String sql = "INSERT INTO customers ( fname ) values (?) ;";
In my example below, you will see similar code:
INSERT INTO person_ ( name_ )
VALUES ( ? )
;
Here is an entire example app that creates a database with one table person_, inserts two rows in that table, and retrieves those two rows. You can see how calling PreparedStatement#set… methods works.
This code uses the H2 Database Engine. But the following code will be nearly the same for any SQL database.
Tip: Separate your database access code from your GUI code. Get that database code worked out and running smoothly before trying to integrate with GUI.
Tip: Use try-with-resources to automatically close your connection, statement, result set, and so on.
Tip: Always include the optional semicolon statement terminator. You can get away without it in some places, but could mess up code in other places. Be neat, be consistent.
package work.basil.example;
import com.thedeanda.lorem.LoremIpsum;
import org.h2.jdbcx.JdbcDataSource;
import javax.sql.DataSource;
import java.sql.*;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.Objects;
public class DbH2Example
{
public static void main ( String[] args )
{
DbH2Example app = new DbH2Example();
app.demo();
}
private void demo ( )
{
// -------------------| DataSource |---------------------------------
DataSource dataSource = null;
{
org.h2.jdbcx.JdbcDataSource ds = Objects.requireNonNull( new JdbcDataSource() ); // Implementation of `DataSource` bundled with H2.
ds.setURL( "jdbc:h2:mem:MyExampleDb;DB_CLOSE_DELAY=-1" ); // To keep an in-memory database after disconnecting, add DB_CLOSE_DELAY=-1 argument.
ds.setUser( "scott" );
ds.setPassword( "tiger" );
ds.setDescription( "An example database showing how to insert a row." );
dataSource = ds;
}
Objects.requireNonNull( dataSource );
// -------------------| Prepare database |---------------------------------
{
String sql =
"""
DROP TABLE IF EXISTS person_
;
CREATE TABLE IF NOT EXISTS person_
(
name_ text NOT NULL ,
row_created_ TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP() ,
id_ IDENTITY NOT NULL ,
CONSTRAINT person_pkey_ PRIMARY KEY ( id_ )
)
;
""";
try (
Connection conn = dataSource.getConnection() ;
Statement stmt = conn.createStatement() ;
)
{
System.out.println( "INFO - Preparing database. Message # adaaf8ed-8922-4c15-addf-35f6ead1442b. " + Instant.now() );
stmt.executeUpdate( sql );
}
catch ( SQLException e )
{
e.printStackTrace();
}
}
// -------------------| Insert row |---------------------------------
{
System.out.println( "INFO - Insert rows. Message # 7a7e1c0a-7e97-4ebc-8d24-6e9ea20f8b5f. " + Instant.now() );
String sql =
"""
INSERT INTO person_ ( name_ )
VALUES ( ? )
;
""";
try
(
Connection conn = dataSource.getConnection() ;
PreparedStatement ps = conn.prepareStatement( sql ) ;
)
{
ps.setString( 1 , "Alice" );
ps.executeUpdate();
ps.setString( 1 , "Bob" );
ps.executeUpdate();
}
catch ( SQLException e )
{
e.printStackTrace();
}
}
// -------------------| Dump rows |---------------------------------
{
System.out.println( "INFO - Dump rows. Message # f6b786be-ef1e-4b97-9779-59bc84566e3d. " + Instant.now() );
try
(
Connection conn = dataSource.getConnection() ;
Statement stmt = conn.createStatement() ;
)
{
String sql =
"""
TABLE person_
;
""";
try (
ResultSet rs = stmt.executeQuery( sql ) ;
)
{
while ( rs.next() )
{
String name = rs.getString( "name_" );
Instant whenCreated = rs.getObject( "row_created_" , OffsetDateTime.class ).toInstant();
long id = rs.getLong( "id_" );
System.out.println( "whenCreated = " + whenCreated + " | " + "id : " + id + " | " + "name = " + name );
}
}
}
catch ( SQLException e )
{
e.printStackTrace();
}
}
}
}
When run.
INFO - Preparing database. Message # adaaf8ed-8922-4c15-addf-35f6ead1442b. 2021-01-23T06:44:22.363589Z
INFO - Insert rows. Message # 7a7e1c0a-7e97-4ebc-8d24-6e9ea20f8b5f. 2021-01-23T06:44:22.389564Z
INFO - Dump rows. Message # f6b786be-ef1e-4b97-9779-59bc84566e3d. 2021-01-23T06:44:22.414178Z
whenCreated = 2021-01-23T06:44:22.393600Z | id : 1 | name = Alice
whenCreated = 2021-01-23T06:44:22.413983Z | id : 2 | name = Bob
You have only one placeholder in your query, therefore in this statement the index should be one: ps.setString(1, jTextField_fname.getText());

JDBC query does not return any values without errors

I have a local SQL-Server running MariaDB and need to query Data from a database using Java and JDBC. I can connect to the Database and also write data, but a simple SELECT does not work.
I already tried to use different versions of the mysql-java-connector and checked that the SQL-Server is up to date.
Connecting to Database:
//Check wether connection already exists
if(connection != null && !connection.isClosed()){
return;
}
//Create new connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/statdb", "root", "");
System.out.println("Connected to Database");
//Update guilds from Database
updateGuildsInDatabase();
The method called at the end looks like this:
private void updateGuildsInDatabase() throws SQLException {
//Check for not existing connection
if(connection == null || connection.isClosed()){
init();
return;
}
ArrayList<String> localInDb = new ArrayList<>();
Statement qGStmt = connection.createStatement();
//Execute Query
ResultSet guilds = qGStmt.executeQuery("SELECT * FROM guilds;");
guilds.first();
//Adding results to List
while(guilds.next()){
localInDb.add(guilds.getString("guild_uid").toLowerCase());
}
System.out.println("Queried: " + localInDb.size());
this.guildsInDb = localInDb;
}
The table "guilds" in the database "statdb" has two columns named "guild_uid" (primary key, varchar) and "display_name" (varchar). I've added one entry with the values "guild_1" and "Test Guild".
As I have one entry in the table 'guilds' I would expect the console to look like this:
Connected to Database
Queried: 1
But the actual output looks like this:
Connected to Database
Queried: 0
The ResultSet#first() method itself moves the cursor to the first row of the result set. The ResultSet#next() method then moves the cursor forward by one, and reads whatever record is there, if a record is there.
Therefore, using your pattern will always result in skipping the first record from the result set. If the result set happens to have only a single record, then the record count will appear to be zero.
You should probably remove the call to ResultSet#first(). Use this instead:
ResultSet guilds = qGStmt.executeQuery("SELECT * FROM guilds;");
while(guilds.next()) {
localInDb.add(guilds.getString("guild_uid").toLowerCase());
}
System.out.println("Queried: " + localInDb.size());
this.guildsInDb = localInDb;
The reason why calling ResultSet#next() on a fresh result set logically works, is that by default a JDBC result set actually does not start pointing to the first record. Rather, we typically advance it to the first record with the very first call to ResultSet#next().
I don't think you need guilds.first(). Try removing it.
According to the ResultSet JavaDoc:
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
I believe what is happening here is, guilds.first() set the cursor from before first row to first row. And guilds.next() in the while loop move the cursor to further one step ahead. Therefore, you are missing the first row.
The other two Answers are correct, you are skipping the first row when retrieving from the result set. No need for your line guilds.first(); as they explained, the result set automatically points at first row by default.
Example code, retrieving from ResultSet
Here is a complete example using the H2 Database Engine. This shows creating a new database (in-memory, not persisted to disk), adding a table, populating that table with a few rows, and then retrieving all those rows through a ResultSet.
The key line is while ( rs.next() ) {.
package work.basil.example;
import java.sql.*;
import java.util.*;
import org.h2.jdbcx.JdbcDataSource;
import javax.sql.DataSource;
public class GuildDemo {
public static void main ( String[] args ) {
GuildDemo app = new GuildDemo();
app.doIt();
}
private void doIt ( ) {
DataSource dataSource = null;
final String catalogName = "guild_demo_";
final String tableName = "guild_";
// Verify JDBC driver.
try {
Class.forName( "org.h2.Driver" );
JdbcDataSource ds = new JdbcDataSource(); // The `javax.sql.DataSource` interface implemented by `org.h2.jdbcx.JdbcDataSource`.
ds.setURL( "jdbc:h2:mem:" + catalogName + ";DB_CLOSE_DELAY=-1" ); // Set delay to -1 to keep in-memory database even after last connection closed.
ds.setUser( "scott" );
ds.setPassword( "tiger" );
ds.setDescription( "Dummy database for demo showing how to retrieve rows from a ResultSet." );
dataSource = ds; // Generalize from the concrete class to the interface.
} catch ( ClassNotFoundException e ) {
e.printStackTrace();
return;
}
// Connect, and create database.
try (
Connection conn = dataSource.getConnection() ;
) {
String sql = null;
// Create table.
try ( Statement stmt = conn.createStatement() ; ) {
sql = "CREATE TABLE " + "guild_" + " ( \n" +
" pkey_ UUID DEFAULT random_uuid() PRIMARY KEY , \n" +
" name_ VARCHAR NOT NULL \n" +
") ; \n";
System.out.println( "TRACE - SQL:\n" + sql );
stmt.execute( sql );
}
// Add rows.
sql = "INSERT INTO guild_ ( name_ ) \n" +
"VALUES ( ? ) " +
"; ";
List < String > names = List.of( "Alpha" , "Beta" , "Gamma" , "Delta" ); // Insert a row for each of these names.
System.out.println( "Inserting list of names: " + names );
try (
PreparedStatement ps = conn.prepareStatement( sql ) ;
) {
for ( String name : names ) {
ps.setString( 1 , name );
ps.executeUpdate();
}
}
// Retrieve rows from a `ResultSet`.
sql = "SELECT * FROM " + "guild_" + " ;";
try (
Statement stmt = conn.createStatement() ;
ResultSet rs = stmt.executeQuery( sql ) ;
) {
while ( rs.next() ) {
UUID pkey = rs.getObject( "pkey_" , UUID.class );
String name = rs.getString( "name_" );
System.out.println( "Row pkey_: " + pkey + " name_: " + name );
}
}
} catch ( SQLException e ) {
e.printStackTrace();
}
}
}
When run.
Inserting list of names: [Alpha, Beta, Gamma, Delta]
Row pkey_: 69908390-5fa6-4eee-8e12-40106db8d60d name_: Alpha
Row pkey_: 3116acb9-fcce-427f-b222-99c78c6e752a name_: Beta
Row pkey_: b3fd0930-a2e7-461a-be70-f05124fc58de name_: Gamma
Row pkey_: dddb423a-5eb2-4e5e-be16-7bb0c27c0033 name_: Delta

java - only reading and extracting one file to table

I have a program where I extract a text from PDF file and insert those text in a form of words into a table in MySQL.
I have two tables, a queue table and a word table.
The program retrieves a file from the queue table and build an index of words to the word table.
It works fine, but the problem is it only grabs one file but not the other files after that. Meaning, it only perform on the 1st file and then it closes. I am using a while loop and I disable autocommit so I have to commit it manually.
Did I make any mistake?
Code:
public void index1() throws Exception
{
try
{
// Connection con1=con.connect();
Connection con1 = con.connect();
Statement statement = con1.createStatement();
ResultSet rs = statement.executeQuery( "select * from filequeue where Status='Active' LIMIT 5" );
while ( rs.next() )
{
// get the filepath of the PDF document
String path1 = rs.getString( 2 );
int getNum = rs.getInt( 1 );
// while running the process, update status : Processing
//updateProcess_DB(getNum);
Statement test = con1.createStatement();
test.executeUpdate( "update filequeue SET STATUS ='Processing' where UniqueID=" + getNum );
try
{
// call the index function
/*Indexing process = new Indexing();
process.index(path1);*/
PDDocument document = PDDocument.load( new File( path1 ) );
if ( !document.isEncrypted() )
{
PDFTextStripper tStripper = new PDFTextStripper();
String pdfFileInText = tStripper.getText( document );
String lines[] = pdfFileInText.split( "\\r?\\n" );
for ( String line : lines )
{
String[] words = line.split( " " );
String sql = "insert IGNORE into test.indextable values (?,?);";
preparedStatement = con1.prepareStatement( sql );
int i = 0;
for ( String word : words )
{
// check if one or more special characters at end of string then remove OR
// check special characters in beginning of the string then remove
// insert every word directly to table db
word = word.replaceAll( "([\\W]+$)|(^[\\W]+)", "" );
preparedStatement.setString( 1, path1 );
preparedStatement.setString( 2, word );
preparedStatement.addBatch();
i++;
if ( i % 1000 == 0 )
{
preparedStatement.executeBatch();
System.out.print( "Add Thousand" );
}
}
if ( i > 0 )
{
preparedStatement.executeBatch();
System.out.print( "Add Remaining" );
}
}
}
// con1.commit();
// con1.close();
preparedStatement.close();
System.out.println( "Successfully commited changes to the database!" );
// After completing the process, update status: Complete
Statement pre = con1.createStatement();
pre.executeUpdate( "update filequeue SET STATUS ='Complete' where UniqueID=" + getNum );
con1.commit();
preparedStatement.close();
System.out.println( "Successfully commited changes to the database!" );
con1.close();
// updateComplete_DB(getNum);
}
catch ( Exception e )
{
try
{
System.err.println( e );
// updateError_DB(getNum);
// update status = Error in queue table if any error
Statement statement1 = con1.createStatement();
statement1.execute( "update filequeue SET STATUS ='Error' where UniqueID=" + getNum );
// add rollback function
rollbackEntries();
}
catch ( Exception e1 )
{
System.out.println( "Could not rollback updates :" + e1.getMessage() );
}
}
}
}
catch ( Exception e )
{
}
}

Get the return value of date diff?

So i have this query using DATEDIFF function on MS SQL Server?
SELECT DATEDIFF(DAY,(select StartDate from CarOrder where OrderID= 59),(select EndDate from CarOrder where OrderID= 59))
This work fine and the result is 10 but i dont know how to get the return value and use it in this function for java
public int getDateDiff(int OrderID){
Connection conn = DBConnection.getConnection();
int datediff;
String getdiffSQL = "SELECT DATEDIFF(DAY,(select StartDate from CarOrder where OrderID = ? ) ,(select EndDate from CarOrder where OrderID= ?) )";
try {
PreparedStatement pstm = conn.prepareStatement(getdiffSQL);
pstm.setInt(1, OrderID);
pstm.setInt(2, OrderID);
int nRows = pstm.executeUpdate();
return nRows;
} catch (SQLException ex) {
System.out.println("Error: " + ex.getMessage());
} finally {
DBConnection.closeConnection(conn);
}
}
i want it to return the date diff number so that it is a variable i can use in java, how can i do this ?
Thank You.
Use ResultSet
You need to capture the ResultSet, and access the rows of that ResultSet (in this case a single row). If you are executing a query, call executeQuery on your PreparedStatement, thereby producing a ResultSet.
Use the modern try-with-resources syntax to automatically close your database resources. You can drop the finally clauses; no need to call closeXXX on your database resources as that chore is handled for you.
I have not tried executing the following code example, but I hope it is close to what you need. I am using the alternate SELECT line suggested in comment by Martin Smith; I’ve not put thought into that as it is not the core of your Question.
String sql = "SELECT DATEDIFF( DAY , StartDate , EndDate ) FROM CarOrder WHERE OrderID = ? ;" ;
Integer diff = null ;
try (
Connection conn = myDataSource.getConnection() ;
PreparedStatement pstmt = conn.prepareStatement ( sql ) ;
) {
pstmt.setInt( 1 , orderId ) ;
try (
ResultSet rs = pstmt.executeQuery( sql ) ;
) {
while ( rs.next ( ) ) {
diff = rs.getInt( 1 ) ; // Auto-boxing `int` to `Integer`.
}
}
}
} catch ( SQLException e ) {
e.printStackTrace ( ); // Handle error condition however you see fit.
}
if( null == diff ) {
System.out.println( "mission failed." ) ;
} else {
System.out.println( "mission succeeded. Diff is: " + diff ) ;
}
For real work, I would also test to make sure I had only one row returned (make sure that while loop runs exactly once rather than zero or more than once).
If this is not clear to you about the various database resources (DataSource, Connection, PreparedStatement, ResultSet), you should put down the IDE and do some more study of the Oracle Tutorial on JDBC matters, and do some searching/studying of Stack Overflow on the topic.
Store the result of the query in the ResultSet object, and then pick the value of the appropriate column by using of {YOUR_RESULT_SET}.getYourDataType(columnNumber).

Table access - SQL (Java)

Suppose I have a table MYtable as given below:
ID A B C
1 100 APPLE CAKE
2 200 BANANA PIE
I want to be able to save all these table records into a list (of some kind) and iterate through each record.
Query would be :
select * from Mytable where ID in (1,2,3)
So,the list should have 2 records:
record1 should contain 1,100,APPLE,CAKE
and record2 should contain 2,200,BANANA,PIE
I also want to be able to iterate through each record
So for record1 - I want to getColumnA i.e 100, getColumnB i.e APPLE, and so on
List<YourObject> listOfObjects = new ArrayList<YourObject>();
while(rs.next()){
int id = rs.getInt(1);
int A = rs.getInt(2);
String B= rs.getString(3);
String C = rs.getString(4);
YourObject ob = new YourObject (id, A, B, C);
listOfObjects.add(ob); //now you have the list of objects .. iterate trough it
}
First you will need JDBC to connect to the database.
You can use Statement or PreparedStatement to fetch data from database and then you can get that data stored in ResultSet.
Now you can iterate through the results in ResultSet.
For that you need to implement JDBC.
After creating JDBC connection. Execute query and the fetch records from the resultset. From a record you can fetch particular columns as well.
see following example how to work with jdbc basic
http://www.jdbc-tutorial.com/
import java.sql.* ;
class JDBCQuery
{
public static void main( String args[] )
{
try
{
// Load the database driver
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;
// Get a connection to the database
Connection conn = DriverManager.getConnection( "jdbc:odbc:Database" ) ;
// Print all warnings
for( SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning() )
{
System.out.println( "SQL Warning:" ) ;
System.out.println( "State : " + warn.getSQLState() ) ;
System.out.println( "Message: " + warn.getMessage() ) ;
System.out.println( "Error : " + warn.getErrorCode() ) ;
}
// Get a statement from the connection
Statement stmt = conn.createStatement() ;
// Execute the query
ResultSet rs = stmt.executeQuery( "select * from Mytable where ID in (1,2,3)" ) ;
// Loop through the result set
while( rs.next() )
{
System.out.println( rs.getString('ID') ) ;
System.out.println( rs.getString('A') ) ;
System.out.println( rs.getString('B') ) ;
System.out.println( rs.getString('C') ) ;
}
// Close the result set, statement and the connection
rs.close() ;
stmt.close() ;
conn.close() ;
}
catch( SQLException se )
{
System.out.println( "SQL Exception:" ) ;
// Loop through the SQL Exceptions
while( se != null )
{
System.out.println( "State : " + se.getSQLState() ) ;
System.out.println( "Message: " + se.getMessage() ) ;
System.out.println( "Error : " + se.getErrorCode() ) ;
se = se.getNextException() ;
}
}
catch( Exception e )
{
System.out.println( e ) ;
}
}
}

Categories

Resources