How to retrieve row in DB Table just added now in Java - java

Table
id int(11) No auto_increment Change Drop Primary Index Unique Fulltext
email varchar(45) latin1_swedish_ci No Change Drop Primary Index Unique Fulltext
billpayment tinyint(1) No Change Drop Primary Index Unique Fulltext
dispatch tinyint(1) No Change Drop Primary Index Unique Fulltext
address varchar(75) latin1_swedish_ci Yes NULL Change Drop Primary Index Unique Fulltext
phone int(11) Yes NULL Change Drop Primary Index Unique Fulltext
created_at datetime No Change Drop Primary Index Unique Fulltext
totalbillamount float Yes NULL Change Drop Primary Index Unique Fulltext
Java Code:
sql = "insert into session_shopping (email,billpayment,dispatch,address,phone,created_at,totalbillamount) values(?,?,?,?,?,?,?)";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, email);
ps.setBoolean(2, false);
ps.setBoolean(3, false);
ps.setString(4, "");
ps.setInt(5, 0);
java.util.Date date = new java.util.Date();
long t = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(t);
ps.setDate(6, sqlDate);
ps.setFloat(7, 00.0f);
int newId = ps.executeUpdate();
System.out.println("newId" + newId);
if (newId == 1) {
sql = "select * from session_shopping where id = ?";
ps = (PreparedStatement) con.prepareStatement(sql);
ps.setInt(1, newId);
ResultSet reS = ps.executeQuery();
Session s = new Session();
s.setId(reS.getInt("id"));
s.setEmail(reS.getString("email"));
System.out.println("retreived");
return s;
} else {
System.out.println("unable to save");
}
This code fails because int newId is boolean
What i want to do is. I want to retrieve the row which i added just now.

executeUpdate will return the number of rows affected, not the current row .
Try this
ResultSet rs = aStatement.executeQuery("SELECT LAST_INSERT_ID()");
while(rs.next())
{
key = rs.getInt(1);
}

The value returned by executeUpdate has nothing to do with your ID.
Before we go to getting your ID, you can start off by setting email in the Session from your email variable rather than pulling it back out of the database.
As things stand, the only way I can think of to get the newly inserted ID is by changing your SQL thus:
sql = "select max(id) from session_shopping";
This will give you problems if you get another insert before you pick out the maximum ID though. To prevent that, put the select in the same transaction as your insert.

Related

change data in SQL

I´ve created a table in SQL.
CREATE TABLE IF NOT EXISTS data (
id int NOT NULL AUTO_INCREMENT,
Username String,
Countdown double,
PRIMARY KEY(id)
)
Now I want to change the Countdown - field.
try {
final int i = 10; //my new var, which should saved in databank
PreparedStatement ps = connection.prepareStatement(""); //Dont know what to write in SQL here
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
Example : Imagine my field with the field Username "example" has the Countdown 11 and now I want to change this value to 10.
If you want to use a prepared statement, you need to "prepare" your query first, then inject the values. More info here.
First, you need an UPDATE query.
String updateStatement =
"UPDATE data" +
"SET Countdown = ? " +
"WHERE Username = ?";
Then you can prepare your statement with:
PreparedStatement ps = connection.prepareStatement(updateStatement);
And add your values with:
ps.setInt(1, 11);
ps.setString(2, "example");
And you're ready to go!
ps.executeUpdate();

Cannot delete or update a parent row - Java

I teacher is trying to delete a row, which is used by a student.
But how can I delete this row anyway?
If the teacher wants to delete the lesson it should delete it anyway?
This is the function I have for the delete query:
con = DriverManager.getConnection ("jdbc:mysql://localhost:3307/lessons","root","");
String query = "DELETE FROM lessons WHERE Number= ?";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1,txtFieldNumber.getText());
pst.executeUpdate();
.
CREATE TABLE UserLogin(
Number INTEGER,
UserNumberINTEGER,
FOREIGN KEY (Number) REFERENCES termin(Number),
FOREIGN KEY (UserNumber) REFERENCES User(UserNumber)
);
CREATE TABLE lessons(
Number INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
LName VARCHAR(20)
);
CREATE TABLE User(
Name VARCHAR (20),
UserNUmber INTEGER NOT NULL PRIMARY KEY
);
You have to perform 2 separate deletes and in the right order using the same value for the Number parameter.
First delete from UserLogin with
DELETE FROM UserLogin WHERE Number = ?
And then use the command you have today
DELETE FROM lessons WHERE Number = ?
If you want to be sure both statements gets executed properly you can use manual commit like this
You can't use setString when the underlying column is int
Assuming your txtFieldNumber.getText() returns a number in String format, Try the following
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
Update:
Based on your question edit, looks like you are first trying to delete primary key in lessons which is being referenced in UserLogin table. This is the reason you're facing the error.
To overcome this, you may want to first delete in UserLogin table and then delete the corresponding rows in lessons table.
String query = "DELETE FROM UserLogin WHERE Number= ?";
PreparedStatement pst = con.prepareStatement(query);
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
pst.executeUpdate();
String query2 = "DELETE FROM lessons WHERE Number= ?";
pst = con.prepareStatement(query2);
pst.setInt(1,Integer.parseInt(txtFieldNumber.getText()));
pst.executeUpdate();
This should solve your issue

