java.sql.sqlexception invalid column index - java

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 (?,?,?,?,?,?)");

Related

PreparedStatement: executeUpdate insert wrongly the raw

I try the below code: once just does not work, and when make Auto incremental the primary key it works, but bring the raw doubled.
At this point I guess it' s something stupid, so if an idea, I will be grateful.
try {
String insertSQL = "INSERT INTO `news`( `title`, `date`, `description`) VALUES (?,?,?)";
PreparedStatement ps = DBUtils.getPreparedStatement(insertSQL);
ps.setString(1, n.getTitle());
ps.setString(2, n.getDate());
ps.setString(3, n.getDescription());
if (ps.executeUpdate() > 0) {
ps.executeUpdate();
System.out.println("DB updtata!");
}
} catch (ClassNotFoundException |SQLException ex) {
ex.printStackTrace();
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
};
Try this in try catch block..
String insertSQL = "INSERT INTO `news`( `title`, `date`, `description`) VALUES(?,?,?)";
PreparedStatement ps = DBUtils.getPreparedStatement(insertSQL);
ps.setString(1, n.getTitle());
ps.setString(2, n.getDate());
ps.setString(3, n.getDescription());
int rs = ps.executeUpdate();
if (rs > 0) {
System.out.println("DB updated!");
}

Syntax for SQL statement using mysql database

public void insertTags(Elements[] elements) {
Connection con = (Connection) DbConnection.getConnection();
try {
String sql = "insert into htmltags(source) values(?),(?),(?)";
PreparedStatement ps = (PreparedStatement) con.prepareStatement(sql);
ps.setString(1, elements[0].toString());
ps.setString(2, elements[1].toString());
ps.setString(3, elements[2].toString());
int rs = ps.executeUpdate(sql);
System.out.println("Data inserted" + rs);
} catch (SQLException e) {
e.printStackTrace();
}
}
is this a valid syntax for Prepared statement.
This is your problem:
int rs = ps.executeUpdate(sql);
From the JavaDoc we see that PreparedStatement#executeUpdate() does not take any parameters. The reason is that we already passed the query earlier when preparing the statement. Your code should be this:
int rs = ps.executeUpdate(); // no parameter
Also no need to cast the result of prepareStatement to PrepareStatement
To insert multiple values, I don't thing using values(?),(?),(?) is the right syntax, instead use a loop, or for better way you can use batch :
String sql = "insert into htmltags(source) values(?)";
try (PreparedStatement ps = con.prepareStatement(sql);) {
for (Elements element : elements) {
ps.setString(1, element.toString());
ps.addBatch();//Add a new batch for each Element
}
int[] result = ps.executeBatch();//Submits a batch of commands to the database
} catch (SQLException e) {
e.printStackTrace();
}

What is "java.sql.SQLException: No value specified for parameter 1 "?

I don't know what is wrong with my code below.
try {
String sql = "INSERT INTO `myporject`.`selectnation` (`nations` ,`package` ,`persons`) "
+ "VALUES ('?', ?, ?)";
PreparedStatement ps = connect.prepareStatement(sql);
if (ps.executeUpdate() != -1) {
ps.setString(1,"Japan" );
ps.setInt(2, this.pack);
ps.setString(3, jTextField1.getText());
And this is StackTrace
java.sql.SQLException: No value specified for parameter 1
You are trying to execute the prepareStatement before setting the parameters, so you need to change your code as follows:
PreparedStatement ps = connect.prepareStatement(sql);
//set the parameters first
ps.setString(1,"Japan" );
ps.setInt(2, this.pack);
ps.setString(3, jTextField1.getText());
//now execute the prepared statement
if (ps.executeUpdate() != -1) {
//add your code
}
I suggest you refer here to understand the jdbc concepts.

Speeding up sql inserts on postgresql with JDBC?

I have two methods below for checking if a match is in the database and if not if would call the insert method. My program has to go through thousands of rows and it takes a very long time. Am I doing this incorrectly? Anything I can do to significantly make this faster?
public Boolean isMatchIdInDatabase(String matchId) throws SQLException
{
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
Boolean exists = false;
try
{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, props);
pst = conn.prepareStatement("SELECT COUNT(*) FROM match where match_id = ?");
pst.setString(1, matchId);
rs = pst.executeQuery();
while (rs.next())
{
exists = rs.getBoolean(1);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
pst.close();
rs.close();
conn.close();
}
return exists;
}
public Boolean insertMatchId(String matchId, String name, Timestamp birthdate, String bio, String accountId) throws SQLException, ClassNotFoundException
{
Connection conn = null;
PreparedStatement pst = null;
Boolean exists = false;
try
{
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(url, props);
pst = conn.prepareStatement("INSERT INTO match (match_id, name, birthdate, bio, account_id) values(?, ? , ?, ?, ?)");
pst.setString(1, matchId);
pst.setString(2, name);
pst.setTimestamp(3, birthdate);
pst.setString(4, bio);
pst.setString(5, accountId);
pst.executeUpdate();
}
finally
{
pst.close();
conn.close();
}
return exists;
}
Are you calling first isMatchIdInDatabase then insertMatchId for many records?
Possible duplicate: Efficient way to do batch INSERTS with JDBC
It is an expensive operation to open a connection and query for a single record. If you do that thousands of times, it gets very slow. You should try to restructure your query so that you only use one SELECT. Then you can collect the records which you have to insert and doing it with batch insert.
You could try changing your SQL query that inserts the row to insert only if the row isn't in the database by using WHERE NOT EXISTS.
This post seems to be relevant - I know it's for MySQL instead of PostgreSQL but the principles should be the same.
MySQL Conditional Insert

column not allowed here oracle with getText

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

Categories

Resources