I'm trying to get the automatically incremented column after I input a new row. I have the following columns in my table:
+----+---------+---------+-------+------------+--------------+------------+---------------+-----------+
| ID | Minkita | Maxkita | Meser | MetodasNum | MainQuestion | MetodaData | RequiresZiood | Nispachim |
+----+---------+---------+-------+------------+--------------+------------+-----
Where ID is an auto-incremented, not null mediumint.
My JSP code for this:
PreparedStatement s = connection.prepareStatement(
"INSERT INTO Threads"
+"(`MinKita`, `MaxKita`, `Meser`, `MetodasNum`, `MainQuestion`, `MetodaData`, `RequiresZiood`, `Nispachim`)"
+" VALUES(?, ?, ?, ?, ?, ? ,? ,?)"
);
//Blah blah, setting strings and values for the prepared statement... Then:
s.executeUpdate();
Now, I understand that executeUpdate returns the row number of my new row, but what I want to do is to get the ID from my row number.
The thing is, the IDs aren't consistent and they may be in an order like so: 1, 2, 5, 7, 13... as rows may be deleted.
So, how do I get the data in the ID column from the row number?
Thanks in advance,
~ NonameSL
You can get the generated ID when doing an INSERT with the following:
First create a PreparedStatement which does return generated values of auto-increment columns:
PreparedStatement s = connection.prepareStatement(
"INSERT INTO <your sql>",
Statement.RETURN_GENERATED_KEYS);
After you have execute the statement you can retrieve the ID as follows:
s.executeUpdate();
ResultSet result = stmt.getGeneratedKeys();
if (result.next())
id = result.getObject(1);
If you have multiple AUTO_INCREMENT columns in the table you can also specify the columns which should be returned:
PreparedStatement s = connection.prepareStatement(
"INSERT INTO <your sql>",
new String[] { "ID" }); // the ID column only
Related
Could someone tell me what I'm doing wrong here? I have a table like this:
mysql> describe mytable;
Field Type Null Key Default Extra
-----------+----------+--------+--------+------------+---------------
id int(11) NO PRI NULL auto_increment
foreignid int(11) NO MUL NULL
date date NO '0000-00-00'
[some more columns]
I'm trying to insert values via a preparedStatement:
String insert = "insert into mytable (foreignid, date) values (?, ?)";
PreparedStatement pst = connection.prepareStatement(insert);
pst.setInt(1, newForeignID); //valid foreign key
pst.setDate(2, newDate); //newDate is a proper java.sql.Date
pst.execute();
That should be fairly straightforward, yet I always get this error:
Unknown column 'date' in 'field list'
Any idea why that happens?
date is a Keyword in mysql. You should escape or better rename it:
String insert = "insert into mytable (foreignid, `date`) values (?, ?)";
I want to use insert statement with select subquery from another table. In my case, I want to add a row from PRESENTATION table to AVAILABILITY table.
AVAILABILITY table structure:
availableID (number, generated using sequence)
availableDay (varchar)
availableStart (varchar)
availableEnd (varchar)
lecturerID(FK) (varchar)
presentationID(FK) (number, generated using sequence)
PRESENTATION table structure:
presentationID (number, generated using sequence)
presentationDay (varchar)
presentationStart (varchar)
presentationEnd (varchar)
I tried to construct the query in DAO like this :
String lecturerID = Abean.getLecturerID();
String availableDay = Abean.getAvailableDay();
String availableStart = Abean.getAvailableStart();
String availableEnd = Abean.getAvailableEnd();
Date availableDate = Abean.getAvailableDate();
String presentationID = Abean.getPresentationID();
try{
currentCon = JavaConnectionDB.getConnection();
PreparedStatement ps=currentCon.prepareStatement("
insert into availability (availableID,
lecturerID,
availableDay,
availableStart,
availableEnd,
presentationid)
select(availabilityseq.nextval,
?,
presentationDay,
presentationStart,
presentationEnd,
presentationid)
from presentation where presentationid=?
");
ps.setString(1,Abean.getLecturerID());
ps.setString(2,Abean.getAvailableDay());
ps.setString(3,Abean.getAvailableStart());
ps.setString(4,Abean.getAvailableEnd());
ps.setString(5,Abean.getPresentationID());
// ps.setString(6,Abean.getAvailableID());
ps.executeUpdate();
}
catch(Exception e){
System.out.println("add availability 2 failed: An Exception has occurred! " + e);
}
As expected, it return error
ERROR: java.sql.SQLException: Invalid column index
So, how can i do insert with subquery with extra column?
UPDATE: MY DAO codes
You need to match the setting of bind variables values with the bind variables specification in the SQL text :
EDIT Apr 18th: removed parenthesis from select subquery
PreparedStatement ps=currentCon.prepareStatement("
insert into availability (availableID,
lecturerID,
availableDay,
availableStart,
availableEnd,
presentationid)
select availabilityseq.nextval,
?,
presentationDay,
presentationStart,
presentationEnd,
presentationid
from presentation where presentationid=?
");
ps.setString(1,Abean.getLecturerID()); // match first "?"
ps.setString(2,Abean.getPresentationID()); // match 2nd "?"
public static void createLoan(Loan loan){
Connection con = null;
try {
con = JDBCConnectionFactory.getInstance().getNewConnection();
String sql = "";
sql = "INSERT INTO loan (users_id, book_id, loan_date, loan_dueDate) "
+ "VALUES (?, ?, CURDATE(), DATE_ADD(CURDATE(),INTERVAL 30))";
PreparedStatement prep = con.prepareStatement(sql);
prep.setLong(1, loan.user.getDatabaseId());
prep.setLong(2, loan.book.getDatabaseId());
Why can´t I use the DATE_ADD function to set a specific date? It just returns Null.
DATEADD Method example :
SELECT OrderId,DATEADD(day,45,OrderDate) AS OrderPayDate
FROM Orders
check this one : http://www.w3schools.com/sql/func_dateadd.asp
function Date_Add has signature DATE_ADD(date,INTERVAL expr unit) you are missing the unit.
I tried with below sample data
CREATE TABLE `person` (
`ID` INT(11) NOT NULL,
`NAME` VARCHAR(100) NOT NULL,
`loanduedate` DATETIME DEFAULT NULL
) ;
INSERT INTO person VALUES(4,'shirish',DATE_ADD(CURDATE() , INTERVAL 45 DAY));
and the insert went fine.
table has below data inserted successfully
ID NAME loanduedate
------ ------- -------------------
4 shirish 2015-06-11 00:00:00
Source
DATE_ADD(date,INTERVAL expr unit)
The date argument specifies the starting date or datetime value.
expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a “-” for negative intervals.
unit is a keyword indicating the units in which the expression should be interpreted.
And for you, the problem is that unit is missing you should select it from the table of unit value, like DAY.
sql = "INSERT INTO loan (users_id, book_id, loan_date, loan_dueDate) "
+ "VALUES (?, ?, CURDATE(), DATE_ADD(CURDATE(),INTERVAL 30 DAY))";
i got a table made in this way
CREATE TABLE WS_NAPACQ00T
( IDE_IDEN varchar2(20) PRIMARY KEY NOT NULL,
CLB_CXML CLOB,
SYS_DATE TIMESTAMP
);
and this java code to put in dt_date current date.
Timestamp dt_date = new Timestamp(System.currentTimeMillis());
String insertXML = "insert into WS_NAPACQ00T (IDE_IDEN, CLB_CXML, SYS_DATE) values ('10', 'test', '"+dt_date+"' ) ";
result = statement.executeQuery(insertXML);
the error is:
"not a valid month"
how can i resolve?
Don't use Statement it can lead to SQLInjection, instead use PreparedStatement as follows.
String insertXML = "insert into WS_NAPACQ00T (IDE_IDEN, CLB_CXML, SYS_DATE) values (?, ?, ?) ";
PreparedStatement statement = connection.prepareStatement(insertXML);
statement.setString(1,"10");
statement.setString(2,"test");
statement.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
result = statement.executeQuery();
Unrelated.
If you want to insert current timestamp you can use CURRENT_TIMESTAMP. SELECT CURRENT_TIMESTAMP from DUAL; will give the current timestamp.
I'm trying to insert skeleton data into a database using jdbc.
So far my code is:
Statement st=con.createStatement();
String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
+ "VALUES (1, 1, 'forename1', 'surname1', '1996-06-03');";
I need to create 100 entries for this and I'm not too sure how to go about doing it.
All I want is the student id, titleid, forename and familyname to increment by 1 until it reaches 100 entries with those rows filled in, date of birth doesn't need to be altered. I'm asking how to do a loop for this
General answer - You should use PrepareStatement instead of Statement and execute as batch.
Common way to insert multiple entry or execute
String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
+ "VALUES (?, ?, ?, ?, ?);";
ps = connection.prepareStatement(SQL_INSERT);
for (int i = 0; i < entities.size(); i++) {
ps.setString(1, entity.get...());
...
ps.addBatch();
}
ps.executeBatch();
Important Note:
Why you should use PrepareStatement Over Statement
SQL Injection Example
There are two ways to do this. You can put your insert query inside a loop or you can put your loop inside an insert query. I have found that the better method depends on the database engine (but I've never used postresql) and the number of records you want to insert. You could bump up against the maximun query length or number of parameters or something.
The following code sample is ColdFusion, but it is intended to show the general idea of having a loop inside a query. You would have to write equivalent code in java.
<cfquery>
insert into yourtable
(field1
, field2
, etc)
select null
, null
, null
from SomeSmalllTable
where 1 = 2
<cfloop>
union
select <cfqueryparam value="#ValueForField1#">
, <cfqueryparam value="#ValueForField#">
, etc
</cfloop>
</cfquery>