I am writing a database program. But I am stuck with the Java prepared statement. The prepared statement doesn't seems to be working. I spend several hours to make it work but still same result.
String sql = "INSERT into EDMSDATABASE.MESSAGE (title, subject, description, deadline) VALUES (?, ?, ?, ?)";
try (
PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
) {
statement.setString(1, bean.getTitle());
statement.setString(2, bean.getSubject());
statement.setString(3, bean.getDescription());
statement.setString(4, bean.getDeadline());
int affectedRow = statement.executeUpdate();
if(affectedRow == 1) return "Success";
} catch (SQLException e)
{
} finally{
}
Note that bean is a parameter
Are you using 1.7 . If not please use version compatible logic.
Related
How do I check if the statement can execute in my code? the second parameter won't be set if txtFirstName.getText() is empty.
String sql = "INSERT INTO Employees (id, firstName, lastName, adress, phone, email, photo, comments) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement statement = database.connection.prepareStatement(sql);
statement.setString(1, database.users.size() + 1 + "");
if (txtFirstName.getText().matches(""))
statement.setString(2, txtFirstName.getText());
statement.setString(3, txtLastName.getText());
statement.setString(4, txtAdress.getText());
statement.setString(5, txtPhone.getText());
statement.setString(6, txtEmail.getText());
statement.setString(7, txtPhotoURL.getText());
statement.setString(8, txtComment.getText());
statement.executeUpdate();
the second parameter won't be set if txtFirstName.getText() is empty.
Yes, it will; it will be set to an empty string. Whether that's valid for this specific query and table structure is beyond the realm of JDBC.
You need to check your constraints in advance, separately, and then either make the call or not.
You need an else condition to specify what to do if txtFirstName does not match the pattern, e.g.:
if (txtFirstName.getText().matches("")){
statement.setString(2, txtFirstName.getText());
}else {
throw new IllegalArgumentException("Invalid name pattern");
}
This will prevent the code from executing errorneous preparedstatement and throw an exception with appropriate error message.
I have an "Invitation" object that is modeled in a MySQL database. This object has one list ("treatmentPlanIDsToCopyf") and is maintained in the database with a second table. The method I have written to insert into the main table and then loop through the list and insert records for each item in the list into the second table is below. At the line ps = cn.prepareStatement(sql);Eclipse is giving me a warning that says "Resource leak: 'ps' is not closed at this location". I am closing the prepared statement in the finally clause, so I wanted to know if there really is a resource leak I need to fix. This is my first time using batches with prepared statements, so I wasn't really sure. Thanks.
public void invitationCreate(Connection cn, Invitation invitation) throws SQLException{
PreparedStatement ps = null;
try {
//first insert primary invitation data into the invitation table
String sql = "INSERT INTO invitiation (invitation_code, recipient_email, sender_user_id_fk, date_intived, date_accepted, accepted, recipient_first_name, recipient_last_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
ps = cn.prepareStatement(sql);
ps.setString(1, invitation.getInvitationCode());
ps.setString(2, invitation.getRecipientEmail());
ps.setInt(3, invitation.getSenderUserID());
ps.setTimestamp(4, convertLocalTimeDateToTimstamp(invitation.getDateInvited()));
ps.setTimestamp(5, convertLocalTimeDateToTimstamp(invitation.getDateAccepted()));
ps.setBoolean(6, invitation.isAccepted());
ps.setString(7, invitation.getRecipientFirstName());
ps.setString(8, invitation.getRecipientLastName());
int success = ps.executeUpdate();
//now loop through all the treatmentPlanIDs in the invitation that are to be copied into the invitees account when the register
sql = "INSERT INTO invitation_treatment_plans (invitation_code_fk, invitation_treatment_plan_id_fk) VALUES (?, ?)";
ps = cn.prepareStatement(sql);//TODO confirm this if this is actually a resource leak
for(int treatmentPlanID : invitation.getTreatmentPlanIDsToCopy()){
ps.setString(1, invitation.getInvitationCode());
ps.setInt(2, treatmentPlanID);
ps.addBatch();
}
ps.executeBatch();
} finally {
DbUtils.closeQuietly(ps);
}
}
I believe the leak is in the first prepared statement.
After int success = ps.executeUpdate(); you need to close that prepared statement before you assign the variable to a new prepared statement.
So far I have been able to insert data into my SQL table only when i declare values inside the executedUpdate statement. What I wanted to know if there is a way that I can pass those values as variables that I will declare as parameters in the executing method like so:
public void updateSQL(String name, String dnsName, String ipV4, String ipV6, int statusCode)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection("jdbc:sqlserver://servername;database=databasename;integratedSecurity=true");
System.out.println("Database Name: " + connection.getMetaData().getDatabaseProductName());
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID)" + "VALUES(#Name, #DNSName, #IPAddressV4, #IPAddressV6, #StatusCodeID)");
System.out.println("Data Inserted");
ResultSet resultSet = statement.executeQuery("SELECT Name FROM ComputerStatus");
while(resultSet.next())
{
System.out.println("Computer Name: " + resultSet.getString("Name"));
}
connection.close();
}
catch (Exception e)
{
e.printStackTrace();
System.err.println("Problem Connecting!");
}
}
I've tried couple of different things but no luck so far. Anyone know if this can be done?
You may use PreparedStatement instead of Statement.
PreparedStatement stmt = connection.prepareStatement("insert into test (firstname, lastname) values (?, ?");
stmt.setString(1, name);
stmt.setString(2, lname);
stmt.executeUpdate();
Using this way, you prevent SQL injection.
Have a look here :
PreparedStatement prep = conn.prepareStatement("INSERT INTO ComputerStatus(Name, DNSName, IPAddressV4, IPAddressV6, StatusCodeID) VALUES(?, ?, ?, ?, ?)");
prep.setString(1, name);
prep.setString(2, dnsName);
prep.setString(3, ipV4name);
prep.setString(4, ipV6);
prep.setInt(5, statusCode);
prep.executeUpdate();
this will help you understand.
I am trying to do an Insert, Update and Delete on a table in MS Access. Everything works fine
for a SELECT statement. But when doing the other three operations, I don't seem to get any
errors, but the actions are not reflected on to the DB. Please help...
THe INSERT statement is as follows:
PreparedStatement ps = con.prepareStatement("INSERT INTO Student VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1,1);
ps.setString(2,"ish");
ps.setInt(3,100);
ps.setInt(4,100);
ps.setInt(5,100);
ps.setInt(6,300);
ps.setInt(7,100);
ps.setString(8,"A");
ps.executeUpdate();
Also may I know why PreparedStatement is used except for SELECT statement...
I get this error:
Exception in thread "main" java.sql.SQLException: General error
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6986)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7114)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3149)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(JdbcOdbcPreparedState
ment.java:216)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(JdbcOdbcPrepare
dStatement.java:138)
at Student.main(Student.java:19)
This is my code...
import java.sql.*;
import java.io.*;
class Student {
public static void main(String args[]) throws SQLException, IOException, ClassNotFoundException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Student","","");
Statement st = con.createStatement();
PreparedStatement ps = con.prepareStatement("INSERT INTO Student VALUES (?, ?, ?, ?,
?, ?, ?, ?)");
ps.setInt(1,1);
ps.setString(2,"Girish");
ps.setInt(3,100);
ps.setInt(4,100);
ps.setInt(5,100);
ps.setInt(6,300);
ps.setInt(7,100);
ps.setString(8,"A");
ps.executeUpdate();
con.commit();
con.close();
}
}
This can happen when you don't commit/close the connection. Ensure that you're committing the connection after executing the statement and are closing the connection (and statement and resultset) in the finally block of the try block where they are been acquired and executed.
As to why the PreparedStatement is used, it's the common approach to avoid SQL injection attacks and to ease setting fullworthy Java objects like Date, InputStream, etc in a SQL query without the need to convert them to String.
I believe your prepared statement is of the wrong format. The documentation for INSERT INTO (available here: http://msdn.microsoft.com/en-us/library/bb208861(v=office.12).aspx) gives this format:
Single-record append query:
INSERT INTO target [(field1[, field2[, …]])] VALUES (value1[, value2[, …])
You give the format:
INSERT INTO target VALUES (value1[, value2[, …])
edit:
To be more clear I believe you want something like:
PreparedStatement ps = con.prepareStatement("INSERT INTO Student (Year, Name, field3 ...) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
Where Year, Name, field3 ... are the names of the fields you are trying to insert into.
The main reason for using a PreparedStatement is security. Generating a SQL query by concating strings is unsafe as the variable parts may contain SQL statements entered by a user. This would allow to execute statements like DROP TABLE * to the user (see SQL Injection). Theres is is a good idea only to use PreparedStatemnts if the SQL query is not static (doe snot contain variable parts).
Therefore it would be better also to use PreparedStatement for SELECT statements.
Edit :
You try to Insert your Student Primary Key, if it's an Identity column, it will not work.
You need to prepare your statement like this :
PreparedStatement ps = con.prepareStatement("INSERT INTO Student(Field1,Field2,Field3,Field4,Field5,Field6,Field7) VALUES (?, ?, ?, ?, ?, ?, ?)");
Without your Primary Key set, the DB will do it for you.
.
.
.
Original post :
There is a kind of similar question on StackOverflow.
You won't see any result from INSERT queries with Access until you close your Connection properly.
Your code doesn't close any resources, which will surely bring you grief. Call the close methods (in reverse order if there are more than one) in a finally block.
Here is a class DataBaseUtils to help you if needed.
public class DatabaseUtils
{
public static Connection createConnection(String driver, String url, String username, String password)
throws ClassNotFoundException, SQLException
{
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace(e);
}
}
public static void close(Statement statement)
{
try
{
if (statement != null)
{
statement.close();
}
}
catch (SQLException e)
{
e.printStackTrace(e);
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace(e);
}
}
}
Is there a way to retrieve the auto generated key from a DB query when using a java query with prepared statements.
For example, I know AutoGeneratedKeys can work as follows.
stmt = conn.createStatement();
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
However. What if I want to do an insert with a prepared Statement.
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql);
//this is an error
stmt.executeUpdate(Statement.RETURN_GENERATED_KEYS);
if(returnLastInsertId) {
//this is an error since the above is an error
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
Is there a way to do this that I don't know about. It seems from the javadoc that PreparedStatements can't return the Auto Generated ID.
Yes. See here. Section 7.1.9. Change your code to:
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.executeUpdate();
if(returnLastInsertId) {
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
auto_id = rs.getInt(1);
}
There's a couple of ways, and it seems different jdbc drivers handles things a bit different, or not at all in some cases(some will only give you autogenerated primary keys, not other columns) but the basic forms are
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Or use this form:
String autogenColumns[] = {"column1","column2"};
stmt = conn.prepareStatement(sql, autogenColumns)
Yes, There is a way. I just found this hiding in the java doc.
They way is to pass the AutoGeneratedKeys id as follows
String sql = "INSERT INTO table (column1, column2) values(?, ?)";
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
I'm one of those that surfed through a few threads looking for solution of this issue ... and finally get it to work. FOR THOSE USING jdbc:oracle:thin: with ojdbc6.jar PLEASE TAKE NOTE:
You can use either methods:
(Method 1)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
myPrepStatement = <Connection>.prepareStatement(yourSQL, Statement.RETURN_GENERATED_KEYS);
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
java.sql.RowId rid=rs.getRowId(1);
//what you get is only a RowId ref, try make use of it anyway U could think of
System.out.println(rid);
}
} catch (SQLException e) {
//
}
(Method 2)
Try{
String yourSQL="insert into Table1(Id,Col2,Col3) values(SEQ.nextval,?,?)";
//IMPORTANT: here's where other threads don tell U, you need to list ALL cols
//mentioned in your query in the array
myPrepStatement = <Connection>.prepareStatement(yourSQL, new String[]{"Id","Col2","Col3"});
myPrepStatement.setInt(1, 123);
myPrepStatement.setInt(2, 123);
myPrepStatement.executeUpdate();
ResultSet rs = getGeneratedKeys;
if(rs.next()) {
//In this exp, the autoKey val is in 1st col
int id=rs.getLong(1);
//now this's a real value of col Id
System.out.println(id);
}
} catch (SQLException e) {
//
}
Basically, try not used Method1 if you just want the value of SEQ.Nextval, b'cse it just return the RowID ref that you may cracked your head finding way to make use of it, which also don fit all data type you tried casting it to! This may works fine (return actual val) in MySQL, DB2 but not in Oracle.
AND, turn off your SQL Developer, Toad or any client which use the same login session to do INSERT when you're debugging. It MAY not affect you every time (debugging call) ... until you find your apps freeze without exception for some time. Yes ... halt without exception!
Connection connection=null;
int generatedkey=0;
PreparedStatement pstmt=connection.prepareStatement("Your insert query");
ResultSet rs=pstmt.getGeneratedKeys();
if (rs.next()) {
generatedkey=rs.getInt(1);
System.out.println("Auto Generated Primary Key " + generatedkey);
}