i have table with 2 columns 1.column1 2.column2(its unique)
now through java coding i am inserting data through 2 methods
in the first method i want to insert data ,in this coumn1 filed should be auto increment(for new user)
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
pstm = connection.prepareStatement(sql);
pstm.setInt(1, auto_incrmentvalue need to set);
pstm.setInt(2,column2);
in the second method insert data with what i want
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
pstm = connection.prepareStatement(sql);
pstm.setInt(1, column1);
pstm.setInt(2,column2);
how to set auto increment value in the first method
NOTE:Here column1 is not a primary key
INSERT INTO table(column1) SELECT MAX(column1)+1 FROM table
This one worked for me
Please see INSERT...SELECT
Your query should be like this,
INSERT INTO table(column1, column2) SELECT MAX(column1)+1, 79 FROM table
More refined answer:
INSERT INTO
usertable(column1, column2)
SELECT CASE COUNT(column1)
WHEN 0 THEN 0
ELSE MAX(column1) END+1,
79 FROM usertable
This could be a more simple solution:
INSERT INTO usertable(column1, column2)
SELECT IFNULL(MAX(column1)+1,1),79 FROM usertable
Lets try this once (not tested)
INSERT INTO table(column1) SELECT count(column1)+1 FROM table
For ex,
INSERT INTO table(column1, column2) SELECT count(column1)+1, 79 FROM table
if you want the auto value of column1, don't set it, just let it get a defult value
INSERT INTO table (column2) values(?)
Related
I am using jdbcTemplate to write data to my Oracle DB. I would like to reuse my code for the same table but in two different enviroments and the difference between these two enviroments is only one column missing. So before writing the data I need to check if the column is there or not to use the correct sql query, other I will get an exception. So I would like to have something like:
if(column3IsMissing){
String sql = String.format("insert into %s %s", MYTABLE,
"(column1, column2) values (?, ?)");
}else{
String sql = String.format("insert into %s %s", MYTABLE,
"(column1, column2, column3) values (?, ?, ?)");
}
jdbcTemplate.batchUpdate(sql, data, types);
Can anyone give me hint how should I implement the column3IsMissing check here? Thank you very much in advanced!
Oracle offer three different views to get table columns information: ALL_TAB_COLUMNS, USER_TAB_COLUMNS and DBA_TAB_COLUMNS.
You can run query like below with JDBC, to confirm if column exists before running your insert query.
select column_name from ALL_TAB_COLUMNS where TABLE_NAME = 'MYTABLE';
In order to get check the columns size. put all your column into array and check if
columnSize = 2.
String[] columnList = {column1,column2,column3);
if(columnList.size()==2){
String sql = String.format("insert into %s %s", MYTABLE,
"(column1, column2) values (?, ?)");
}else{
String sql = String.format("insert into %s %s", MYTABLE,
"(column1, column2, column3) values (?, ?, ?)");
}
jdbcTemplate.batchUpdate(sql, data, types);
I have a database called college with two tables; Students and Courses. Course_fk is a foriegn key of the primary key in Courses table. Now in my query for saving data, i am expecting the Course_fk to be have the id of the primary key in Courses table whenever data is saved into Courses table.
I am running a multiple query (i.e entering data into Students and Courses table at the same time) But i get an error saying "Course_fk doesn't have any default value".
Students
ID
Name
Course_fk
Courses
ID
Course_Name
Query to save data
String sql = "Insert into Students(Name) values (?)";
String query = "Insert into Guardians(Course_Name) values (?) ";
try{
pst1 = conn.prepareStatement(query);
pst1.setString(1, course_name.getText());
pst1.execute();
pst = conn.prepareStatement(sql);
pst.setString(1, name.getText());
pst.execute();
Based on your information I think that this insert will work for you:
INSERT INTO students (course_fk)
SELECT id FROM courses WHERE course_name = "coursename";
I did not check this in MySQL database.
I am trying to retrieve the generated key for an insert statement to an Oracle database. I'm using a PreparedStatementSetter with the jdbcTemplate. I've read the other StackOverflow post on this topic here, but the answer basically proposes moving away from StatementSetters. Is there a way to retrieve the key while using a PreparedStatementSetter? The documentation on using PreparedStatementSetters to retrieve keys is surprisingly sparse.
Here's my jdbcTemplate update statement:
statementSetter.setUpdatedBy(...);
statementSetter.setFileStatus(...);
statementSetter.setCompany(...);
int modifiedCount = jdbcTemplate.update(sql, statementSetter);
Here's my SQL string:
database.insertFileControlRecordQuery = INSERT INTO MY_TABLE \
(PRIMARY_KEY_FIELD, FIELD2, FIELD3,...) VALUES (MY_TABLE_SEQ.NEXTVAL, ?,?, ...)
Using a NEXTVAL as suggested in comments is potentially hazardous: if some other process does an insert and commit in between you fetching the NEXTVAL and committing your insert, you'll have a different key than what you assumed.
Instead, I would suggest using the update-function which has provisions for returning a key, i.e. ...
JdbcTemplate.update(PreparedStatementCreator, KeyHolder);
... from which you can determine the key.
An example to illustrate:
String insertQuery="INSERT INTO MY_TABLE (FIELD1, FIELD2) " +
"VALUES (?, ?)";
KeyHolder keyHolder = new GeneratedKeyHolder();
PreparedStatementCreator preparedStatementCreator = connection -> {
PreparedStatement preparedStatement = connection.prepareStatement(insertQuery, new String[]{"PRIMARY_KEY_FIELD"});
preparedStatement.setString(1, field1);
preparedStatement.setDate(2, field2);
return preparedStatement;
};
jdbcTemplate.update(preparedStatementCreator, keyHolder);
Number primaryKey = keyHolder.getKey();
Note that the setting of the column which holds the primary key upon creating the PreparedStatement is essential for Oracle! Without it, you'll be getting the ROWID instead.
I have a jinternal frame form with textfields. I am entering name and no to these textfields. I need to insert these data into my database table addstudents. In addstudent table there are more columns not only no and name column.
So I need to type select query inserting textfield data into selected columns.
String n = no.getText();
String nm = name.getText();
select no,name from addstudent insert into...
i can't find how to insert data to selected columns of the db table..
Please help me
Use a SQL INSERT statement, and use a Java PreparedStatement:
String n = no.getText();
String nm = name.getText();
String sql = "INSERT INTO addstudent ( no, name )" +
" VALUES ( ?, ? )";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, n);
stmt.setString(2, nm);
stmt.executeUpdate();
}
Hi
I have a code for table creating:
create table clt (id bigint not null, sources set('A1', 'empty', 'A2', 'A3'), text varchar(50));
table was created successfully.
now I'm trying to insert data:
java.sql.PreparedStatement stmt = null;
String query = "insert into clt (id, sources, text) values (?, ?, ?)";
stmt = conn.prepareStatement(query);
int it = 0;
stmt.setLong(++it, 25);
stmt.setString(++it, "A1, A2");
stmt.setString(++it, "some text data");
stmt.executeUpdate();
and gettting an error :(
exception: java.sql.SQLException: Data truncated for column 'sources' at row 1
without sources everything is ok.
where is my mistake?
thank you.
Get rid of the parentheses around A1:
stmt.setString(++it, "A1");