Reading a table from database - glassfish

I having a problem to run below Java code. I couldn't find the DB.java class.
ResultSet rs = DB.getConnection().createStatement().executeQuery("select * from products");
while(rs.next()){
System.out.print(rs.getString("pid"));
System.out.print(rs.getString("name"));
System.out.print(rs.getString("price"));
System.out.print(rs.getString("ava_qty"));
}
I'm using Glassfish server. Can someone help me to write the DB.java class?

The getConnection() method is part of the DriverManager class. Initialize your drivermanager properly, as described in this post:
https://www.tutorialspoint.com/javaexamples/jdbc_dbconnection.htm
Example code for future reference:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
System.out.println("JDBC Class found");
int no_of_rows = 0;
try {
Connection con = DriverManager.getConnection (
"jdbc:derby://localhost:1527/testDb","username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery ("SELECT * FROM employee");
while (rs.next()) {
no_of_rows++;
}
System.out.println("There are "+ no_of_rows + " record in the table");
} catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}

Related

my javafx project doesn't read data from the database

So i created a database table in intellij and i made a javafx project and it's connected to my server(localhost)
now i'm getting errors here
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
it says I'm unable to access the table
this is the method
public boolean isLogin(String user,String pass) throws SQLException
{
PreparedStatement preparedStatement = null ;
ResultSet resultSet = null;
String query = "SELECT * FROM IntellijDB.dbo.Employee WHERE username = ? and passcode = ?";
try
{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,user);
preparedStatement.setString(2,pass);
resultSet = preparedStatement.executeQuery();
if (resultSet.next())
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
return false;
//TODO: handle exception
}
finally {
preparedStatement.close();
resultSet.close();
}
}
and the other error here
if (loginModel.isLogin(userAction.getText(), passAction.getText()))
and this line too
resultSet.close();
and I guess they are related and i don't know how to fix this
this is the other code
#FXML
public void Login(ActionEvent event) {
try {
if (loginModel.isLogin(userAction.getText(), passAction.getText())) {
isConnected.setText("Username & password is correct");
}
else
{
isConnected.setText("Check your username or password");
}
} catch (SQLException e)
{
isConnected.setText("Check your username or password");
//TODO Auto-generated catch block
e.printStackTrace();
}
}

Get INSERT string on JDBC

I’m trying to write a method to get the string from the SQL INSERT query to the DB, with an input array as the number of columns using JDBC:
public String methodtest(String ListofColumns)
{
String query = "INSERT INTO" + TableName + "(" + ListOfColumns + ")";
try
{
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
While (rs.next())
{
String result = rs.getString(query);
System.out.println("The SQL query is " + result);
}
}
catch (SQLException sqlEx)
{
e.printStackTrace();
}
finally
{
rs.close();
}
}
Can you see any mistake?
Thanks, Monkawee, for the advice.
You can use the following pattern:
public string methodtest(Array listofcolumns)
{
try{
<Connection string path>
<DB connection method>
<Query string>
<Execution>
<Reset Object>
}
catch(SQLException sqlEx){
// handle exception
}
catch(Exception ex){
// handle other exceptions if any
}
finally{
<Close connection and other resources like PreparedStatement>
}
}

ResultSet is getting closed on executing statement.execute(sql)

