Does not automatic sum - java

Why my pk will not auto ++ in my database? I want to let my ok auto +1 every time when I insert new details to the database...
public void generatePK(){
try{
rsCombineItem = stmtSearch.executeQuery("SELECT * FROM CombineItem;");
while(rsCombineItem.next()){
this.pk = rsCombineItem.getInt(1);
}
this.pk+=1;
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
}

This is something that you need to set up on the database side, and not in your code. Set the column in your database as primary key, and to auto increment! See the example to see an example using SQL Server.

It's not clear what you're trying to do here at all. You talk about inserting but show a select statement; you talk about incrementing in the database but are incrementing in code; you have a method called generatePK which returns void; etc...
The short answer is that you should get the database to handle this. Every half-decent database has explicit support for primary keys, which you can have auto-assigned and auto-incremented. Simply set up the table to do this for you, and let the database choose the (after all, arbitrary) primary key as and when one is required.

Related

jOOQ Mocking: Why does insert require me to prepare a MockResult for a subsequent select?

I have a jOOQ MockConnection/DSL set up for unit tests to be able to do insert, but in at least one instance of my testing I have to also implement a MockResult for a subsequent select statement.
My question is, why does jOOQ execute a select statement in org.jooq.impl.AbstractDMLQuery#executeReturningGeneratedKeysFetchAdditionalRows -> selectReturning for my insert?
My insert is a simple myRecord.insert(), and the mocked DSL looks something like this:
// Simplified
var connection = new MockConnection(ctx -> {
var sql = ctx.sql();
if (sql.startsWith("insert")) {
return mockResultCount(1); // Impl elsewhere
}
return null;
});
var dsl = DSL.using(connection, SQLDialect.MYSQL);
[...]
var myRecord = new MyRecord();
myRecord.setX(...).setY(...);
dsl.attach(myRecord);
// Why does this require a mocked insert result AND a mocked select result?
myRecord.insert();
And my test fails because jOOQ needs the DSL to return a result for a select on something like SELECT ID_COLUMN, UNIQUE_KEY_COLUMN WHERE UNIQUE_KEY_COLUMN = ?
The only thing I can think of is that this table has a unique key?
Anyone know why a simple record.insert(); requires a select statement to be executed?
This depends on a variety of factors.
First off, the dialect. MySQL, for example cannot fetch values other than the identity values via JDBC's Statement.getGeneratedKeys(). This is the main reasons why there might be an additional query at all.
Then, for example, your Settings.returnAllOnUpdatableRecord configuration might cause this behaviour. If you have turned this on, then a separate query is required in MySQL to fetch the non-identity values.
Or, if your identity column (in MySQL, the AUTO_INCREMENT column) does not coincide with your primary key, which seems to be the case given your logged SQL statement, where you distinguish between an ID_COLUMN and a UNIQUE_KEY_COLUMN.
The reason for this fetching is that jOOQ assumes that such values may be generated (e.g. by triggers). I guess that the special case where
The identity and the primary key do not coincide
The primary key has been supplied fully by the user
We can attempt not to fetch the possibly generated primary key value, and fetch only the identity value. I've created a feature request for this: https://github.com/jOOQ/jOOQ/issues/9125

can I set autocommit to ON while using savepoints

I am a newbiee to Java database programming.
Recently during my project, I have got stuck in a concept, which I searched a lot but not getting any solution to satisfy my query, which may help me to get out of my problem.
Actually the problem is:
I have three table, let say one main (which contains common fields of actual data) table and two child table(which contains other different fields according to some criteria). Main table contain some part of information, and rest of information, depending on some criteria, will be saved in only one of the child table.
Now the scenario is like this, I have set autocommit off, then firing one insert query. So, when the insert query will be fired, database will give it a unique ID, in mysql, since the ID feild is autoIncrement. Now firing a Select Query, I want to extract that ID from main table. So, here is my question, Will SELECT QUERY BE ABLE TO EXTRACT THE ID OF THAT PARTICLULAR RECORD I HAVE JUST SAVED? Please remember that autocommit is set to false, and I have not committed yet.
I am doing this because I want that unique ID to be inserted in one of the child tables so that I can relate the information between table. So, After finding the ID, I have again fired a new INSERT query to save rest of the data in one of the child tables, now with the unique ID with rest of the data. And then on successful insertion, I have committed the connection.
Also, I want that either the information is saved in both (main and one of the child) tables or the details does not saves completely if any failure occur, so that I do not lose the partial information.
Please Help me in this. If you can explain what is relation between autocommit, savepoints. When to use, what things are to be remembered. Please provide some genuine resources, if you can, which demonstrate their nature,how they work under different circumstances, etc. I have googled but didn't got any such useful information. I want to get deep knowledge about it.
Thanks in advance :)
It looks like you want to get the ID when the record is added to the table. This is available when you insert the record if you use the getGeneratedKeys(). The autocommit cannot be used to return this.
The following code shows how this can be done.
/**
* Insert to database using JDBC 3.0 + which will return the key of the new row.
*
* #param sql is the sql insert to send to the database
* #return the key for the inserted row
* #throws DBSQLException
*/
public static int insertAndReturnKey(Connection dbConnection, String sql, List<SqlField> params) throws DBSQLException
{
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String paramList = null;
try {
preparedStatement = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// Setup your parameters
int result = preparedStatement.executeUpdate();
resultSet = preparedStatement.getGeneratedKeys();
if (resultSet.next()) {
return (resultSet.getInt(1));
} else {
// throw an exception from here
throw new SQLException("Failed to get GeneratedKey for [" + sql + "]");
}
} catch (SQLException ex) {
throw new DBSQLException(buildErrorMessage(ex, sql, params));
} finally {
DBConnector.closeQuietly(preparedStatement);
DBConnector.closeQuietly(resultSet);
}
}

