Checking for existing record in the SQL database - java

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
}

Related

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);
}
}

Mysql query in with the answer true, false

I was not too long ago studying java, so maybe I have a stupid question.
I have a table, where i store some info.
And i want to check in this table on availability of some information (it will be only one line), and if yes - take from this line, the information in a particular column, if no - do another thing.
I really don`t know how to do this.
My idea was something like this: at first - check the table:
SELECT * FROM tablename WHERE nickname = "kvant";
then if true, do another query with searching info.
and do this with condition if\else. but all my attempts not turn.
I hope for your help, sorry for my awry English.
Check if the data exists like this:
IF EXISTS(SELECT * FROM tablename WHERE nickname = "kvant")
BEGIN
--value is found so go ahead
END
ELSE
--value not found
BEGIN
END
One simple way is to query the database and get the result. If result!=Null {//do something} else {//Do something}
(Can use try - catch as well)
Pure java possible solution:
Try to get that value in the query. Get the ResultSet rs of that query and:
if(rs.next()) {
String value = rs.getString("value"); //Assuming the column is value and that it is a String.
//Do whatever you want with the value
} else {
//The other thing
}
If you can not take the value from the first ResultSet, do another query in the if.
write in sql like select case exists (select * from yourtable where condition) then 'dothis thing' else 'dootherthing' from 'yourtable' where 'yourcondition'
since you wanted to run some other query after you know you have some conditon exists.

getting all the data from mysql database table is not working in java

i am trying to get all the data from a certain table.but it's only giving me only the first row twice a result (as i have two rows in the database)
here is my code
String data[]=new String[10];
String[] result;
Product p= new Product();
int serial=0;
try{
String sql="select * from product";
rslt=st.executeQuery(sql); //where private static Statement st, private static ResultSet rslt;
while(rslt.next()){
data[1]=rslt.getString("p_code");
data[2]=rslt.getString("p_name");
/* data[3]=rslt.getString("description");
data[4]=rslt.getString("measurement");
data[5]=Integer.toString(p.RemainProduct(data[1]));
data[6]=p.getSellPrice(data[1]);
serial+=1;
data[0]=Integer.toString(serial);
DTB.addRow(data); */
System.out.println("code :"+data[1]+" "+"Name :"+data[2]);
}
}catch(Exception ex){
System.out.println("ERROR :"+ex);
}
my table has two data, here is my database table data
and here is the result after i run the program.
i don't know where is the actual problem. the same code works fine on the other method but why i can't get it here. i am very new to java, please help me fixing this problem
Your code looks correct to me. I think this is a case of "what you are looking at is not what is broken". Perhaps you are not querying the table you think you are querying, or perhaps your table view is cached and out of date. Refresh your table view, and try printing out the PK (id column in the table) in your program output as a double check that the table your are querying is the correct table. Also, double check your JDBC URL and verify you are querying the correct database.
Also, your comments indicate that the same code is giving correct results in a different method. Maybe there is more going on in your actual code that we don't have insight into? Perhaps your code (not shown in your example) is:
Updating the table so that row 1 and 2 have the same data.
Querying the database (as shown in your example), and returning same data in row 1 and 2.
Update the table so that row 1 and 2 now have different data which shows up when you manually query the database.
Finally, make sure some of your other team members or an automated test process isn't updating the table without your knowledge.

Does not automatic sum

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.

concurrency with h2 database

I have a table xxx with id (id_xxx int AUTO_INCREMENT ) and name (name_xxx varchar (50)),
When I insert a new row in the table I made​​:
INSERT INTO xxx VALUES ​​("name for test");
and the result (int=1) of insertion is returned, then I display in my java interface a message "succseed!", until now it's a very basic and simple operation...
BUT,
when I want to return the inserted id_xxx,I have to do another query to the database:
INSERT INTO xxx VALUES ​​("name for test");
//after the insert response I made:
SELECT MAX (id_xxx) FROM xxx;
and I display in my java interface "succseed $$$ is your id_xxx "....
the second version can easily cause a serious error during concurrent access to multiple users:
imagine a case when a user1 makes an insert... and then H2DB interrupt operations of this user then executes the insert of user2.
when user1 executes a select max (id_xxx) the H2DB return A FALSE id_xxx...
(I hope that my example is clear otherwise I will schematize this problem).
how to solve this problem?
You should be able to retrieve keys generated by insert query, see 5.1.4 Retrieving Automatically Generated Keys.

Categories

Resources