Accessing berkeley db from another class in Java - java

I created a database in one of my java class files and was wondering how to access/open that database in another java class file to read through the data. I tried using openDatabase but how does it know the location of the database file? I've searched through many forums and all I could find is having the code in the same class and just accessing the database object.
ex.I created a database at the directory /documents/ in one of my java class files and all my java code is somewhere else. How do I access and use that database in my other source code?
Edit:
public static void main(String[] args) {
try {
EnvironmentConfig environmentConfig=new EnvironmentConfig();
environmentConfig.setAllowCreate(true);
Environment environment=new Environment(new File("user/documents/"),environmentConfig);
DatabaseConfig databaseConfig=new DatabaseConfig();
databaseConfig.setAllowCreate(true);
Database db=environment.openDatabase(null,"mytable",databaseConfig);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
I tried the following and I keep getting this error when compiling.
openDatabase(com.sleepycat.db.Transaction,java.lang.String,java.lang.String,com.sleepycat.db.DatabaseConfig) in com.sleepycat.db.Environment cannot be applied to (<nulltype>,java.lang.String,com.sleepycat.db.DatabaseConfig)
Database db=environment.openDatabase(null,key,databaseConfig);
^
1 error

Yeah since it is related to mysql database , that means you have to have a password and username as it is a secure school system , and you can use mysql connector to access the data you created .
To be more clear you have to have database.java file .
then in that file the main thing to know is the constructor and way to go ...
import java.sql.*;
public class database
{
public static database bDatabase = null;
protected String connection_url = "";
protected String _name = "";
protected String name = "";
protected String user = "";
protected String password = "";
protected Class some_class = null;
protected Connection connection = null;
protected ResultSet results = null;
protected String current_table = "";
protected Boolean error = false;
public database(String name, String user, String password)
{
this(name, user, password, "jdbc:mysql://localhost:3306", "com.mysql.jdbc.ClassName");
}
public database(String name, String user, String password, String connection_url, String any_name)
{
this.name = name;
this.user = user;
this.password = password;
this.connection_url = connection_url;
this._name = any_name;
}
public static void openDatabase()
{
try
{
bDatabase = new database("dbname", "user_id",
"password", "jdbc:mysql://host",
"com.mysql.jdbc.Anyclass");
bDatabase.open();
}
catch (Exception ex)
{
throw new InvalidQueryException("Unable to open database ");
}
}

Related

Java Return Null When Tried to Get Method

first of all I know this is duplicated question. But I've search and tried from stackoverflow listed on Google to quora but still cant resolve my Get method still return null.
This is my class loginModel.java under package com.hello.model
public class loginModel {
public String username;
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
}
This is my loginView.java under package com.hello.view
import com.hello.model.loginModel;
public class loginView extends javax.swing.JFrame {
loginModel login = new loginModel();
public loginView() {
initComponents();
this.setLocationRelativeTo(null);
loginFunction();
}
private void loginFunction(){
String username = usernameText.getText();
String password = passwdText.getText();
String query = "select * from access where username = '" +username+ "' AND password = '" +password+"'";
databaseConnect db = new databaseConnect();
try (Connection con = DriverManager.getConnection(db.url, db.user, db.password);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
if(rs.next()) {
if(username.equals(rs.getString("username")) && password.equals(rs.getString("password"))){
JOptionPane.showMessageDialog(null, "login Success");
String name = rs.getString("name");
String privilege = rs.getString("privilege");
login.setUsername(name);
menu = new menuView();
menu.setVisible(true);
this.setVisible(false);
}
} else {
JOptionPane.showMessageDialog(null, "username or password incorrect");
}
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want call my username from menuView.java under package com.hello.view after login success
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
}
As per my question when I call Get method from loginModel, messagebox return null.
I've tried:
Put system.out.println directly in loginModel.java, value return
and call system.out.println in menuView.java at the same time but value return null. How?
Send string between jframe with menu = menuView(username) in loginView.java and retrieve in menuView.java, value return null
Using no model and create set string in loginView and call it in
menuView, value return null
I need values that I want to use in another class/package/jframe. Am I doing wrong?
I am not well versed in Swing but I can see the problem, just not the exact solution.
Your code creates an instance of loginModel in both the menuView and in loginView. Then in loginView is sets the name in the instance it has, in in menuView it gets the name from its own instance.
You need to create a single instance of the model and share it between the two views.
In a pojo way I would pass the loginModel to both "views" in a constructor.
menu = new menuView(login);
And in menuView
public menuView(loginModel login) {
this.login = login;
}
Your menuView instance isn't using the loginModel class that you instantiate in loginView, it's using the new one you created using new menuView() when you initialized the login variable in the menuView class. You just need to add a setter method for the loginModel attribute in the menuView class like this:
import com.hello.model.loginModel;
import com.hello.view.loginView;
public class menuView extends javax.swing.JFrame {
private String username;
loginModel login = new loginModel();
public menuView() {
initComponents();
this.setLocationRelativeTo(null);
initMenu();
}
private void initMenu(){
username = login.getUsername();
JOptionPane.showMessageDialog(this, username);
}
public void setLogin(loginModel loginModel) {
this.login = loginModel;
}
}
Then call the setter in loginView.loginFunction like this:
... code before
login.setUsername(name);
menu = new menuView();
menu.setLogin(login);
menu.setVisible(true);
this.setVisible(false);
... code after
Notice the only changes to your code are the added setLogin method on the menuView class and the call to menu.setLogin(login) in loginView.loginFunction.
You need to think in stages/steps. Login is a single step, it has one of two outcomes, success or failure.
Your app needs to perform this step and take appropriate action based on the outcome of the result.
You also need to think about "separation of responsibility" - in this case, it's not really the responsibility of the loginView to perform the login operation, it just coordinates the user input.
The responsibility actually falls to the LoginModel
// Just a custom exception to make it easier to determine
// what actually went wrong
public class LoginException extends Exception {
public LoginException(String message) {
super(message);
}
}
// LoginModel ... that "does" stuff
public class LoginModel {
private String username;
DatabaseConnect db;
public LoginModel(DatabaseConnect db) {
this.db = db;
}
// I would consider not doing this. You need to ask what reasons would
// the app need this information and expose it only if there is really a
// reason to do so
public String getUsername() {
return username;
}
public boolean isLogedIn() {
return username != null;
}
public void validate(String username, String password) throws SQLException, LoginException {
String query = "select * from access where username = ? AND password = ?";
try ( Connection con = DriverManager.getConnection(db.url, db.user, db.password); PreparedStatement st = con.prepareStatement(query)) {
st.setString(1, username);
st.setString(2, password);
try ( ResultSet rs = st.executeQuery()) {
if (rs.next()) {
this.username = username;
} else {
throw new LoginException("Invalid user credentials");
}
}
}
}
}
This is an overly simplified example, as the actual responsibility for performing the login should fall to the controller, which would then generate the model, but I'm getting ahead of myself.
Because the flow of the app shouldn't be controlled/determined by the login view, the LoginView should itself be a dialog. This way, it can be shown when you need it, it can perform what ever operations it needs and then go away, leaving the rest of the decision making up to who ever called it
public class LoginView extends javax.swing.JDialog {
private LoginModel model;
public LoginView(LoginModel model) {
initComponents();
setModal(true);
this.model = model;
this.setLocationRelativeTo(null);
}
// This will get executed when the user taps some kind of "perform login button"
private void loginFunction() {
String username = usernameText.getText();
String password = passwdText.getText();
try {
model.validate(username, password);
dispose()
} catch (SQLException ex) {
// This should probably be considered a fatal error
model = null;
dispose();
} catch (LoginException ex) {
JOptionPane.showMessageDialog(this, "Login vaild");
}
}
}
This then means you might put it together something like this...
DatabaseConnect db = new DatabaseConnect();
LoginModel model = new LoginModel(db);
LoginView loginView = new LoginView(model);
// Because we're using a modal dialog, the code execution will wait here
// till the window is disposed/closed
loginView.setVisible(true);
if (loginView.model != null) {
// model is now valid and can continue to be used
// in what ever fashion you need
} else {
JOptionPane.showMessageDialog(null, "Fatal Error");
}
This takes you a step closer to a more decoupled solution, where you feed information to the classes when they need it, rather than the classes making decisions about what they should create/use.
It also moves you a step closer to re-usable classes, as they do their specific job and nothing more.
You might find taking the time to read up on "model-view-controller" will help you better understand this approach

Rest API returns an empty list when connecting to database using JDBC ignoring the data brought from the database

Im doing a project on my own and the point of the project is to make an a rest API in java and bring data from database using JDBC. The problem is when i make the connection and retrieve the data using main method everything works fine but when i try to retrieve the data through a get request, it returns an empty list. This is the endpoint
#Path("/users")
public class UserResource {
UserService userService = new UserService();
#GET
#Path("/all")
#Produces(MediaType.APPLICATION_JSON)
public Response getAllUsers() throws InterruptedException {
List<User> users = userService.getAllUsers();
GenericEntity<List<User>> wrapper = new GenericEntity<List<User>>(users) {
};
return Response.ok(wrapper).build();
}
}
And this is the class that connects to database using JDBC
public class ConnectionJDBC {
private static String USERNAME = "root";
private static String PASSWORD = "root";
private static String CONSTRING = "jdbc:mysql://localhost:3306/";
private static String DATABASE = "users_db";
static Connection connection;
public ConnectionJDBC() {
}
public static Connection getConnectionToDB() {
try {
String url = CONSTRING + DATABASE;
connection = DriverManager.getConnection(url, USERNAME, PASSWORD);
if (connection != null) {
System.out.println("Connected");
} else {
System.out.println("Connection faild");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Something went wrong before establishing the connection");
}
return connection;
}
public List<User> getUsers() {
connection = getConnectionToDB();
String query = "SELECT * FROM users_db.user_info;";
List<User> userListRetrived = new ArrayList<>();
try {
PreparedStatement statement = connection.prepareStatement(query);
ResultSet dataRetrieved = statement.executeQuery();
while (dataRetrieved.next()) {
User user = new User(dataRetrieved.getInt("id"),
dataRetrieved.getString(2),
dataRetrieved.getString(3));
userListRetrived.add(user);
return userListRetrived;
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("Something went wrong when retriving the data");
}
return userListRetrived;
}
}
UserService class is here
public class UserService {
private ConnectionJDBC connectionJDBC = new ConnectionJDBC();
public UserService() {
}
public List<User> getAllUsers() {
ConnectionJDBC connectionJDBC = new ConnectionJDBC();
List<User> usersList = connectionJDBC.getUsers();
return usersList;
}
}
The user class is a normal java bean. It feels like getUsers method is ignoring bringing the data from the database and instead it returns the instantiated empty list instead. I'm using jersey and deploying the project on Glassfish.
Any clues on how i can fix that or explanation for this situation?
Many thanks in advance!
You didn't invoke userService.getUsers() method from userResource() class. Please update your code in userResource() class as follows
GenericEntity<List<User>> wrapper = new GenericEntity<List<User>>(userService.getUsers());

Getting values from Get and Set methods using separate classes [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 8 years ago.
Improve this question
I am new to Java:
I have the following program that connects to different databases using an Enum to call the different database connection.
I need to put the credentials, username and password in a class by itself but I am not sure because they are both initialized using get and set and the only way I can get this to work is called them both in the same method.
First I have this class which initializes the connection strings and data elements.
class DatabaseUtility {
private String USERNAME;
private String PASSWORD;
private String HSQLDB;
private String MYSQL;
public DatabaseUtility() {
USERNAME = null;
PASSWORD = null;
HSQLDB = null;
MYSQL = null;
}
public String getUsername() {
return USERNAME;
}
public void setUsername(String username) {
USERNAME = username;
}
public String getPassword() {
return PASSWORD;
}
public void setPassword(String password) {
PASSWORD = password;
}
public String getHsdbConn() {
return HSQLDB;
}
public void setHsdb(String hsdbConnection) {
HSQLDB = hsdbConnection;
}
public String getMySqlConn() {
return MYSQL;
}
public void setMySqlConn(String mySqlConnection) {
MYSQL = mySqlConnection;
}
}
Next I have an enum use to call both db types:
public enum DBType {
HSQLDB, MYSQL
}
Next I have a method which uses a switch statement to assign the different db connection based on the user preference in the main method.
*This is the focus of my post, I have to call both the get and set methods in here, I would rather not set the credentials in the same method but not sure how to separate the two.
import java.sql.*;
class DatabaseConnectivity {
DatabaseUtility dbUtil = new DatabaseUtility();
public Connection getConnection(DBType dbType) throws SQLException {
dbUtil.setHsdb("jdbc:hsqldb:data/explorecalifornia");
dbUtil.setMySqlConn("jdbc:mysql://jsa/explorecalifornia");
dbUtil.setUsername("dbuser");
dbUtil.setPassword("dbpassword");
switch (dbType) {
case MYSQL:
return DriverManager.getConnection(dbUtil.getMySqlConn(),
dbUtil.getUsername(), dbUtil.getPassword());
case HSQLDB:
return DriverManager.getConnection(dbUtil.getHsdbConn(),
dbUtil.getUsername(), dbUtil.getPassword());
default:
return null;
}
}
}
Finally, here is the main class, notice the DBType enum called in the try catch block.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MultiDatabaseConnectionMain {
public static void main(String[] args) throws SQLException {
DatabaseConnectivity databaseConnectivity = new DatabaseConnectivity();
Connection connection = null;
Statement statement = null;
ResultSet resultset = null;
try {
connection = databaseConnectivity.getConnection(DBType.MYSQL);
System.out.println("Connected");
System.out.println();
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
resultset = statement.executeQuery("SELECT * FROM states");
resultset.last();
System.out.println("Number of rows: " + resultset.getRow());
} catch (SQLException e) {
System.err.println(e);
} finally {
if (resultset != null) {
resultset.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
}
}
I am not 100% sure, but I think what you are asking is that you have to call dbUtil.set* and dbUtil.get* in the same method.
What I would suggest is that you create enum with db properties so whatever dbType passed to the argument you can just call getters on them. You can define your enum as below.
public enum DBType {
//ser properties you want for db. url, username are just dummy values
HSQLDB("url", "username", "password"), MYSQL("url", "username", "password");
private String url;
private String username;
private String password;
private DBType(String url, String username, String password){
this.url = url;
//set other properties
}
public String getUrl(){
return this.url;
}
//getter for all the other values
}
and in DatabaseConnectivity's getConnection method will be
public Connection getConnection(DBType dbType) throws SQLException {
return DriverManager.getConnection(dbType.getUrl(),
dbType.getUsername(), dbType.getPasword());
}
You can provide credentials in the constructor of class DatabaseConnectivity and then use them to set values in the instance of DatabaseUtility.
class DatabaseConnectivity {
DatabaseUtility dbUtil;
public DatabaseConnectivity (String userName, String password) {
dbUtil = new DatabaseUtility();
dbUtil.setUsername(userName)
dbUtil.setPassword(password);
}
......

why can't java see my mysql driver

I'm having trouble working out why java can't see my mysql driver:
I've downloaded the driver .jar from the mysql website
I've added the jar to my runtime classpath
I can confirm the jar is on the classpath, by printing out the relevant system property
But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?
class example:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
My main class simply passes the query into the DB class:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}
You've a typo in the driver class name.
private String driverClassName = "com.myqsl.jdbc.Driver";
it should be
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?

preparedstatement with sql query referencing multiple tables

So I am trying to find an example online about creating a preparedStatement that has an sql query referencing multiple tables.
For e.g. The examples I've encountered so far are always
e.g.
s = conn.prepareStatement ("DELETE FROM Users WHERE id_user = ?");
s.setInt (1, 2);
where there is only one table involved, and the method exists in the same class of the database table. E.g. User.class , user table in database.
The query that I have requires me to set the place holder from another table/class. In this case, my method exists in the User.class, however, it requires a the binding from a Group object.
SELECT DISTINCT *
FROM usuarios
WHERE NOT EXISTS
(SELECT * FROM usuarios_grupos
WHERE usuarios_grupos.id_grupo = ?
AND usuarios_grupos.id_usuario = usuarios.id_usuario);
Will the method be the following:
public List<Usuarious> list(Grupos groups) throws DAOExceptions {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Usuarious> users = new ArrayList<Usuarious>();
try {
connection = daoFactory.getConnection();
preparedStatement = connection.prepareStatement(SQL_LIST_ALL);
preparedStatement.setInt(1, groups.getId_grupo());
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
users.add(mapUser(resultSet));
}
} catch (SQLException e) {
throw new DAOExceptions(e);
} finally {
close(connection, preparedStatement, resultSet);
}
return users;
}
or will it be written differently?? because I seem to be getting a NPE with this, and from the examples I've seen online. The query always reference 1 table. Is what I'm doing here wrong?
okay here is my method for groups.getId_grupo(), which exists in my Group.class:
public class Grupos {
Integer id_grupo;
String descricao;
public Grupos() {
}
public Grupos(Integer id_grupo, String descricao) {
this.id_grupo = id_grupo;
this.descricao = descricao;
}
public Grupos(Integer id_grupo) {
this.id_grupo = id_grupo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Integer getId_grupo() {
return id_grupo;
}
public void setId_grupo(Integer id_grupo) {
this.id_grupo = id_grupo;
}
}
I am calling my List list(Grupos groups) method in my ManagedBean
public class UsuariousGruposBean implements Serializable {
private Usuarious user = new Usuarious();
private Grupos grps = new Grupos();
private UsuariousGrupos userGroups = new UsuariousGrupos();
protected final UsuariousDAO userDAO = daoFactory.getUserDAO();
protected final GruposDAO grpDAO = daoFactory.getGruposDAO();
protected final UsuariousGruposDAO userGrpDAO = daoFactory.getUsuariousGruposDAO();
private List<Usuarious> listOfUsuarios;
private List<Grupos> listOfGrps;
private List<UsuariousGrupos> listOfUserGroups;
public UsuariousGruposBean() {
}
public List<Usuarious> getListOfUsuarios() throws DAOExceptions {
List<Usuarious> usuariosList = userDAO.list(grps);
listOfUsuarios = usuariosList;
return listOfUsuarios;
}
First instance in your code can throw NPE is at:
preparedStatement = connection.prepareStatement(SQL_LIST_ALL);
if your connection is null, your connection factory didnt return you one, check if you have a valid connection
Second place :
groups.getId_grupo()
Check if your groups is null or not
If these are not the reasons then please post your stacktrace.
The stack trace of your NPE should help tell you where the issue is (line #, etc.). From what I can tell, your SQL and the way you are calling it is all valid.
Is it possible that you're receiving a null groups parameter, such that calling groups.getId_grupo() is throwing the NPE?

Categories