I'm making book store and so far i only have 3 tables.
Book:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null
Cart:
-id:(int) primary key, autoincrement, not null
and
Article:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null,
- cart_id:(int) foreign key referencing cart
For me it's logical when user clicks on "add to cart" button to check if cart already exist, if exist i will return that cart if not create new. And user will put multiple articles in one cart. This is my class for inserting Cart in db:
public class CartDAO {
private static DataSource dataSource;
private static int autoIncKey = -1;
public static void insertCart() {
Connection conn = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("jdbc/NemkeDB");
conn = dataSource.getConnection();
String insert = "insert into cart() values()";
PreparedStatement ps = conn.prepareStatement(insert, RETURN_GENERATED_KEYS);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} catch(Exception e){
System.err.println(e);
}
In CartDAO i want to have that check, something like this:
if(cart == null){
'insert into cart()values()'
}else{ // if cart exist i want to return that cart id}
i don't know how to do that with GeneratedKeys.
Below is the class where i'm passing the id from cart in ArticleDAO
public class ArticleDAO {
private static DataSource dataSource;
private static ArrayList<Article> articleList = new ArrayList<>();
public static void insertArticle(String title, double price) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("jdbc/NemkeDB");
conn = dataSource.getConnection();
st = conn.createStatement();
CartDAO.insertCart(); // Here is where i call(insert) Cart
String insert = "insert into article(title,price,cart_id) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(insert);
ps.setString(1, title);
ps.setDouble(2, price);;
ps.setInt(3, CartDAO.getAutoIncKey()); // Here i pass that id
ps.executeUpdate();
rs = st.executeQuery("select * from artical");
while (rs.next()) {
String articalTitle = rs.getString("title");
double articalPrice = rs.getDouble("price");
Artical artical = new Artical(articalTitle, articalPrice);
articalList.add(artical);
}
} catch (Exception e) {
System.err.println(e);
}
My question is what is the proper way to make that check? Maybe with session? And how to return id if cart exist? I know it's a long question but i think it's easy for anyone with any working experience with java. Thanks everyone who invested time to read and reply this problem.
Related
I'm having an issue with getting the value of stored ArrayList<String> as VARCHAR[] in the database.
Somehow, when I'm debugging, I can see that the value returning from the database is:
I am expecting to store an ArrayList<String> by converting it to VARCHAR[] and when reading from the DB I expect to convert VARCHAR[] to ArrayList<String>
Code:
public Message<ArrayList<String>> getPlayersInSession(Object data) throws SQLException, ClassNotFoundException {
String sessionCode = (String) data;
Session session = PostgreSQLJDBC.sessionJDBCInstance().getSession(sessionCode);
//session.getPlayers() is the problem I have
return new Message<>(Message.RequestCode.RECEIVE_PLAYERS_IN_SESSION, session.getPlayers());
(Message.RequestCode.RECEIVE_PLAYERS_IN_SESSION, players);
}
public class Session {
private int _id;
private String _code;
private ArrayList<String> _players;
private ArrayList<Pair<String, String>> _leaderboard;
public Session() {
_code = "";
_players = new ArrayList<>();
_leaderboard = new ArrayList<>();
}
...
}
public class SessionJDBC implements SessionSQL {
private final Connection _connection;
public SessionJDBC(String url, String user, String password) throws ClassNotFoundException, SQLException {
Class.forName("org.postgresql.Driver");
_connection = DriverManager.getConnection(url, user, password);
if (!sessionTableExists()) createTable();
}
#Override
public void createTable() throws SQLException {
String sql = "CREATE TABLE session(" +
"id SERIAL PRIMARY KEY," +
"code VARCHAR," +
"players VARCHAR[]," +
"leaderboard VARCHAR[]" +
")";
PreparedStatement ps = _connection.prepareStatement(sql);
ps.executeUpdate();
}
#Override
public void addSession(Session session) throws SQLException {
String sql = "INSERT INTO session(code, players, leaderboard)"
+ "VALUES (?,?,?)";
PreparedStatement ps = _connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, session.getCode());
ps.setArray(2, _connection.createArrayOf("VARCHAR", session.getPlayers().toArray()));
ps.setArray(3, _connection.createArrayOf("VARCHAR", session.getLeaderboard().toArray()));
ps.executeUpdate();
ResultSet generatedKeys = ps.getGeneratedKeys();
if (generatedKeys.next()) {
session.setId(generatedKeys.getInt(1));
}
}
#Override
public void removeSession(Session session) throws SQLException {
String sql = "DELETE FROM session WHERE id = ?";
PreparedStatement ps = _connection.prepareStatement(sql);
ps.setInt(1, session.getId());
ps.executeUpdate();
}
#Override
public Session getSession(String code) throws SQLException {
return getAllSessions().stream().filter(session -> session.getCode().equals(code)).findFirst().orElse(null);
}
#Override
public ArrayList<Session> getAllSessions() throws SQLException {
ArrayList<Session> array = new ArrayList<>();
ResultSet result = _connection.prepareStatement("SELECT * FROM session").executeQuery();
while (result.next()) {
Session session = new Session();
session.setCode(result.getString("code"));
session.setId(result.getInt("id"));
session.setPlayers(new ArrayList(Collections.singletonList(result.getArray("players"))));
session.setLeaderboard(new ArrayList(Collections.singletonList(result.getArray("leaderboard"))));
array.add(session);
}
result.close();
return array;
}
#Override
public boolean sessionTableExists() throws SQLException {
DatabaseMetaData dbm = _connection.getMetaData();
ResultSet tables = dbm.getTables(null, null, "session", null);
return tables.next();
}
}
I don't know how the code example compiles given that the ArrayList shown in the debugger is actually of type ArrayList<PgArray> rather than ArrayList<String>.
The problem is occurring in these lines:
session.setPlayers(new ArrayList(Collections.singletonList(result.getArray("players"))));
session.setLeaderboard(new ArrayList(Collections.singletonList(result.getArray("leaderboard"))));
For a start result.getArray("players") is returning a java.sql.Array object, more specifically a PgArray implementation. To get the real underlying data you need to do:
(String[])result.getArray("players").getArray();
The next problem is that you are using Collections.singletonList(). What this does is produce an ArrayList with only one element. Instead what you should use is Arrays.asList. Full solution:
session.setPlayers(new ArrayList(Arrays.asList((String[])result.getArray("players").getArray)));
session.setLeaderboard(new ArrayList(Arrays.asList((String[])result.getArray("leaderboard").getArray)));
Another thing that is interesting about this code is that you are selecting all rows from the table and then filtering in memory by streaming over the results. Why not select on the code field in an SQL query?
Hello I want to populate a table from database but I have some difficult to do since I am newbie in java programming
here is the Users.java where the method getData(select) is implemented:
#Override
public Users getData(Users u) throws Exception {
Connection con = null;
Users user = null;
ResultSet rs = null;
PreparedStatement ps = null;
try{
con = getConnection();
String sql = "SELECT * FROM USERS";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
user = new Users();
user.setFirstName(rs.getString("First_NAME"));
user.setLastName(rs.getString("LAST_NAME"));
user.setAge(rs.getInt("AGE"));
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}finally{
rs.close();
ps.close();
closeConnection(con);
}
return user;
}
Well the data is stored in Users object now and I want to display it on a jTable which is located in patientJframe file can you tell me how to do that?
I created a method on patientJframe but I dont know what to do Im stuck onhere.
PatientJframe :
public void PopulatejTable(){
try {
Users u = null;
Users user = UsersDB.getInstance().getData(u);
if(user== null){
DefaultTableModel dtm = (DefaultTableModel)jTable.getModel();
dtm.setRowCount(0);
Vector vector = new Vector();
vector.add(user.getCin());
vector.add(user.getLastName());
vector.add(user.getFirstName());
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The method it is correct ? please can you help me ?
I am connecting my Java Program to a database stored in the program folder, and I am having users answer quiz questions and I want the results to be stored in the database. The Update statement is not working, and I don't know if it's a problem with the actual statement or the database connection.
I've tried creating a new database with the same tables and reconnecting to that database, but nothing seems to be working.
//database connection class
public class databaseConnection {
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager
.getConnection("jdbc:sqlite:D:\\Users\\mariammahmoud\\eclipse-workspace\\ia_2019_final\\testjava.db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
public class student {
public static final String DB_NAME = "testjava.db";
public static final String TABLE_STUDENTS = "students";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_GRADE = "grade";
public static final String COLUMN_RESULTS = "results";
public static final String COLUMN_EVENTS = "events";
public static final String COLUMN_USERNAME = "username";
public void main() {
try {
String user_name = login_student.sendQuiz();
Connection conn = databaseConnection.dbConnector();
ArrayList<String> results = new ArrayList<String>(15);
instructions();
questions(results);
results.trimToSize();
System.out.println("Here are the events that you should consider competing in:");
System.out.println(results);
String separator = ",";
int total = results.size() * separator.length();
for (String finalResults : results) {
total += finalResults.length();
}
StringBuilder sb = new StringBuilder(total);
for (String finalResults : results) {
sb.append(separator).append(finalResults);
}
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = " +user_name;
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Something went wrong:" + e.getMessage());
e.printStackTrace();
}
}
I expected the update statement to update the testjava.db database, but everything is staying the same. What should I do? Thank you in advance!
Your problem is that while you wisely used a prepared statement in your code for the update, you never actually used it for the username column in the WHERE clause. Hence, the query you are executing currently won't be interpreted as comparing some input against username. Rather, the username value will be interpreted as a column. Try this version:
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = ?";
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.setString(2, user_name);
myStmt.executeUpdate();
Note that you could have just tried the following:
String sql = "UPDATE students SET events = ? WHERE username = '" + user_name + "'";
But, please bind a value to a ? placeholder instead, as I have suggested above. One benefit of using statements is that it frees you from having to worry about how to escape your data in the query.
I have a login servlet where I have a login query in my post method from the query I am getting username, password, company name and ID
I am storing all this values in a variable like
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String companyDB,nameDB,idDB;
try {
con = DBConnection.createConnection();
statement = con.createStatement();
String sql = " SELECT MT_USERS.MT_USERS_VCLOGINCODE AS USERID, MT_USERS.MT_USERS_VCUSERPASSWORD AS PASSWORDID, MT_USERS.MT_USERS_VCUSERNAME AS NAME, (SELECT MT_DISTRIBUTR_VCDISTRIBUTRNAME FROM MT_DISTRIBUTR WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS COMPANYNAME ,(SELECT mt_distributr_vcdistributrcode FROM mt_distributr WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS ID FROM MT_USERS WHERE MT_USERS_VCLOGINCODE='admin' AND MT_USERS_VCUSERPASSWORD ='admin'";
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
companyDB = resultSet.getString("COMPANYNAME");
nameDB = resultSet.getString("name");
idDB = resultset.getString("ID");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Now I have an another class where I am writing a query and in that query I want to use idDB like
My new class is
public class Outlet {
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
public List<String> getoutlet() throws ClassNotFoundException, SQLException {
List<String> list = new ArrayList<String>();
con = DBConnection.createConnection();
statement = con.createStatement();
try {
ResultSet resultSet = statement.executeQuery("select * from ecustomer where CUSTOMERIDENTIFIER in(select CUSTOMERIDENTIFIER from mt_distributrol where mt_distributr_vcdistributrcode = 'AAAA'");
while (resultSet.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
Where mt_distributr_vcdistributrcode = 'AAAA'" at the place of 'AAAA' I have to pass a variable which has the value of idDB
You may use a prepared statement here:
String sql = "SELECT CUSTOMERDESCRIPTOR FROM ecustomer WHERE CUSTOMERIDENTIFIER IN (";
sql += "SELECT CUSTOMERIDENTIFIER FROM mt_distributrol ";
sql += "WHERE mt_distributr_vcdistributrcode = ?)");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "AAAA");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
I actually find that MkYong does a good job of explaining prepared statements in Java, see here, but any good documentation is a good place to start looking. And see Oracle Tutorial.
I would like to implement a method which would prevent the user to create an exisiting account where the name and email have already been used
try{
String query="Insert into users(name,email,password)values(?,?,?)";
pst=conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pst.setString(1,nam.getText());
pst.setString(2,emal.getText());
pst.setString(3,pass.getText());
int affectedrows=pst.executeUpdate();
rs=pst.getGeneratedKeys();
if(rs.next()){
int id = rs.getInt(1);
JOptionPane.showMessageDialog(null, "Your account has been registerd");
dispose();
new Landing_Page(id);
}
else{
JOptionPane.showMessageDialog(null,"Account already exists");
}
}
catch(Exception e ){
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
the best way is to select query both email and name from the database and if the resultSet of the queries were empty then insert into the table.
imagine you have a table in your database as below:
CREATE TABLE `stackoverflow`.`users` (
`id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL,
`email` VARCHAR(45) NULL,
`password` VARCHAR(45) NULL,
PRIMARY KEY (`id`));
now the code below first selects from the database the name and email that were set as the argument in this method and then if the values where empty(checks it with resultSet method next()) starts inserting into the table:
public static void insertUser(String name,String email,String pass)
{
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String queryName = "select * from users where name = ?";
String queryEmail = "select * from users where email = ?";
boolean nameExists = false;
boolean emailExists = false;
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/stackoverflow", "root", "red devils11");
ps = conn.prepareStatement(queryName);
ps.setString(1, name);
rs = ps.executeQuery();
nameExists = rs.next();
ps = conn.prepareStatement(queryEmail);
ps.setString(1, email);
rs.close();
rs = ps.executeQuery();
emailExists = rs.next();
if(!nameExists && !emailExists)
{
String insertUser = "insert into users(name,email,password) values(?,?,?)";
ps = conn.prepareStatement(insertUser);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
ps.execute();
}
else
{
System.out.println("user or email is already in the database");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
rs.close();
ps.cancel();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}//insertUser
remember to add jconnector for mysql to the jre library of your
project or you won't even get connected https://dev.mysql.com/downloads/connector/j/