Good day!
In order to access the mysql server, I used the JConnect and my code is as follows:
public AddBooks() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/catalog";
conn = DriverManager.getConnection(url,"root","upittc");
stmt = conn.prepareStatement("INSERT INTO books VALUES(?,?,?,?,?,?,?,?,?,?,)");
} catch (Exception exc) {
JOptionPane.showMessageDialog(null, exc.getMessage());
}
initComponents();
}
To put the data in the database, I used the following code:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
stmt.setString(1, jTextField0.getText());
stmt.setString(2, jTextField1.getText());
stmt.setString(3, jTextField2.getText());
stmt.setString(4, jTextField3.getText());
stmt.setString(5, jTextField4.getText());
stmt.setString(6, Jan2.getSelectedItem().toString());
stmt.setString(7, Jan3.getSelectedItem().toString());
stmt.setString(8, jTextField5.getText());
stmt.setString(9, jTextField6.getText());
stmt.setString(10, jTextField8.getText());
stmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Save Successful!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
But there's an error on row 1. COLUMN COUNT DOESN'T MATCH THE VALUE AT ROW What does it mean?
Please advise. Thank you.
If the field is auto-increment, you should not assign anything to it, remove it from your SQL prepared statement string and just set everything else, the auto increment will do the job by itself.
PreparedStatement stmt = connect.prepareStatement("INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) ");
get rid of first column to have:
PreparedStatement stmt = connect.prepareStatement("INSERT INTO table_name (column2, column3,...) VALUES ( value2, value3,...) ");
and replace values with question marks and set them as you do later on.
stmt.setString(1, jTextField1.getText());
stmt.setString(2, jTextField2.getText());
stmt.setString(3, jTextField3.getText());
stmt.setString(4, jTextField4.getText());
stmt.setString(5, Jan2.getSelectedItem().toString());
stmt.setString(6, Jan3.getSelectedItem().toString());
stmt.setString(7, jTextField5.getText());
stmt.setString(8, jTextField6.getText());
stmt.setString(9, jTextField8.getText());
stmt.executeUpdate();
NOTICE: decremented indices (the number of the question mark value).
Hope that helps!
Related
public boolean findCongDan(String socancuoc) throws SQLException {
CongDan congdan = new CongDan();
openDatabase();
String sqlFind = "Find From CongDan Where SoCanCuoc = ?";
PreparedStatement stmt = jdbcConnection.prepareStatement(sqlFind);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
stmt.setString(1, socancuoc);
stmt.setString(2, congdan.getHoTen());
stmt.setString(3, congdan.getDiaChi());
stmt.setString(4, congdan.getGioiTinh());
stmt.setString(5, congdan.getNgaySinh());
stmt.setString(6, congdan.getDanToc());
stmt.setString(7, congdan.getTonGiao());
stmt.close();
}
closeDatabase();
int rowFind = stmt.executeUpdate();
return rowFind>0;
}
You didn't provide parameters for your query before executing it. You have to call setString on your prepared statement before calling executeQuery
Every ? in the query string needs to be provided in the stmt.executeQuery():
ResultSet rs = stmt.executeQuery("search value");
effectively making the query like this:
Find From CongDan Where SoCanCuoc = 'search value';
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 (?,?,?,?,?,?)");
Hello everyone can someone tell me what is wrong here ?
I have a task i was asked and i am new in connecting oracle databases with java servlet.
here is me code:
try {
out.print("first");
Class.forName("oracle.jdbc.OracleDriver");
out.print("aaa");
Connection con
= DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "myusername", "mypassword");
out.print("111");
PreparedStatement ps = con
.prepareStatement(
"INSERT INTO signup
values(fn, ln, date, em, pa, crnum)
");
out.print("222");
ps.setString(1, fn);
ps.setString(2, ln);
ps.setString(3, da);
ps.setString(4, em);
ps.setString(5, pa);
ps.setString(6, cr);
int i = ps.executeUpdate();
if (i > 0) {
out.print("You are successfully registered...");
}
} catch (Exception e2) {
out.println(e2);
}
out.close();
response.sendRedirect("address");
/* when press next bottom
it'll take me to add.html*/
and after i ran the whole code i get this :java.sql.sqlexception: invalid column index
In your SQL statement, you have to provide the tokens or placeholders for your bind variable like in the following...
PreparedStatement ps = con.prepareStatement("INSERT INTO signup values(?,?,?,?,?,?)");
ps.setString(1,fn);
ps.setString(2,ln);
ps.setString(3,da);
ps.setString(4,em);
ps.setString(5,pa);
ps.setString(6,cr);
You need to use placeholder ?:
PreparedStatement ps = con.prepareStatement("INSERT INTO signup values (?,?,?,?,?,?)");
i have to insert data into database .Because sql statement VALUES(......) have 8 parameters . Is it proficient way to use insert statement ?
Class UserRegistration {
public void insertToDatabase(){
String sql=" INSERT INTO db1(......) Values(id,fname,lastname,username,password,usertype,email,contact,address )"
}
}
The correct way to do it in Java, assuming you're using JDBC, is to use a PreparedStatement.
String sql = "INSERT INTO db1" +
" (id,fname,lastname,username,password,usertype,email,contact,address)" +
" VALUES (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt (1, id);
stmt.setString(2, fname);
stmt.setString(3, lastname);
stmt.setString(4, username);
stmt.setString(5, password);
stmt.setString(6, usertype);
stmt.setString(7, email);
stmt.setString(8, contact);
stmt.setString(9, address);
stmt.executeUpdate();
}
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