On executing the follwing code i am getting error java.sql.SQLException: ResultSet is closed
public class SavePoints {
public void extract(ResultSet rs)
{
int c;
try {
while(rs.next())
{
c = rs.getInt("id");
String d=rs.getString("name");
String e=rs.getString("city");
String f=rs.getString("state");
String g=rs.getString("country");
//Displaying values
System.out.println("ID is:"+c+"\tName is:"+d+"\tCity is:"+e+"\tState is:"+f+"\tCountry is:"+g);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) {
SavePoints spobj=new SavePoints();
try {
Connection con=DriverManager.getConnection("jdbc:odbc:Divya", "SYSTEM", "tiger");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from publishers");
spobj.extract(rs);
//DatabaseMetaData databaseMetaData = con.getMetaData();
//System.out.println(databaseMetaData.getDriverMajorVersion());
//Savepoint sp=con.setSavepoint("Deleting Rows");
st.execute("delete from publishers where id=104");
//con.rollback(sp);
spobj.extract(rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
What is the error? I cannot find it. Please let me know. I am a newbie.. so please explain in simple terms. I am grateful for your help. Thanks :)
you have called spobj.extract(rs); twice ,
first time when this function executes resultset moves to last because you are using rs.next()..
to achieve this you have use scrollable resultset
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
and for next call of spobj.extract(rs); reverse the call of resultset by rs.previous()

Java + Sql database data rollback is not working

In my application, I am writing data to a database.
This is the code for database writing.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class DatabaseRollback {
private static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " + "Include in your library path!");
System.out.println(e.getMessage());
e.printStackTrace();
}
System.out.println("PostgreSQL JDBC Driver Registered!");
try {
dbConnection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/MyDB","root","123");
if (dbConnection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
return dbConnection;
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
System.out.println(e.getMessage());
e.printStackTrace();
}
return dbConnection;
}
public static void main(String args[]) throws SQLException {
Connection dbConnection = null;
PreparedStatement pstmt = null;
String query = "insert into orders(orderid, execid, exectype, lastprice, lastqty, ordstatus) values(?, ?, ?, ?, ?, ?)";
try {
dbConnection = getDBConnection();
dbConnection.setAutoCommit(false);
pstmt = dbConnection.prepareStatement(query); // create a statement
pstmt.setString(1, "OrderID");
pstmt.setString(2, "Test02");
pstmt.setString(3, "exectype");
pstmt.setDouble(4, 100.00);
pstmt.setInt(5, 100);
pstmt.setString(6,"ordstatus");
pstmt.executeUpdate();
dbConnection.commit();
query.concat("error");
dbConnection.prepareStatement(query);
pstmt.setString(1, "eeeeeeeeeeeeeeeeeeeeeeee");
pstmt.executeUpdate(); // here error comes.........
} catch (Exception e) {
// e.printStackTrace();
dbConnection.rollback();
}
finally {
if (pstmt != null) {
pstmt.close();
}
if (dbConnection != null && !dbConnection.isClosed()) {
dbConnection.close();
}
}
}}
After debug point reach to the dbConnection.commit(); I have checked database and one record was inserted. But then it goes through dbConnection.rollback(); section. but it doesn't rollback inserted record. How can I implement rollback machanism?
dbConnection.commit();
should be placed at the end of your transaction.
pstmt.setString(1, "eeeeeeeeeeeeeeeeeeeeeeee");
pstmt.executeUpdate(); // here error comes.........
dbConnection.commit();
} catch (Exception e) {

ActiveMQ and JMS : Basic steps for novice

Hi all please give some basic about ActiveMQ with JMS for novice. And configuration steps also.
We are going to create a console based application using multithreading. So create an java project for console application.
Now follow these steps..........
Add javax.jms.jar, activemq-all-5.3.0.jar, log4j-1.2.15.jar to your project library.
(You can download all of above jar files from http://www.jarfinder.com/ .
create a file naming jndi.properties and paste these following texts .. ( Deatils for jndi.properties just Google it)
# START SNIPPET: jndi
java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory
# use the following property to configure the default connector
java.naming.provider.url = tcp://localhost:61616
# use the following property to specify the JNDI name the connection factory
# should appear as.
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry
# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue
# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic
# END SNIPPET: jndi
Add JMSConsumer.java
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JMSConsumer implements Runnable{
private static final Log LOG = LogFactory.getLog(JMSConsumer.class);
public void run() {
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
MessageConsumer consumer = null;
Destination destination = null;
String sourceName = null;
final int numMsgs;
sourceName= "MyQueue";
numMsgs = 1;
LOG.info("Source name is " + sourceName);
/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("queueConnectionFactory");
destination = (Destination)jndiContext.lookup(sourceName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
consumer = session.createConsumer(destination);
connection.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MessageListener listener = new MyQueueMessageListener();
consumer.setMessageListener(listener );
//Let the thread run for some time so that the Consumer has suffcient time to consume the message
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JMSException e) {
LOG.info("Exception occurred: " + e);
} finally {
if (connection != null) {
try {
connection.close();
} catch (JMSException e) {
}
}
}
}
}
Add JMSProducer.java
import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class JMSProducer implements Runnable{
private static final Log LOG = LogFactory.getLog(JMSProducer.class);
public JMSProducer() {
}
//Run method implemented to run this as a thread.
public void run(){
Context jndiContext = null;
ConnectionFactory connectionFactory = null;
Connection connection = null;
Session session = null;
Destination destination = null;
MessageProducer producer = null;
String destinationName = null;
final int numMsgs;
destinationName = "MyQueue";
numMsgs = 5;
LOG.info("Destination name is " + destinationName);
/*
* Create a JNDI API InitialContext object
*/
try {
jndiContext = new InitialContext();
} catch (NamingException e) {
LOG.info("Could not create JNDI API context: " + e.toString());
System.exit(1);
}
/*
* Look up connection factory and destination.
*/
try {
connectionFactory = (ConnectionFactory)jndiContext.lookup("queueConnectionFactory");
destination = (Destination)jndiContext.lookup(destinationName);
} catch (NamingException e) {
LOG.info("JNDI API lookup failed: " + e);
System.exit(1);
}
/*
* Create connection. Create session from connection; false means
* session is not transacted.create producer, set the text message, set the co-relation id and send the message.
*/
try {
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
TextMessage message = session.createTextMessage();
for (int i = 0; i
Add MyQueueMessageListener.java
import java.io.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.jms.*;
public class MyQueueMessageListener implements MessageListener {
private static final Log LOG = LogFactory.getLog(MyQueueMessageListener.class);
/**
*
*/
public MyQueueMessageListener() {
// TODO Auto-generated constructor stub
}
/** (non-Javadoc)
* #see javax.jms.MessageListener#onMessage(javax.jms.Message)
* This is called on receving of a text message.
*/
public void onMessage(Message arg0) {
LOG.info("onMessage() called!");
if(arg0 instanceof TextMessage){
try {
//Print it out
System.out.println("Recieved message in listener: " + ((TextMessage)arg0).getText());
System.out.println("Co-Rel Id: " + ((TextMessage)arg0).getJMSCorrelationID());
try {
//Log it to a file
BufferedWriter outFile = new BufferedWriter(new FileWriter("MyQueueConsumer.txt"));
outFile.write("Recieved message in listener: " + ((TextMessage)arg0).getText());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
System.out.println("~~~~Listener : Error in message format~~~~");
}
}
}
Add SimpleApp.java
public class SimpleApp {
//Run the producer first, then the consumer
public static void main(String[] args) throws Exception {
runInNewthread(new JMSProducer());
runInNewthread(new JMSConsumer());
}
public static void runInNewthread(Runnable runnable) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(false);
brokerThread.start();
}
}
Now run SimpleApp.java class.
All da best. Happy coding.
Here it is a simple junit test for ActiveMQ and Apache Camel. This two technologies works very good together.
If you want more details about the code, you can find a post in my blog:
http://ignaciosuay.com/unit-testing-active-mq/
public class ActiveMQTest extends CamelTestSupport {
#Override
protected CamelContext createCamelContext() throws Exception {
CamelContext camelContext = super.createCamelContext();
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
camelContext.addComponent("activemq", jmsComponentClientAcknowledge(connectionFactory));
return camelContext;
}
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from("mina:tcp://localhost:6666?textline=true&sync=false")
.to("activemq:processHL7");
from("activemq:processHL7")
.to("mock:end");
}
};
}
#Test
public void testSendHL7Message() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:end");
String m = "MSH|^~\\&|hl7Integration|hl7Integration|||||ADT^A01|||2.5|\r" +
"EVN|A01|20130617154644\r" +
"PID|1|465 306 5961||407623|Wood^Patrick^^^MR||19700101|1|\r" +
"PV1|1||Location||||||||||||||||261938_6_201306171546|||||||||||||||||||||||||20130617134644|";
mock.expectedBodiesReceived(m);
template.sendBody("mina:tcp://localhost:6666?textline=true&sync=false", m);
mock.assertIsSatisfied();
}