Java JDBC adding automatic value to database

I'm working with Java JDBC with Apache Derby data base.
I have a table called `company`` with the values :
id, comp_name, password, email.
This method should create a new row of company with name, password, and email received from the user but the ID should be given automatically from the database and increment itself each time a new company is added to the database.
I just can't figure out how to make this work, I obviously get a error
"column 'ID' cannot accept a NULL value."
because the update occours before the ID is setted.
Code:
public void createCompany(Company company) {
Connection con = null;
try {
con = ConnectionPool.getInstance().getConnection();
String sql = "INSERT INTO company (comp_name, password, email) VALUES (?,?,?)";
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, company.getCompName());
pstmt.setString(2, company.getPassword());
pstmt.setString(3, company.getEmail());
pstmt.executeUpdate();
ResultSet rs = pstmt.getGeneratedKeys();
rs.next();
company.setId(rs.getLong(1));
pstmt.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
ConnectionPool.getInstance().returnCon(con);
}
During creation of that table you have to write following DDL
CREATE TABLE MAPS
(
comp_id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(24) NOT NULL,
password VARCHAR(26)
)
Ref : https://db.apache.org/derby/docs/10.0/manuals/develop/develop132.html
You're doing almost everything right, you just need to let the database assign an unique ID to each inserted row:
CREATE TABLE my_table (
id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
...
);
A problem could be that you made a mistake by creating your table.
You could create your table like this:
CREATE TABLE company
(
ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
comp_name VARCHAR(50),
email VARCHAR(50),
password VARCHAR (50)
)
IF you want other values to be not NULL you could add NOT NULL to their lines:
password VARCHAR (50) NOT NULL
Delte your old table and execute the the SQl above on your DB. After that you can use your code without changes.

[Java]Error when Inserting SQL, auto increment in the table - userId

So I am making a registration page and when I enter all the fields and click signup to submit, enterNewUser(,,,) is called and the fields userId, username,password and role are inserted into the table User. I confirm this by running select * from user; into MYSQL workbench.
Then enterUsername(,,,) is called and I get this error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '(3,'Barry','Allen')' at line 1
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
'(3,'Barry','Allen')' at line 1
public static int enterNewUser(String username,String password, String role){
//int userId = -1;
int ID = 0;
//int ID=-1;
try{
if(checkUserNameAvailable(username)==true){
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost/log", "root", "root");
String q0 = "Select userId from user ORDER BY userId DESC LIMIT 1"; //get ID of last
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(q0);
if(rs.next()){
ID = rs.getInt("userId");
ID++;
}
else
ID=1; // Empty Table, so start with ID 1
rs.close();
st.close();
String q1="insert into user values(?,?,?)";
PreparedStatement ps = cn.prepareStatement(q1);
//ps.setInt(1,ID);
ps.setString(1,username);
ps.setString(2,password);
ps.setString(3,role);
ps.executeUpdate();
ps.close();
}
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
DB_close();
//if(userId!=-1)
// return userId;
return -1;
}
public static boolean enterUsername(int userId, String firstname, String lastname){
try{
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost/log", "root", "root");
//String q1="INSERT INTO user_profile values(?,?,?)";
String q1 = "INSERT into user_profile (userId, firstname, lastname) VALUES (?,?,?)";
PreparedStatement ps = cn.prepareStatement(q1);
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
ps.executeUpdate();
ps.close();
return true;
}catch(Exception e){
System.err.println(e.getMessage());
e.printStackTrace();
}
DB_close();
return false;
}
Here is my database structure.
Edit: found the issue, database was not structured properly.
CREATE TABLE user ( userId int(3) NOT NULL AUTO_INCREMENT,
username varchar(20) DEFAULT NULL, password varchar(20) DEFAULT
NULL, role varchar(20) DEFAULT NULL, PRIMARY KEY (userId),
UNIQUE KEY username (username) );
CREATE TABLE user_profile ( userId int(3) NOT NULL DEFAULT '0',
firstName varchar(20) DEFAULT NULL, lastName varchar(20) DEFAULT
NULL, PRIMARY KEY (userId), CONSTRAINT FK FOREIGN KEY
(userId) REFERENCES user (userId) );
Shouldn't following section in method enterUsername
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
be like this
ps.setInt(1, userId);
ps.setString (2, firstname);
ps.setString (3, lastname);
I don't see the reason for the error message that you posted.
But I see some other things that look like a problem:
ps.setInt(1, userId);
ps.setString (1, firstname);
ps.setString (2, lastname);
The indexes are wrong: instead of 1, 1, 2, it should be 1, 2, 3.
(Frankly, I don't see how the code could possibly work as posted.)
Btw, this also looks wrong in the other method:
insert into user values(?,?,?)
As the table has more than 3 columns, you need to specify their names,
like you did in enterUsername.
Use
String q1 = "INSERT into user_profile (firstname, lastname) VALUES (?,?)";
because your first field is auto increment..So it automatically increment values while inserting values.
I recommended this way,
Delete your current table and create a new one like this
id-->int(30) (AUTO INCREMENT) NOTNULL //Dont need to take care of this field
USER_ID-->int(30) NOT NULL //you should create your own ID and increment it before adding a new person
username-->varchar(100)
password-->varchar(100)
role-->varchar(100)
and usually, call userId exactly same like your code,
String q0 = "Select userId from user ORDER BY USER_ID DESC LIMIT 1"; //get ID of last
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery(q0);
if(rs.next()){
ID = rs.getInt("USER_ID ");
ID++;
}

preparedStatement and resultSet interfaces how to use batch and get methods

I am starting now to use the package java.sql and I am doing some experiments with it.
I have these two tables
the first is:
`user` (
`userID` INT NOT NULL AUTO_INCREMENT ,
`nickname` VARCHAR(20) NULL ,
PRIMARY KEY (`userID`) )
and the second is:
`club` (
`clubID` INT NOT NULL AUTO_INCREMENT ,
'clubName` VARCHAR(20) NOT NULL ,
`userID` INT NULL ,
PRIMARY KEY (`clubID`) ,...
where userID is a foreign key associated to the userID of the first table.
And this is the code that should explain what I want to do. (this is only for one user-club)
Class.forName("com.mysql.jdbc.Driver");
this.connect = DriverManager.getConnection("jdbc:mysql://localhost/" + this.database + "?user=" + this.user + "&password=" + this.password);
String s;
s = ("insert into " + this.database + ".user (nickname) values (?)");
this.preparedStatement = this.connect.prepareStatement(s);
this.preparedStatement.setString(1, "username");
this.preparedStatement.executeUpdate();
s = ("SELECT userID from " + this.database + ".user where nickname = 'username'");
this.preparedStatement = this.connect.prepareStatement(s);
this.resultSet = this.preparedStatement.executeQuery();
int n=0;
while (resultSet.next())
{
n = this.resultSet.getInt("userID");
}
s = ("insert into " + this.database + ".club (clubName, userID) values (?, ?)");
this.preparedStatement = this.connect.prepareStatement(s);
this.preparedStatement.setString(1, "club");
this.preparedStatement.setInt(2, n);
this.preparedStatement.executeUpdate();
If I would do this process for more couples (username, clubname), for example saved in an HashMap how could I use the addBatch() method of preparedStatement Inteface??
I should use three batches one for eache action:
1 insertion of username
2 selection (and recording) of userID
3 insertion of clubname associated to the correct userID
Or I could include all the process in only one batch??
And another question, why If i try to remove the while cycle surrounding the resultSet.getInt() method it gives me an error??
Thanks in advance to all who will try to help me!
You cannot include all the process in only one batch. The batch is intended for a single query. Here is the reference link for a good example.
You can execute multiple queries as different batches as follows .
try {
DataSource dataSource = null;// specify data source
Connection con = dataSource.getConnection();
Statement s = con.createStatement();
// or
// PreparedStatement s =
// con.prepareStatement("INSERT INTO profile (fullname) VALUES ('Visruth CV')");
s.addBatch("INSERT INTO tran1 (username, password, profileid) VALUES ('visruth', 'password', 1)");
s.addBatch("INSERT INTO testtab (name) VALUES ('testtab')");
s.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}
If you remove the while (resultSet.next()) loop, it will make a NullPointerException because the current position of the cursor in the resultSet is in the default row, when you make resultSet.next() the cursor will jump in to the next row if there is a row available (from the default row to first row, first row to second row etc...) and at the same time resultSet.next() will return true (only if it jumps) otherwise false. If resultSet contains more than one row, it can be put inside a while loop, if not just need to use the if condition there.

Categories

Resources