Checking for existing record in the SQL database

i have made a car rental management system in JAVA and SQL. The data base is working fine with no problems. i am stuck at checking if the data already exists in the database? like if a person enters NIC of 355353553.. it shouldn't be entered again.. Any suggestions about what i should do? thanks for any help!
You can set unique columns in mysql:
CREATE TABLE Cars
(
car_id int NOT NULL,
NIC int NOT NULL,
...
...
....
UNIQUE (car_id, NIC)
)
for more info, have a look here: Unique - sql syntax
Since you already have the database set to be unique, it sounds like you just want a method for handling errors in this case. I would use something like this personally, however I would bet that there is a more effective solution.
Create a method to get the count of the results from a query. In my example, I just called it countMethod. Have it return the number of rows from the query. You could alternatively use COUNT(*) from MySQL if you want to avoid using the java code. Here is some sudo code to get you started if you decided to try to implement.
int total = countMethod("SELECT id FROM the_table WHERE id=" + inputID);
if(total > 0) {
//Throw a warning message, it already exists
} else {
//Insert it into the database
}

How to get Auto Generated ID from SQL Table when multiple users working simultaneously

Am creating a SQL Database for multiple users(Roughly 100 user), each records having nearly 15 fields in it.. In which the ID field is auto incremented...
Whenever a person Inserting a record to the database, it has to show "auto incremented ID" for that particular person, For this am using this code
PreparedStatement ppstmt = conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
ppstmt.execute(sql,PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = ppstmt.getGeneratedKeys();
long key = 0;
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
As of now its working fine but my doubt is when multiple users inserting the record at the same time, whether it will corresponding auto generated ID to each person..?
The statement will work correctly. The generated key returned will be the key generated by that execution of that statement for that user. These are SQL-defined semantics. Any implementation where it didn't work would be broken.
NB the result set cannot be null at the point you're testing it.
You have tagged oracle, so here is oracle's documentation on how retrieving generated keys works. A key piece of information is:
Auto-generated keys are implemented using the DML returning clause.
So it is worth looking at the documentation on how the returning clause works.
As you can see, this is guaranteed to return only data relevant to the just executed statement.
I would also like to point out that your use of a PreparedStatement is wrong. Once you have created the PreparedStatement from
PreparedStatement ppstmt = conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
The next call should be to ppstmt.execute followed by ppstmt.getGeneratedKeys.

Java How to add data in two tables (Relational database)

I'm making a desktop app in Swing.
Here's the problem:
I have two tables - suppliers and items.
supplier supplierid(PK,AI),name,address,telephone
item itemid(PK,AI),supplier_supplierID(FK),name
Questions:
how do I insert in supplier and item tables at the same time? Does foreign key in items adds by itself or do I have to do it explicitly?
how do I add only item for a specific supplier? I was thinking about some list, dropdown menu to choose supplier -> get his PK and insert into item table.
I'm using Netbeans, MySQL
Thanks!
That depends on how you're trying to access your database.
Using a ORM like Hibernate and similar will do the most of the work for you because it's handling dependencies between Entities.
If you access your DB using plain JDBC, well you should insert the "rows" manually in the correct order.
So you should insert the supplier first and then the depending item.
If the supplier already exists, you should get it's id first and pass that value as supplier_supplierID when saving the item.
But this all has nothing to do with Spring!
You have to add the parent row (supplier) first, and then the item. Otherwise you will get an error.
When you add the supplier you use the new supplier_id as the value for the item.
This code is not the best but it works , first of all first insert some data in your primary table then you get that primary id you replace it with the 7 in the foreign key position in this code . so once it works then find a way to deal with the foreign key I did not work on it
try {
String url ="jdbc:mysql://localhost/dbtec";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,userdb,pass);
PreparedStatement statement = (PreparedStatement) conn.prepareStatement(" INSERT INTO supplier(name,address,telephone
) VALUES(?,?,?)");
statement.setString(1,"stackoverflow");
statement.setString(2,”15 newyork”);
statement.setString(3,"+19898989");
statement.executeUpdate();
statement.close();
/// Insert into another table
PreparedStatement statement2= (PreparedStatement) conn.prepareStatement("INSERT INTO item(supplierID,name) VALUES (?,?) ");
statement2.setString(1,"7");
statement2.setString(2,"Bruce");
statement2.executeUpdate();
statement2.close();
conn.close();
}
catch(SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(newclient.class.getName()).log(Level.SEVERE, null, ex);
}

Categories

Resources