I am having a difficult time with just updating the data within my SQLite Database. I have tried using a BinaryStream however no luck. So I then decided, screw it. No need to update the Blob, if I delete any code related to the BLOB (even in the SQL Statement) the Update statement doesn't execute (properly). Prior to adding the BLOB everything worked fine. Now I just can't seem to understand why I cannot update my database any longer. If I take out the BLOB, program will say "Employee has successfully added to the database" however, when I look at my database, all information is the same. I can insert, search and delete them methods are fine, just updating just doesn't seem to be working for me. I am running out of ideas on what to do, could someone possibly help me? Even if it's not updating the BLOB, at this rate I'll take anything. Update or no update.
Code -
updateEmployee.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Connection connection = null;
PreparedStatement pst = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:employeeDatabase.sqlite");
connection.setAutoCommit(false);
String sql = "UPDATE employees SET ID =?, Name=?, Gender=?, DOB=?, Address=?, Postcode=?, NIN=?, JobTitle=?, StartDate=?, Salary=?, Email=?, Images=? WHERE ID=?";
pst = connection.prepareStatement(sql);
pst.setInt(1,Integer.parseInt(idTextField.getText()));
pst.setString(2, nameTextField.getText());
pst.setString(3, genderTextField.getText());
pst.setString(4, dobTextField.getText());
pst.setString(5, addressTextField.getText());
pst.setString(6, postcodeTextField.getText());
pst.setString(7, ninTextField.getText());
pst.setString(8, jobtitleTextField.getText());
pst.setString(9, startdateTextField.getText());
pst.setString(10, salaryTextField.getText());
pst.setString(11, emailTextField.getText());
pst.setBytes(12, readFile(s));
pst.executeUpdate();
System.out.println("EmployeeAdded");
JOptionPane.showMessageDialog(null, "Employee has successfully added to the database");
connection.commit();
pst.close();
connection.close();
}
catch ( Exception e1 ) {
JOptionPane.showMessageDialog(null, "Uh oh! Something went wrong!");
}
}
});
Thank you.
Sorted the issue.
It was with the line-
String sql = "UPDATE employees SET ID =?, Name=?, Gender=?, DOB=?, Address=?, Postcode=?, NIN=?, JobTitle=?, StartDate=?, Salary=?, Email=?, Images=? WHERE ID=?";
I needed to add pst.setInt(12,Integer.parseInt(idTextField.getText())); for WHERE ID=?.
Never happened to me before though, alas I'll take it.
Your command text has 13 parameter placeholders (?) but you are only defining 12 parameters. You are missing the last one, which should presumably be the same value as the first one ("ID").
Related
I am creating a library program,where when a student borrows a book,it is removed from the library table and added to the borrowed books table. My query gives me an exception of atleast one parameter to the current statement os uninitialized
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
Connection con=CreateDB.getConnection();
String query3="insert into borrowedbooks values(?,?,?,?,?)";
PreparedStatement statement=con.prepareStatement(query3);
statement.setString(1, regNo.getText());
statement.setString(2, names.getText());
String value3=sClass.getSelectedItem().toString();
statement.setString(3, value3);
statement.setString(4, ((JTextField)date.getDateEditor().getUiComponent()).getText());
statement.setString(5, title.getText());
statement.execute();
String query4="update bookentry set copies=copies-1 where title=?";
Statement st=con.createStatement();
st.executeUpdate(query4);
JOptionPane.showMessageDialog(null,"Book lent Successfully");
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
In this LOC
String query3="insert into borrowedbooks values(?,?,?,?,?)";
You have 5 parameters and you are filling them out 1 by 1 in the following LOC's
statement.setString(1, regNo.getText());
statement.setString(2, names.getText());
String value3=sClass.getSelectedItem().toString();
statement.setString(3, value3);
statement.setString(4, ((JTextField)date.getDateEditor().getUiComponent()).getText());
statement.setString(5, title.getText());
But in the Update query, you also have a parameter but you are not adding any value into it. This is the reason which is causing the issue. Use the previous already created statement and no need to create another. The statement you are trying to run is called prepared statement. Try running the below written code.
String query4="update bookentry set copies=copies-1 where title=?";
statement=con.prepareStatement(query4);
statement.setString(1, title.getText());
statement.executeUpdate();
this design is a poor design. please redesign the database structure. example is given below. if some student get a book, related student id, book id and date add to the borrowed_book table as a new record
I've looked on here before, but none of the answers helped me out!
I have the following code:
public void addSerialToDb(String serial) {
System.out.println(serial);
try{
System.out.println(getMaxInt());
}catch (Exception e){
e.printStackTrace();
}
String serialV2 = ""+serial;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("INSERT INTO blogdata.serials" + "VALUES(?, ?)");
pst.setInt(1, getMaxInt());
pst.setString(2, serialV2);
pst.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}
closeDataBase();
}
In my database scheme, there are 2 columns, first one is integer (id) and second one is a VARCHAR(45) (serial). But still I get the following error:
java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3321)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3306)
at com.mysql.jdbc.PreparedStatement.setString(PreparedStatement.java:4021)
at DataBase.SerialDataBase.addSerialToDb(SerialDataBase.java:41)
I used this method on another program, but since switched to IntelliJ it stopped working.
Thanks in advance!
EDIT:
I forgot to mention, I'm using Java 1.8, the mySql connector 5.1.40 and running MySql 5.7.15
According to your comment getMaxInt() method, the problems is because of prepare statement object. It's being updated in getMaxInt() method and parameters not match error occurred. I think it's program logic error and you just need to change this program logic. I also recommend to not concat the String if it's not needed.
Below is just ok.
pst = con.prepareStatement("INSERT INTO blogdata.serials (column1,column2) VALUES (?,?)";
Try using the insert statement like this:
"INSERT INTO blogdata.serials (column1,column2) VALUES (?,?)";
i have the following jframe :
and i wanna make the buttons work im still new to programming can someone help me please? i want the add row btn to add a new row to database, the update btn let me save changes and delete delete the selected row, also the jTextBoxes are connected to the database
i tried doing this to update :
Connection conn=null;
PreparedStatement pst = null;
try{
String value1=txt_cid.getText();
String value2=txt_carid.getText();
String value3=txt_aid.getText();
String value4=txt_rd.getText();
String value5=txt_bd.getText();
String value6=txt_bn.getText();
String sql="update booking set customer_id'"+value1+"',car_id'"+value2+"',agency_id'"+value3+"',return_date'"+value4+"',booking_date'"+value5+"',booking_number'"+value6+"',";
pst=conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "table updated");
}catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
but it didnt work out for me i get exception error
You haven't stated what the error is but UPDATE takes an equals operator for every parameter. Also use PreparedStatement placeholders to avoid SQL Injection attacks:
String sql = "update booking set customer_id=?, car_id=?,agency_id=?,return_date=?,booking_date=?,booking_number=?";
pst = conn.prepareStatement(sql);
pst.setInt(1, value1);
pst.setInt(2, value2);
... // set the other parameters
Read: UPDATE Syntax
I am new in java, in a java project, i want to subtract a textbox value named Quantity(q_field) from 'Available' field of database table Item_detail whenever 'sell' button is clicked and automatically update the table. I wrote some piece of code but its not working. My code is:
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
if(!p_field.getText().isEmpty() && !b_field.getText().isEmpty() && !m_field.getText().isEmpty() && !sell_field.getText().isEmpty() && !c_field.getText().isEmpty()){
int a=Integer.parseInt(q_field.getText().trim());
String sql1="update Item_detail set Available=Available-'a' where P_name=? and Manuf_name =? and Model_no=?";
String sql2="insert into Sell (`S_id`,`P_name`,`Manuf_name`,`Model_no`,`Date`,`Quantity`,`S.p`,`Cost_price`) values(?,?,?,?,?,?,?,?)";
try{
pst=(PreparedStatement) con.prepareStatement(sql1);
pst.setString(1, p_field.getText());
pst.setString(2, b_field.getText());
pst.setString(3, m_field.getText());
pst.setString(4, q_field.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Product sold successfully");
update_table();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
What will be the correct sql code of 'sql1', i can not understand. Please help
sql1 shall be:
String sql1="update Item_detail
set Available=Available-?
where
P_name=?
and Manuf_name =?
and Model_no=?";
And set values to pst query to include value of variable a as follows:
pst=(PreparedStatement) con.prepareStatement(sql1);
pst.setInt(1, a);
pst.setString(2, ...
...
pst.executeUpdate();
But make sure that you have values set only for that number of palce holders in the query. Otherwise there would be a place holder count mismatch and an SQLException would be thrown.
update Item_detail set Available=Available - ? where ...
The value of a is a parameter of your query, just like the other ones. BTW, you're binding 4 different parameters to the statement, and your query only has 3 parameters (? placeholders)
Change your Update Query to this
String sql1="update Item_detail set Available=Available-? where P_name=? and Manuf_name =? and Model_no=?";
ps.setInt(1,a);
I have a requirement where I need to insert mobile number in mysql if and only if the number is is not present.So for this I am first checking if a number is present in mysql using select query .If number is not present then insert.Following is my code
PreparedStatement pt1=con.prepareStatement("select * from registerSmsUsers where mobile='"+mobile+"'");
PreparedStatement pt=con.prepareStatement("insert into registerSmsUsers values(?,?,?)");
pt.setString(1, name);
pt.setString(2, email);
pt.setString(3, mobile);
ResultSet rs1=pt1.executeQuery();
if(rs1.next())
{pt.executeUpdate();}
i dont know whether this is a efficient way or not.Please suggest me a better way then this
Probably the easiest way in mysql is:
insert ignore into registerSmsUsers values(?,?,?)
When assuming you have unique key on mobile
You may check it here: How to 'insert if not exists' in MySQL?
Or here: http://dev.mysql.com/doc/refman/5.6/en/insert.html
Many of the proposed solutions (including yours) have a race condition that can cause a primary key or unique constraint violation. You code also have a possible SQL injection attack by concatenating SQL rather than using prepared statement parameters. Use SELECT...FOR UPDATE.
PreparedStatement ps = con.prepareStatement("SELECT name, email, mobile FROM registerSmsUsers WHERE mobile=? FOR UPDATE",
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
ps.setString(1, mobile);
ResultSet rs = ps.executeQuery();
if (rs.next()) { // it exists already
rs.moveToCurrentRow();
rs.updateString(3, mobile);
rs.updateRow();
} else { // it does NOT exist
rs.moveToInsertRow();
rs.updateString(1, name);
rs.updateString(2, email);
rs.updateString(3, mobile);
rs.insertRow();
}
rs.close();
ps.close();
EDIT: Just make sure you have an index on registerSmsUsers.
CREATE INDEX registerSmsUsers_mobile_ndx ON registerSmsUsers(mobile)
or a unique contraint (which implicitly creates an index):
ALTER TABLE registerSmsUsers ADD CONSTRAINT registerSmsUsers_mobile_unq UNIQUE (mobile)
With an index, even with millions of records the update/insert will basically be instant.
EDIT2: Added cursor/result set options.
I think it would be better to create a stored procedure and then in that stored procedure you can first use the IF NOT EXISTS clause to check if the user exists using the select statement. If the user is not present you can insert the user in database.
Something like this:
IF NOT EXISTS(SELECT 1 FROM `registerSmsUsers` WHERE mobile= #mobile) THEN
BEGIN
INSERT INTO
`registerSmsUsers`
(
//column names
)
VALUES
(
//values
);
END;
END IF;
Also there is a INSERT IGNORE statement which you can use like this:
insert ignore into registerSmsUsers values(?,?,?)
if not exists(select * from registerSmsUsers where mobile='232323') <-- will check your mobile no
begin
insert into registerSmsUsers values(?,?,?)
end
This one is also an efficient way to check your method is also working fine but this also can be done
See difference is you will have only one query here
i hope this will help you thanks
[Edit]
Your questions answer
Ya there is a execution time diff between yours and mine query its depends upon a database size what you are using if you are using small size database (probably 1000 people) then you will not see any diff between your query and mine query but if your are using lakhs of users then your will have a performace issues check include execution plan in mysql you will get realtime difference between two
As requested, here is my tweaked version of brettw's answer:
import java.sql.*;
public class MySQLtest {
public static void main(String[] args) {
Connection con;
try {
con = DriverManager.getConnection(
"jdbc:mysql://192.168.1.3/zzzTest?" +
"useUnicode=yes&characterEncoding=UTF-8" +
"&user=root&password=whatever");
String newName = "Gord";
String newEmail = "gord#example.com";
String newMobile = "416-555-1212";
String sql =
"SELECT " +
"id, " +
"name, " +
"email, " +
"mobile " +
"FROM registerSmsUsers " +
"WHERE mobile = ? " +
"FOR UPDATE";
PreparedStatement pst = con.prepareStatement(
sql,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
pst.setString(1, newMobile);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
rs.moveToCurrentRow();
rs.updateString("name", newName);
rs.updateString("email", newEmail);
rs.updateRow();
System.out.println("Existing row updated.");
}
else {
rs.moveToInsertRow();
rs.updateString("name", newName);
rs.updateString("email", newEmail);
rs.updateString("mobile", newMobile);
rs.insertRow();
System.out.println("New row inserted.");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
Note that id is the Primary Key for the table: int(11) NOT NULL AUTO_INCREMENT