I'm trying to get the data from database but get nothing. The problem is
ResultSet resultSet = statement.executeQuery(readQuery);
always empty. And
while (resultSet.next())
is never executing.
Would really appreciate any help
public class DB {
public Connection connect() {
Connection connection = null;
try {
String databaseURL = "jdbc:derby://localhost:1527/DB;create=true;user=user;password=password";
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connection = DriverManager.getConnection(databaseURL);
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
return connection;
}
ArrayList read(Connection connection, String table, String column, String value) {
ArrayList results = new ArrayList();
Statement statement = null;
try {
statement = connection.createStatement();
String readQuery = "select * from " + table + " where " + column + " = '" + value + "'";
out.print(readQuery);
ResultSet resultSet = statement.executeQuery(readQuery);
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
int numberOfColumns = resultSetMetaData.getColumnCount();
out.print("Read\n");
for (int i = 1; i < numberOfColumns + 1; i++) {
results.add(resultSet.getString(i));
}
}
statement.close();
connection.close();
}
catch (SQLException ex) {
}
return results;
}
}
Related
How do I tell my java program to retrieve the next matching record into my default table model.
Below is my home work so far.using jTable tb1 and default table model dtm is compulsory for me.
private void Show_My_LettersActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(url, "root", "root");
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT * from LCI where SUB_ID = '" + SUB_ID_.getText() + "' AND L_DATE = '" + DATE.getText() + "'";
ResultSet rs1, rs2, rs3, rs4, rs5, rs6, rs7;
rs1=j.getData("select COUNT(*) from LCI");
try (ResultSet rs = stmt.executeQuery(sql)) {
DefaultTableModel dtm = (DefaultTableModel) tb1.getModel();
while (rs.next()) {
String L_ID_ = rs.getString("L_ID");
String L_DATE_ = rs.getString("L_DATE");
String heading = rs.getString("HEADING");
String sub_id = rs.getString("SUB_ID");
System.out.print("ID: " + L_ID_);
System.out.print(", Letter date: " + L_DATE_);
System.out.print(", Heading " + heading);
System.out.println(", Subject ID " + sub_id);
/* This gives the correct out put when debug is done.
But the below code doesn't retrive the full out put.
It gives only the very first record matching with the user inputs*/
Vector v = new Vector();
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
JOptionPane.showMessageDialog(this, "Done");
dtm.getColumnName(1);
v.addElement(rs.getString(1));
dtm.addColumn(v);
dtm.getColumnName(3);
v1.addElement(rs.getString(3));
dtm.addColumn(v1);
dtm.getColumnName(10);
v2.addElement(rs.getString(10));
dtm.addColumn(v2);
// stmt.executeQuery("SELECT * FROM LCI WHERE L_ID IN(SELECT (L_ID + 1)FROM LCI WHERE L_DATE = '"+DATE.getText()+"'");
dtm.addRow(v3);
//stmt.executeQuery("SELECT * FROM LCI WHERE L_ID IN(SELECT (L_ID '"+(+1)+"')FROM LCI WHERE L_DATE = '"+DATE.getText()+"'");
}
}
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}// TODO add your handling code here:
}
I'm new to java and DBMS. I'm trying to update/refresh the JTable after any changes made into the H2 database when user clicks a same button to show JTable and after writing data into database(when write button is clicked). I tried some methods and read some posts but couldn't find anything essential to my program. The code below illustrates my problem.
This is the method used to read from database and show it on JTable
public void readActiveData() throws IOException, InstantiationException, IllegalAccessException, SQLException {
try {
st = conn.createStatement();
} catch (SQLException sqlex) {
JOptionPane.showMessageDialog(null, "Can't connect to DB. " + sqlex);
dispose();
}
try {
rs = st.executeQuery("SELECT * FROM main_data WHERE expirationDate > NOW() + 1;");
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt(1);
String ovogNer = rs.getString(2);
String regNum = rs.getString(3);
String itemName = rs.getString(4);
String note = rs.getString(5);
int zHemjee = rs.getInt(6);
int hvv = rs.getInt(7);
int hugatsaa = rs.getInt(8);
today = rs.getDate(9);
int totalPay = rs.getInt(10);
expirationDate = rs.getDate(11);
rows++;
}
regData = new Object[rows][11];
Object[] Colheads = {"Бүртгэлийн дугаар", "Овог нэр", "Регистрийн дугаар", "Барьцаа",
"Тэмдэглэл", "Зээлийн хэмжээ", "Хүү (%)", "Хугацаа", "Огноо", "Нийт төлөх", "Дуусах хугацаа"};
rs = st.executeQuery("SELECT * FROM main_data WHERE expirationDate > NOW() + 1;");
for (int i1 = 0; i1 < rows; i1++) {
rs.next();
for (int j1 = 0; j1 < 11; j1++) {
regData[i1][j1] = rs.getString(j1 + 1);
}
}
model = new DefaultTableModel(regData, Colheads);
table = new JTable(model);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
activeDataPanel.add(jsp);
rs.close();
st.close();
conn.close();
}
And this is the method i'm using to write data into the database
public void writeDataIntoDB() throws InstantiationException, IllegalAccessException {
ResultSet rs = null;
Connection conn = null;
Statement st = null;
PreparedStatement pst = null;
final String URL = "jdbc:h2:~/registDB";
final String USER = "admin";
final String PASS = "password";
LocalDate currentDate = LocalDate.now();
String input = hugatsaaFld.getText();
long addDays = Long.parseLong(input);
expiration = currentDate.plusDays(addDays);
expirationDate = java.sql.Date.valueOf(expiration);
try {
Class.forName("org.h2.Driver").newInstance();
conn = DriverManager.getConnection(URL, USER, PASS);
String sql = "INSERT INTO main_data(ovogNer,regNum,itemName,note,zHemjee,hvv,hugatsaa,date,totalPay,expirationDate)"
+ "VALUES"
+ "(?,?,?,?,?,?,?,?,?,? )";
pst = conn.prepareStatement(sql);
pst.setString(1, getOvogNer());
pst.setString(2, getRegNum());
pst.setString(3, getItemName());
pst.setString(4, getNote());
pst.setInt(5, +getzHemjee());
pst.setInt(6, +getHvv());
pst.setLong(7, +getHugatsaa());
pst.setDate(8, java.sql.Date.valueOf(LocalDate.now()));
pst.setDouble(9, getTotalPay());
pst.setDate(10, expirationDate);
pst.executeUpdate();
pst.close();
conn.close();
} catch (SQLException se) {
JOptionPane.showMessageDialog(null, "Error: " + se);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
This question has been answered here
but it comes down to clearing and rerendering your JTable object. i.e. refresh, the post above explains it quite nicely.
Hope you get it right.
I have a function to fetch data from MySQL table
public ResultSet getAddressID(String city) throws SQLException{
String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE city =" + "\""+ city+ "\";";
ResultSet rs = executeSearch(q);
return rs;
}
When I try System.out.println(n.getAddressID("Sheffield")); it returns null. Why this happened even though there are data in my table (see picture).
public ResultSet executeSearch(String q){
openConnection();
try{
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(q);
closeConnection();
return resultSet;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
finally {
closeConnection();
return null;
}
}
The problem appears to be in your executeSearch method; the finally block will always execute, so by returning null in the finally block, you essentially override what you returned in the try block!
This could be an alternative solution; note that I'm returning at the end of the method instead of within any parts of the try-catch-finally block.
/**
* Converts a provided ResultSet into a generic List so that the
* ResultSet can be closed while the data persists.
* Source: http://stackoverflow.com/a/7507225/899126
*/
public List convertResultSetToList(ResultSet rs) throws SQLException
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List list = new ArrayList(50);
while (rs.next())
{
HashMap row = new HashMap(columns);
for(int i = 1; i <= columns; ++i)
{
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}
return list;
}
public List executeSearch(String q)
{
List toReturn;
openConnection();
try {
Statement statement = connection.createStatement();
toReturn = this.convertResultSetToList(statement.executeQuery(q));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
toReturn = new ArrayList();
}
finally {
closeConnection();
}
return toReturn;
}
The below java method sets the ResultSet data to a bean class and I am fetching the data. But, the method runHiveQuery() returns only one row that is the last record in the table. While debugging the code i found that the resultset is being looped twice as we have two records. But, while returning the bean class object there is some issue as it retrieves only one record.
Unable to find what is going wrong.
public CSPData getCSPData() throws SQLException {
try {
String drivername = "org.apache.hive.jdbc.HiveDriver";
Class.forName(drivername);
connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/");
statement = connection.createStatement();
resultset = statement.executeQuery(
"select distinct db_name as db_name,db_server_name as db_server_name,lower(db_name) as l_db_name,lower(db_server_name) as l_server_name,regexp_replace(lower(db_server_name), '-', '_') as server_name,db_server_name_secondary as db_server_name_secondary from csp.curated_input");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
while (resultset.next()) {
cspdata.setDbName(resultset.getString("db_name"));
cspdata.setDbServerName(resultset.getString("db_server_name"));
cspdata.setDbServerNameSecondary(resultset.getString("db_server_name_secondary"));
cspdata.setlDbName(resultset.getString("l_db_name"));
cspdata.setlServerName(resultset.getString("l_server_name"));
cspdata.setServerName(resultset.getString("server_name"));
}
return cspdata;
}
public void runHiveQuery() throws SQLException {
CSPData cspdata = hivedao.getCSPData();
String hive_db = "csp";
String dbname = cspdata.getDbName();
String dbservername = cspdata.getDbServerName();
String servername = cspdata.getlServerName();
String drop = "Drop table if exists " + hive_db + "." + "IB_C3_" + dbname + "_" + dbservername;
String insert = "insert into table " + hive_db + "." + "IB_export_log select " + "\'ib_c3_" + dbname + "_"
+ servername + "\' from " + hive_db + "." + "dual limit 1";
System.out.println(drop);
System.out.println(insert);
}
Your code returns the last record since it only returns a single record. You should return a List :
public List<CSPData> getCSPData() throws SQLException {
List<CSPData> result = new ArrayList<>();
try {
String drivername = "org.apache.hive.jdbc.HiveDriver";
Class.forName(drivername);
connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/");
statement = connection.createStatement();
resultset = statement.executeQuery(
"select distinct db_name as db_name,db_server_name as db_server_name,lower(db_name) as l_db_name,lower(db_server_name) as l_server_name,regexp_replace(lower(db_server_name), '-', '_') as server_name,db_server_name_secondary as db_server_name_secondary from csp.curated_input");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
while (resultset.next()) {
CSPData cspdata = new CSPData ();
cspdata.setDbName(resultset.getString("db_name"));
cspdata.setDbServerName(resultset.getString("db_server_name"));
cspdata.setDbServerNameSecondary(resultset.getString("db_server_name_secondary"));
cspdata.setlDbName(resultset.getString("l_db_name"));
cspdata.setlServerName(resultset.getString("l_server_name"));
cspdata.setServerName(resultset.getString("server_name"));
result.add(cspdata);
}
return result;
}
gurus,
I am new to Java SQL, and need some help.
I'm trying to get a parameter from MS SQL Server 2008. The data is definitely there - it is a current and valid DB, and I'm trying to use the users records to get cridentials for another application.
I asserted the following query:
String query = "SELECT [USER].qc_number FROM [USER] WHERE "[USER].login_name = '"
+ userNameInput + "' AND [USER].password = '" + passWordInput + "';";
Where userNameInput and passWordInput are received from the user. The URL, query and driver class are definitely correct: I checked the DB schema both from the application and from the server views. Furthermore, I verified all the Exceptions systems by changing parameters one by one, resulting in correct Exceptions messages. However, I get a resultSet with 1 column and 0 rows.
The code is below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class trOdbc
{// database URL
final String DB_URL = "***";
final String Class_URL = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private Connection connection = null; // manages connection
private Statement statement = null; // query statement
private ResultSet resultSet = null; // manages results
private Boolean connectedToDatabase = false;
// ----------------------------------------------------------
public void createJdbcConnection()
{ // connect to database books and query database
if (connectedToDatabase)
{ return; }
try
{ // connectedToDatabase is false - establish the connection
Class.forName(Class_URL);
connection = DriverManager.getConnection
(DB_URL, "***", "***" );
statement = connection.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
connectedToDatabase = true;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection establishment: " + ex); }
catch (ClassNotFoundException ex)
{ System.out.println ("Class not found exception in query process: " + ex); }
}
// ----------------------------------------------------------
public String [][] processJdbcQuery (String query)
{
createJdbcConnection ();
if (!connectedToDatabase)
{ return null; }// the connection wasn't established
try
{// query database
resultSet = statement.executeQuery(query);
int columns = resultSet.getMetaData().getColumnCount();
int rows = 0;
if (resultSet != null)
{
resultSet.beforeFirst();
resultSet.last();
rows = resultSet.getRow();
}
String [][] tempData = new String[rows][columns];
resultSet.beforeFirst();
rows = 0;
while (resultSet.next())
{
for (int x = 1; x <= columns; x++)
{
tempData [rows][x - 1] = resultSet.getString (x);
}
rows++;
}
CloseJdbcConnection ();
return tempData;
}
catch (SQLException ex)
{
System.out.println ("SQL Exception in query process: " + ex);
CloseJdbcConnection ();
return null;
}
} // end processJdbcQuery
// ----------------------------------------------------------
public void CloseJdbcConnection()
{
if ( connectedToDatabase )
{// close Statement and Connection. resultSet is closed automatically.
try
{
statement.close();
connection.close();
connectedToDatabase = false;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection closure: " + ex); }
} // end if
} // end method CloseJdbcConnection
} // end class trOdbc
Why don't you use Prepared Statement instead ?
Here is a good tutorial for using prepared statement in java
In your case it would be :
String query = "SELECT [USER].qc_number FROM [USER] " +
"WHERE [USER].login_name = ? AND [USER].password = ?;";
And then set it with different values each time you execute it like :
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, userNameInput);
ps.setString(2, passWordInput);
resultSet = ps.executeQuery();