I'm fairly new to developing web apps in Java. I just connected the database, and as seen in the pictures, my ID_patient is auto_increment, but in Netbeans it looks generated.
INSERT INTO sys.patient values('5','elif','nil','er','elif#hotmail.com','11111111111','1234a','istanbul')
The new record inserted wants this value, while i want it to take
INSERT INTO sys.patient values('elif','nil','er','elif#hotmail.com','11111111111','1234a','istanbul')
and auto-increment and give the id as 1,2,3,4...etc.
how can I fix this?
thank you
in netbeans
in mysql
If you are expecting to create an insert query where you don't want to provide an id and the database should generate it automatically based on table defination then you need to create insert query where you have to mention columns names.
Example
INSERT INTO <TABLENAME>(COLUMN1, COLUMN2, COLUMN3, COLUMN4)
VALUES
(VALUE1,VALUE2, VALUE 3,VALUE 4);
So in ur case it should be
INSERT INTO PATIENT(FirstName,MiddleName,LastName,E_mail)
values
('myname','mymiddlename','mylastname','myemailid');
Sequence of column names and their values are very important. They should match exactly. If you don't provide a value for one of column and if its is auto increment, then DB will add an value to it else it will add null value.
Related
So I have a MySQL database schema where there is a USERS table which contains the ID as a primary key for that table, I also have a USER_PASSWORDS table which references the USERS table where the USER_ID will act as a foreign key in this table.
The issue that I am facing is that I am writing an application where the user will be able to sign up and specify a username and password. But I would like to insert the user into the database with one query.
I was thinking I had to insert the username first into the USERS table and see what ID has been given to that username and then insert the hash of the password that the user has entered into the USER_PASSWORDS table and specifying the ID that was queried.
I dont like this approach because it means that I have to:
INSERT into the database
QUERY the database
INSERT into the database again
Is there a better way of doing this?
Thanks
You can't insert into two tables with one insert statement, and you would have to query the users table anyway to get the ID value to insert as a foreign key for the user_passwords table.
Really the only way to do what you want is the solution you've already identified:
Insert into the Users table
Query to get the ID of the User you just inserted
Insert into the USER_PASSWORDS table with the ID you obtained for the User.
You could wrap all this up in a stored procedure that takes user data and password as parameters, which would be the "better" way of doing it.
As you didnt really tell for what system / programming language you need this and you did not provide any code example either, I can only give you some theory what you could do:
Its impossible to insert data into two different MySQL tables with one queries but you can reduce your script atleast by the SELECT query:
1.) There is a function in most mysql apis (Depending on what programming language and MySQL Library you are using) that says "getLastInsertId()", "lastInsertId()" or similar.
This will return the ID that was inserted by the auto-increment of the table after the insert is completed.
Just check the docs of your MySQL-api it will have such a function.
2.)
The second possibility is using a UUID - a very large (commonly 128-bit) long string which is generated totally random. There are more so many possible combinations it will happen more probably that you win in the lottery 10 times in a row then you generate two times the same UUID that is already in your table.
So you just generate the UUID and insert it as a key in both tables and you are done.
Just use google to find out-of-the-box libraries to generate UUID's you dont need to build the alogrithm on your own.
An UUID could looks like this:
4a34fe87-f577-4ea9-9557-1bc8f779a68c
One solution: since the hash is unique you can use the hash as a primary key in the USERS table. Then you know what the primary key (id) is at the time of the insert and can reuse when INSERTING in the USER_PASSWORDS table.
That way you can avoid the id query at least.
I am trying to create a mysql queryer in java and I would like to be able to add the primary key(composite) associated with the user query.
For example:
SELECT *
FROM my_table
WHERE logic
How can i add the composite primary key as the first column of my result? I need to keep columns asked by the user too.
Do i need to use:
CONCAT_WS('-',column1,column2,column3) ?
I can't use it if the user asks every columns (using *).
Perhaps something like this will help:
SELECT concat(....), mytable.*
FROM mytable
Although when you add the concat-column add the end, somthing like below without the additional table reference should work fine:
SELECT *, concat(....) FROM mytable
I have a large data set(250,000 rows) that I need to upload to a SQL table. I am currently doing this from a Java application I created, and as expected, it is extremely slow. I have to insert each row from a text file into a table, with an auto_increment column that stores an id for that new row. Now I want to use that same id to insert a modified version of the string I entered to the first table, into a second table, where one of the columns holds that original incremented id, so that I can tie the two rows together. Obviously I can query the string I just inserted, and pull the id, but that is an extra query per row I'm trying to avoid. Is there a way to pull the incremented id value from the sql table to my java class at the time the insert statement is executed?
Thanks,
I guess you are using JDBC so use getGeneratedKeys() of java.sql.PreparedStatement. The returned Resulset contains the auto-generated key.
This is a common scenario, but i wanted to find out which way is the performance optimized way and best practice.
I have a table with 4 columns: id, name, and two other fields. Id is the PK and name is a unique key. I'm reading data from excel file, populate the values of each row in a Domain object and then saving it. When saving, i want to see whether a record already exists for the same name and if exists, i want to update it. Else save it as a new record.
I can do it with normal select query for the name and check for null, and based on that insert or update but i have thousands of rows to be read from excel files and a non-functional requirement requested is the performance.
So please advice me on which is the best way to handle this senario? i haven't started coding my persistence layer part yet, so i can switch to an ORM or plain jdbc according to your suggestion.
Edited:
If i use name as primary key, then i think i can use saveOrUpdate or merge from an ORM, to fullfill my need. Is it a good idea???
Thanks & regards,
Prasath.
I think the fastest way would be to carry out all the insert/updates in the database itself rather than connecting to it and using a large number of statements.
Note, this is Oracle specific, but other databases may have similar concepts.
I would use the following approach: First save the Excel data as a CSV file on the database server (/mydatadir/mydata.csv), then in Oracle I would be using an external table:
create or replace directory data_dir as '/mydatadir/';
create table external_table (
id number(18),
name varchar2(30),
otherfield1 varchar2(40),
otherfield2 varchar2(40))
organization external (
type oracle_loader
default directory data_dir
access parameters
( fields terminated by ',' )
location ('mydata.csv')
)
(Note, the external table wouldn't have to be set up every time)
Then you can use the following command to merge the data into your table:
merge into yourtable t
using external_table e
on t.name = e.name
when matched then
update set t.id = e.id,
t.otherfield1 = e.otherfield1,
t.otherfield2 = t.otherfield2
when not matched then
insert (t.id, t.name, t.otherfield1, t.otherfield2)
values (e.id, e.name, e.otherfield1, e.otherfield2)
This will upsert the rows in yourtable in one Oracle command, so all the work will be carried out by the database.
EDIT:
This merge command can be issued over plain JDBC (though I prefer using Spring's SimpleJdbcTemplate)
EDIT2:
In MySQL you can use the following construct to perform the merge:
insert into yourtable (id, name, otherfield1, otherfield2)
values (?, ?, ?, ?),
(?, ?, ?, ?),
(?, ?, ?, ?) --repeat for each row in the Excel sheet...
on duplicate Key update
set otherfield1 = values(otherfield1),
otherfield2 = values(otherfield2)
This can be issued as a plain JDBC statement and is going to be better than a separate update and insert, and you can call these in batches of (say) a hundred rows from the spreadsheet. This would mean 1 JDBC call for every 100 rows in your Excel sheet and should perform well. That'll allow you to do it without external tables (you'd need a UNIQUE index on the name column for this to work, I wouldn't change the primary key as this could cause you problems with foreign keys if you needed to change somebody's name).
MySQL also has the concept of external tables, which I think would be faster still than inserting the data as batches as per above. As long as the csv file is uploaded to the correct location, the import should work quickly.
May be it's reasonable to read all names in a Set and subtract the use combinations with Set of names read from the excel file.
Set dbSet=//fill it from SQl query;
Set newSet//fill it from the file;
newSet.removeAll(dbSet); //left non existing ones to be inserted.
originalNewSet (could be clone of initial)
originalNewSet.removeAll(insertingSet); //left records to be updated.
Here is my situation and my constraints:
I am using Java 5, JDBC, and DB2 9.5
My database table contains a BIGINT value which represents the primary key. For various reasons that are too complicated to go into here, the way I insert records into the table is by executing an insert against a VIEW; an INSTEAD OF trigger retrieves the NEXT_VAL from a SEQUENCE and performs the INSERT into the target table.
I can change the triggers, but I cannot change the underlying table or the general approach of inserting through the view.
I want to retrieve the sequence value from JDBC as if it were a generated key.
Question: How can I get access to the value pulled from the SEQUENCE. Is there some message I can fire within DB2 to float this sequence value back to the JDBC driver?
Resolution:
I resorted to retrieving the PREVIOUS_VAL from the sequence in a separate JDBC call.
Have you looked at java.sql.Statement.getGeneratedKeys()? I wouldn't hold out much hope since you're doing something so unusual but you never know.
You should be able to do this using the FINAL TABLE syntax:
select * from final table (insert into yourview values (...) );
This will return the data after all triggers have been fired.