JDBC INSERT not working - java

I am just trying to insert a new row in a table from a java application to an SQL database. I have used the same code before and it worked but for some reasons this doesn't. I have checked my query by inserting it directly in phpmyadmin and it works. Here is my code:
where I actually try to sent the query:
static Connection conn = MySQLAccess.connectDB();
static PreparedStatement pst = null;
static ResultSet rs = null;
public static String submit(String usrn, String psw){
String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
try {
pst = conn.prepareStatement(sql);
System.out.println(sql);
rs=pst.executeQuery();
if (rs.next()){
return "ok";
} else {
return "fail";
}
} catch (Exception e){
return "fail_connection";
}
}
MySQLAccess.java (which I am sure works because I use is at other points in the code):
public class MySQLAccess {
Connection conn=null;
public static Connection connectDB (){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/g52gui","root","");
return conn;
}catch(Exception e){
return null;
}
}
}
I have just changed my code (suggestion of Luiggi Mendoza) but no result:
public static String submit(String usrn, String psw){
//String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
String sql = "INSERT INTO tbl_user VALUES('', '?', '?')";
String result = "failed";
try (Connection conn = MySQLAccess.connectDB();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, usrn);
pst.setString(2, psw);
pst.executeUpdate();
result = "worked";
} catch (SQLException e) {
//handle your exception...
}
return result;
}

Three issues:
Use PreparedStatement#executeUpdate rather than PreparedStatement#executeQuery.
Keep the variables in the narrowest possible scope. Don't set them as static variables in your class.
Don't concatenate the parameters into the query string. Instead, use PreparedStatement#setXyz method to set the proper parameter.
Gluing all of these together produces the following code:
public static String submit(String usrn, String psw){
//String sql = "INSERT INTO tbl_user VALUES('', '"+usrn+"', '"+psw+"')";
String sql = "INSERT INTO tbl_user VALUES('', ?, ?)";
String result = "failed";
try (Connection conn = MySQLAccess.connectDB();
PreparedStatement pst = conn.prepareStatement(sql)) {
pst.setString(1, usrn);
pst.setString(2, psw);
pst.executeUpdate();
result = "worked";
} catch (SQLException e) {
//handle your exception...
}
return result;
}
From your new code, the problem is here:
String sql = "INSERT INTO tbl_user VALUES('', '?', '?')";
^ ^ ^ ^
You're wrapping the parameter character ? with quotes '. Remove such quotes, as shown in my code:
String sql = "INSERT INTO tbl_user VALUES('', ?, ?)";
//No quotes around ?

You should use executeUpdate and not executeQuery;

Related

How to fix "Declaration, final or effectively final variable expected" in a PreparedStatement.setString

The problem is that I am trying to set a wild card in a PreparedStatement but the setString statement is giving me the error above.
I have tried changing it to a setObeject statement with multiple different types like Types.VARCHAR. I have tried declaring the PreparedStatement in different places, and I have tried declaring 'name' in the method and in the class.
public String getTemplateText(String name) {
try (
Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT templateText FROM TEMPLATE WHERE " +
"templateTag = ?");
stmt.setString(1 , name); // this is the line that has the problem!
ResultSet rs = stmt.executeQuery()
) {
System.out.println("Set Text...");
String tempText = rs.getString("templateText");
return tempText;
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}
/* this is the SQL code for the table that I am trying to query */
CREATE TABLE TEMPLATE
(
templateID INTEGER PRIMARY KEY IDENTITY(1,1)
, templateText TEXT
, templateTag CHAR(25)
);
You can't set the stmt parameter in your try-with-resources (because binding the parameter is void and not closable). Instead, you can nest a second try-with-resources after you bind the parameter. Like,
public String getTemplateText(String name) {
try (Connection conn = getConnection();
PreparedStatement stmt = conn
.prepareStatement("SELECT templateText FROM TEMPLATE WHERE " +
"templateTag = ?")) {
stmt.setString(1, name);
try (ResultSet rs = stmt.executeQuery()) {
System.out.println("Set Text...");
String tempText = rs.getString("templateText");
return tempText;
}
} catch (SQLException e) {
e.printStackTrace();
}
return "";
}

Using ResultSet to return string value from database but method skips the "Try" clause?

Why is my following code:
PrintWriter pw = response.getWriter();
pw.println(getValueOf(SQL, "lastName");
not printing anything after passing it into my method:
public static String getValueOf(String sql, String colName)
{
String result = "";
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
result = rs.getString(colName);
conn.close();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
In other words, why does it seem to be skipping the "try" clause entirely and just jumping to return the empty "" result at the end?
My SQL statment:
String SQL = "SELECT lastName FROM customers WHERE firstName=\"Bob\";";
I do have an entry for the person "Bob" (his lastname is "Mike") in my Customers table.
My Customers Table:
lastName / firstName / address / email
EDIT
It works correctly if I change the return type to "void" but I actually need a String value.
Alternate code:
public static void getValueOf(String sql, String colName, PrintWriter pw)
{
try
{
Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next())
pw.println(rs.getString(colName)); // This does print out to the webpage as "Mike"
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Based upon your last edit, I would guess that you have more than one records.
So change your code to
if (rs.next()) {
result = rs.getString(colName);
}
And also, your code does not skip that try block

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

SQL Syntax Error in Java

I am developing an application with java on netbeans/windows 7. I was trying to insert data to database with PreparedStatement using SQL. So this is my code;
private void addInfoActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn;
PreparedStatement pst;
String url = "jdbc:derby://localhost:1527/records";
String SQL_INSERT = "INSERT INTO records"+
"VALUES(?,?,?)";
String name, surname, number;
try {
conn = DriverManager.getConnection(url, "system", "app");
System.out.println("connected to db");
pst = conn.prepareStatement(SQL_INSERT);
name = nameField.getText();
surname = surnameField.getText();
number = numberField.getText();
System.out.println("got data from textfields");
pst.setString(1, name);
pst.setString(2, surname);
pst.setString(3, number);
System.out.println("variables set");
pst.executeUpdate();
System.out.println("sql command executed");
pst.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(addition.class.getName()).log(Level.SEVERE, null, ex);
}
}
But I got an error like this;
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "?" at
line 1, column 27.
Name of my table is records and it has three coloumns named; name, surname and number. As I can understand from the println lines, there is a problem with that line;
pst = conn.prepareStatement(SQL_INSERT);
or maybe I created SQL_INSERT string and SQL code wrong. I couldn't figure out what is the problem exactly.
You're missing a space in
String SQL_INSERT = "INSERT INTO records"+
"VALUES(?,?,?)";
When you do the concatenation, it produces "INSERT INTO recordsVALUES(?,?,?)"
Change it to
String SQL_INSERT = "INSERT INTO records"+
" VALUES(?,?,?)";

Categories

Resources