I have simple program that works with mysql db. I need to switch to oracle db.
I am trying to insert data into database but I'm getting this error. I tried manually to insert data everyting is fine but programatically I got error.
This is my code.
public void saveHasta(List<Hasta> hastaList) {
try {
// PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID) VALUES (12345678912, 'Mert', 'Akel', '1995-07-21', 'Yazilim', 2)");
//
// System.out.println("Oldu");
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID) VALUES (?,'?','?','?','?',?)");
Iterator<Hasta> it = hastaList.iterator();
while (it.hasNext()) {
Hasta h = it.next();
stmt.setLong(1, h.getTcKimlik());
stmt.setString(2, h.getIsim());
stmt.setString(3, h.getSoyIsim());
stmt.setString(4, h.getDogumTarih());
stmt.setString(5, h.getMeslek());
PreparedStatement pst = connection.prepareStatement(
"SELECT randevu_ID FROM tblRandevu where tc_kimlik = '" + h.getTcKimlik() + "'");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
randevu_id = rs.getInt("randevu_ID");
}
stmt.setInt(6, randevu_id);
stmt.addBatch();
}
stmt.executeUpdate();
System.out.println("Oldu");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is my table
CREATE TABLE tblhasta
( hasta_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL,
hasta_tc_kimlik INTEGER,
hasta_isim varchar2(50),
hasta_soyisim varchar2(50),
hasta_dogum_tarih varchar2(50),
hasta_meslek varchar2(50),
randevu_ID INTEGER,
CONSTRAINT hasta_pk PRIMARY KEY (hasta_ID)
);
You have used the prepared statements in a wrong way
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID)
VALUES (?,'?','?','?','?',?)");
Change values to
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID)
VALUES (?,?,?,?,?,?)");
Related
I created a table in Mysql using
Create table
(
id int auto_increment,
us varchar(100),
ps varchar(1000)
);
And used java for adding values thru my GUI application:
I used the following method to add values into my database:
public static void Mysql(String u, String p) throws NoSuchAlgorithmException, InvalidKeySpecException
{
String hashpass=passhash(p);//throws declaration for this statement
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (id,us,ps)"
+ " values (?,?, ?)";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
int id=0;
while(rs.next())
{
id= rs.getInt(1);
}
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setInt(1, id++); //I don't want this method because id is auto increment
preparedStmt.setString(2,u);
preparedStmt.setString(3,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){ System.out.println(e);}
}
Everything works fine
But the id is the auto_increment and I don't need to add value to id while adding other column values.
I can't add like that while adding thru java like only adding us, ps columns and the id will be automatically incremented.
Are there any methods to add data without passing the parameters?
Remove the column id from the sql statement:
String query = "insert into login (us, ps) values (?, ?)";
and don't set any value for it in the prepared statement, so remove this line:
preparedStmt.setInt(1, id++);
The column id is auto_inrement so its value will be set by MySql.
Of course change the indices of the other lines to 1 and 2:
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
You might insert data without ID as it will be auto-generated from SQL
public static void Mysql(String u,String p) throws NoSuchAlgorithmException, InvalidKeySpecException {
String hashpass=passhash(p);
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (us,ps) values (?, ?)"; // CHECK HERE
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){
System.out.println(e);}
}
}
I want to insert the product the user selected into a table called cart which has two columns: cart_id and item_id_FK both are foreign keys. User_id and id are passed in the constructor and then inserted into cart_id and item_id_fk.
No errors are showing in the code, I double checked the connection username and password, everything works fine except for the cart table.
I tried putting a try and catch statement inside and repeating the steps it didn't work.
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch
Change executeQuery to executeUpdate:
executeQuery(sql3)
to
executeUpdate(sql3)
I believe integers don't need the ' ' around them to be inserted, you may try removing those as well. It may be mistaking them as characters or something similiar.
Otherwise if neither of those above fixes work, try something like this:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
I'm having an issue with adding data to a sql database through Java on Netbeans.
String bladeSerial;
String bladeType;
LocalTime startTime1;
private void startButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection ("jdbc:derby://localhost:1527/db01", "Administrator", "admin"); //run procedure getConnection to connect to the database - see below
st = conn.createStatement(); //set up a statement st to enable you to send SQL statements to the database.
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println ("Successful Connection");
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ('+bladeSerial+', '+itemText+', '+(String.valueOf(startTime1))+')";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
I get the error The column position '1' is out of range. The number of columns for this ResultSet is '0'.
In the database, Serial is VARCHAR(5), Bladetype is VARCHAR(80)and StartT1 is VARCHAR(12)
The startTime1 variable is saved in the format HH:mm:ss.SSS.
I appreciate any help on this error
You need to give placeholder in your query. Change your code as given here...
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
You don't need to give column names in query when you are using Prepared statement. Do the following changes:
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
Hope it helps!!
Here you are forming query like simple statement and used it in prepared statement which is not possible, so change your query with place holder like below.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
If you want to directly use variables names like bladeSerial, then you should use these String variables as if you're adding multiple Strings.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ("+bladeSerial+", "+itemText+", "+(String.valueOf(startTime1))+")";
But this is strictly not recommended as it would introduce serious security issues.
The recommended way is to use PreparedStatement. The query you've written is correct, it's just that you have to use placeholders instead of variable names.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
// Exception handling
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
There is a mysql table with primary key as id int auto_increment,
I need to insert multiple rows in batch with multiple insert statement, with autocommit disabled, as following:
SET autocommit=0;
INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', 1, NOW());
INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', 2, NOW());
COMMIT;
Is it possible to get each generated id, instead of only the last id.
If yes, when was each id generated, and how to get all the ids via jdbc?
Thx.
If you want to retrieve the AUTO_INCREMENT keys via JDBC you need to use the JDBC features for doing so (RETURN_GENERATED_KEYS and .getGeneratedKeys()), like this:
try (Connection conn = DriverManager.getConnection(myConnectionString, "root", "beer")) {
try (Statement st = conn.createStatement()) {
st.execute(
"CREATE TEMPORARY TABLE dummy (" +
"`id` INT AUTO_INCREMENT PRIMARY KEY, " +
"`NAME` VARCHAR(50), " +
"`size` INT, " +
"`create_date` DATETIME " +
")");
}
conn.setAutoCommit(false);
System.out.println("AutoCommit is OFF.");
String sql = "INSERT INTO dummy(NAME, `size`, create_date) VALUES('test', ?, NOW())";
try (PreparedStatement ps = conn.prepareStatement(
sql,
PreparedStatement.RETURN_GENERATED_KEYS)) {
// first batch
ps.setInt(1, 1); // `size` = 1
ps.addBatch();
ps.setInt(1, 2); // `size` = 2
ps.addBatch();
ps.executeBatch();
System.out.println("First batch executed. The following AUTO_INCREMENT values were created:");
try (ResultSet rs = ps.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1));
}
}
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
conn.rollback();
System.out.print("Transaction rolled back. ");
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
// second batch
ps.setInt(1, 97); // `size` = 97
ps.addBatch();
ps.setInt(1, 98); // `size` = 98
ps.addBatch();
ps.setInt(1, 99); // `size` = 99
ps.addBatch();
ps.executeBatch();
System.out.println("Second batch executed. The following AUTO_INCREMENT values were created:");
try (ResultSet rs = ps.getGeneratedKeys()) {
while (rs.next()) {
System.out.println(rs.getInt(1));
}
}
}
try (Statement st = conn.createStatement()) {
sql = "SELECT COUNT(*) AS n FROM dummy";
try (ResultSet rs = st.executeQuery(sql)) {
rs.next();
System.out.println(String.format("The table contains %d row(s).", rs.getInt(1)));
}
}
}
... which produces the following console output:
AutoCommit is OFF.
First batch executed. The following AUTO_INCREMENT values were created:
1
2
The table contains 2 row(s).
Transaction rolled back. The table contains 0 row(s).
Second batch executed. The following AUTO_INCREMENT values were created:
3
4
5
The table contains 3 row(s).
I tried to save / edit / delete a new row in the database. writing in the gui values to be saved with getText ()
here is the code
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql;
sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (txt_isbn, txt_disp, txt_titolo, txt_casa, txt_autore, txt_genere, txt_prezzo)";
stmt = conn.createStatement();
emps = stmt.executeQuery(sql);
String ISBN= txt_isbn.getText();
String DISPONIBILITA= txt_disp.getText();
String TITOLO= txt_titolo.getText();
String CASA_EDITRICE= txt_casa.getText();
String CODICE_AUTORE= txt_autore.getText();
String GENERE= txt_genere.getText();
String PREZZO = txt_prezzo.getText();
JOptionPane.showMessageDialog(null, "SALVATO");
}catch(SQLException | HeadlessException e)
{
JOptionPane.showMessageDialog(null, e);
}
finally
{
try{
if (emps != null)
emps.close();
}
catch (SQLException e) { }
try
{
if (stmt != null)
stmt.close();
}
catch (SQLException e) { }
}
Getting this error: column not allowed here
Above code just takes care of insert operation. How can I delete and modify table record?
You have asked 2 different questions here
1. Column not allowed here
This happened because you have not passed values for any of parameter into insert statement.
I am not sure about your requirement however I will use PreparedStatement for this scenario.
Example
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "MindPeace");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
preparedStatement .executeUpdate();
2. This code is only to save the data, delete, and modify an entire row how can I do?
Answer is very simple. You have to write code for the same :)
You need 3 SQL statement which has DELETE and UPDATE operation just like insert in above example.
String sql = "INSERT INTO PROGETTO.LIBRO (ISBN, DISPONIBILITA, TITOLO, "
+ "CASA_EDITRICE, CODICE_AUTORE, GENERE, PREZZO)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.createStatement()) {
NumberFormat numberFormat = NumberFormat.getInstance(Locale.ITALY);
String ISBN = txt_isbn.getText();
String DISPONIBILITA = txt_disp.getText();
String TITOLO = txt_titolo.getText();
String CASA_EDITRICE = txt_casa.getText();
String CODICE_AUTORE = txt_autore.getText();
String GENERE = txt_genere.getText();
BigDecimal PREZZO = new BigDecimal(
numberFormat.parse(txt_prezzo.getText()).doubleValue())
.setScale(2);
stmt.setString(1, ISBN);
stmt.setString(2, DISPONIBILITA);
stmt.setString(3, TITOLO);
stmt.setString(4, CASA_EDITRICE);
stmt.setString(5, CODICE_AUTORE);
stmt.setString(6, GENERE);
stmt.setBigDecimal(7, PREZZO);
int updateCount = stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "SALVATO");
} catch(SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
Try-with-resources closes the stmt automatically.
The prepared statement replaces the value in the SQL with something like:
INSERT INTO table(column1, colum2, ....)
VALUES('De\'l Rey',
1234.50,
...)
for:
"De'l Rey"
1.234,50
updateCount should be 1 on success.
Wooow..true!!
I created three buttons to delete / update / insert and now it all works and automatically updates the tables.
you've been very very great. Thank you very much.
one last thing.
if I wanted to insert an error message when I delete / update etc "book not found" I tried to create an if:
Boolean found = false;
try{
sql= delete......
etc
if (!found)
JOptionPane.showMessageDialog(null, "NOT FOUND","ERRORE",JOptionPane.WARNING_MESSAGE);
etc...
Connection conn = Connessione.ConnecrDb();
Statement stmt = null;
ResultSet emps = null;
try{
String sql= "DELETE FROM progetto.libro WHERE isbn =?"; /
pst=(OraclePreparedStatement) conn.prepareStatement(sql);
pst.setString (1, txt_isbn.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "ELIMINATO");
Update_table();
txt_isbn.setText("");
txt_disp.setText("");
txt_titolo.setText("");
txt_casa.setText("");
txt_autore.setText("");
txt_genere.setText("");
txt_prezzo.setText("");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
if you find the book must exit the book removed, or "not found". but as I deployed I always come out "deleted". why?
thanks again