I am developing a desktop application in Netbeans. I am trying to insert a record into database. The very strange problem I am having is that when I press the save button no error occurs, everything works perfect. But when I check my DB, there is no data in there. But when I try to insert data directly in phpmyadmin through query then it inserts the record after the ID (auto increment) that has been generated before when I try to save data through desktop app. I know It is difficult to explain. Let me give you all a bit more explanation
For example my database is all clear and I am trying to save my first record
Through desktop app I pressed the save button
when I checked the database there is no record there
Here above If data was saved successfully then the record ID has to be 1
But now I am inserting the record by going into phpmyadmin and manually typing the quering in sql tab
now the id of the record should be 1 but the id is 2.
So it means through desktop app data is saving but somewhere hidden which I can't see and also It is remembering the id. I hope you undertstand my question.
If I pressed save button 3 times after then I insert some data in phpmyadmin the id of that record is 4.
I don't know what the problem is?
Here is my code :
public class DBConnectionManager {
private static String DRIVER_NAME = "com.mysql.jdbc.Driver";
private static String HOST_NAME = "localhost";
private static String PORT_NUMBER = "3306";
private static String DB_NAME = "sales";
private static String USER_NAME = "root";
private static String PASSWORD = "";
public static Connection openConnection() throws Exception {
Class.forName(DRIVER_NAME);
String jdbcURL = "jdbc:mysql://"+HOST_NAME+":"+PORT_NUMBER+"/"+DB_NAME;
Connection connection = DriverManager.getConnection(jdbcURL,USER_NAME,PASSWORD);
connection.setAutoCommit(false);
return connection;
}
}
public void addSupplierDetail() {
String contact_name = txt_contactName.getText();
String shop_name = txt_shopName.getText();
String city = txt_city.getText();
int phone = Integer.parseInt(txt_phone.getText());
int mobileNo = Integer.parseInt(txt_mobile.getText());
String address = txt_address.getText();
Supplier supplier = new Supplier();
supplier.setContactName(contact_name);
supplier.setShopName(shop_name);
supplier.setCity(city);
supplier.setPhone(phone);
supplier.setMobileNo(mobileNo);
supplier.setAddress(address);
connection = DBConnectionManager.openConnection();
SupplierDAO dao = new SupplierDAO(connection);
try {
if (dao.addSupplier(supplier)) {
connection.close();
JOptionPane.showMessageDialog(null, "data save");
// Dashboard dashboard = new Dashboard();
//dashboard.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "not saved");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public boolean addSupplier(Supplier supplier) throws Exception {
String sql = "INSERT INTO suppliers"
+ "(sup_name,sup_address,city,mobile_no,phone,shop_name)"
+ "VALUES (?,?,?,?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, supplier.getContactName());
ps.setString(2, supplier.getAddress());
ps.setString(3, supplier.getCity());
ps.setInt(4, supplier.getMobileNo());
ps.setInt(5, supplier.getPhone());
ps.setString(6, supplier.getShopName());
System.out.println(ps);
int rowscount = ps.executeUpdate();
System.out.println("no of rows updated: " + rowscount);
ps.close();
return rowscount > 0;
}
try the debugger, if everything is executed as expected, check the autoCommit property of your statement (or connection I forgot to which one it is bound)
Since the auto-increment seems to be happening, as you said. Looks like auto commit is set to false. You can try to set it at connection level, by calling connection.setAutoCommit(true) or you can do it only for that transaction by calling connection.commit().
Related
I have rolled back the changes made in a database, but the changes are being made in the database. Since it;s a unit test I can't have the data being tested inserted in the database.
I tried to add a member in db and got that member through his id by result set, but the member is being added in the db. I gave rollback to stop the changes made in db, but it's not working, I can see the member being added to db. Any solution?
#Test public void TestAddMember() { Member member = new Member();
try ( Connection connect = BookControl_jdbc.connection()) {
try ( Statement stcheck = connect.createStatement()) {
connect.setAutoCommit(false);
//input parameters
String name = "lia";
int age = 20;
String gender = "F";
String status = "ACTIVE";
member.setAge(age);
member.setGender(gender);
# member.setName(name);
member.setStatus(status);
memberControl.addMember(member);
memberControl.viewMembers();
int memberId;
String singleMemberQuery = "SELECT Member_id,Member_name,Age,Gender, Member_Status FROM Member WHERE Member_name='" + member.getName() + "';";
ResultSet rs = MemberControlDao_jdbc.getStmtResultSet(singleMemberQuery);
assertTrue(rs.next());
memberId = rs.getInt("Member_id");
assertEquals(name, rs.getString("Member_name"));
assertEquals(age, rs.getInt("Age"));
assertEquals(gender, rs.getString("Gender"));
assertEquals(status, rs.getString("Member_Status"));
} finally {
connect.rollback();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am working on a GUI app with MySQL access. When user enters some data in JTextField 'VendorID', I want it to be searched in the database, find the proper line with information and show all the columns in other JtextFields seperately. Actually I wanted this data to be showed in JLabel but unsuccessful, so trying now with JtextFields. Appreciate any help from you.
public void findVendor() {
String vatEntered = vendorID.getText();
try
{
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/masterdata_db?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
Statement st = conn.createStatement();
String check = "SELECT * FROM vendorcreation WHERE VAT = 'vatEntered' ";
ResultSet resultSet = st.executeQuery(check);
boolean status = true;
if(resultSet.next()==status){
nameSelected.setText(resultSet.getString(1));
adressSelected.setText(resultSet.getString(2));
countrySelected.setText(resultSet.getString(3));
vatSelected.setText(resultSet.getString(4));
ptermsSelected.setText(resultSet.getString(5));
conn.close();
}
else {
JOptionPane.showMessageDialog(null, "NO DATA FOUND! FIRST YOU MUST CREATE IT", "Inane error",JOptionPane.ERROR_MESSAGE);
dispose();
new CreateVendor().setVisible(true);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
From what I'm understanding, you're having trouble executing the statement?
You need to set up the statement as following:
String check = "SELECT * FROM vendorcreation WHERE VAT = " +vatEntered ;
But it is better to use a prepared statement instead.
String check = "SELECT * FROM vendorcreation WHERE VAT = ?";
PreparedStatement st = conn.prepareStatement(check);
st.setString(1, vatEntered);
ResultSet resultSet = st.executeQuery();
As for categorizing data, the order seems to depend on the order that the column is in the database. What you can also do is to manually set the result by changing the statement:
String check = "SELECT (column1, column2) FROM vendorcreation WHERE VAT = ?"//etc
where resultSet.getString(1); would be data from column1.
I've made a program which is getting data from database and then authorizing, but the problem is only the last record is correct - logging in is succesful.
public class Test {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/uzytkownicy";
static final String USER = "root";
static final String PASS = "";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.print("login: ");
Scanner zm1= new Scanner(System.in);
String name = zm1.next();
System.out.print("pass: ");
Scanner zm2 = new Scanner(System.in);
String password = zm2.next();
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting...");
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
Statement stmt = conn.createStatement();
String sql = "SELECT logins, passwords FROM users";
ResultSet rs = stmt.executeQuery(sql);
String databasePassword = null;
String databaseUsername = null;
while (rs.next()) {
databaseUsername = rs.getString("logins");
databasePassword = rs.getString("passwords");
}
if (name.equals(databaseUsername) && password.equals(databasePassword)) {
System.out.println("Logged in!");
}
else {
System.out.println("Bad Pass/Login");
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
}
}
If I'm understanding what you're trying to do (which I may not be), your problem is that the comparison of username and password is outside the while loop, so your:
while (rs.next())
just loops through the entire result set, so when the while loop ends, databaseUsername and databasePassword will be set to the values from the last row read.
Instead, move the comparison inside the loop and set a flag (defaulting to false) and break out of the loop if the correct username and password is found, then use that flag to determine what to print.
Also, you might want to read up on parameterized queries. You can actually have the database do all the work for you by using a PreparedStatement and making your query:
SELECT 1 from users where logins = ? and passwords = ?;
If the result set contains anything, then the user entered a valid username and password, otherwise they didn't. The question marks in the query would be set to name and password using the set* methods of PreparedStatement.
Another note--storing plaintext passwords is a horrible idea. If the table storing the passwords is exposed (through various attacks or just a disgruntled employee stealing it), then everyone has all your users' passwords. Eek! You might argue that you'll take steps to prevent that, but from a security perspective, it's best to assume someday the table will be compromised, and do everything you can to ensure that it's not too harmful.
The below method is supposed to update MySql DB with the company info passed to it.
I have other methods that insert and delete and work fine, however this method runs without exceptions, and always returns 1.
The general_log file shows that it received the update string but there are still no changes.
The only time I can get it to work is if I run the code in the MySql workplace directly.
If you need more info to figure this out, please let me know.
I gave you all I thought was needed.
Thanks.
// SQL update string received from the program in the log file
// UPDATE couponsprojectdb.company SET Email = 'admin#MyCompany.org', Password = 'pass' WHERE ID = 3
public void updateCompanyById(Company c, long id) throws SQLException
{
Connection conn = pool.getConnection(); // Gets an available connection from pool
// Prepared statement string
String sql = ("UPDATE company SET Email = ?, Password = ? WHERE ID = ?");
PreparedStatement p = conn.prepareStatement(sql);
p.setString(1, c.getEmail());
p.setString(2, c.getPassword());
p.setLong(3, id);
int i = p.executeUpdate();
System.out.println("changes: " + i);
pool.releaseConnection(conn);
}
You never called conn.commit() after doing the executeUpdate(). The reason the Java code returns 1 is because it succeeded, but the database rolled back the UPDATE immediately after the transaction ended.
You also need to close your connections. Change your code to this:
try {
Connection conn = pool.getConnection();
String sql = ("UPDATE company SET Email = ?, Password = ? WHERE ID = ?");
PreparedStatement p = conn.prepareStatement(sql);
p.setString(1, c.getEmail());
p.setString(2, c.getPassword());
p.setLong(3, id);
int i = p.executeUpdate();
conn.commit(); // <-- MAKE SURE TO COMMIT THE TRANSACTION TO THE DATABASE!!!
System.out.println("changes: " + i);
pool.releaseConnection(conn);
} catch(Exception e) {
// handle errors here
} finally {
try { if (p != null) p.close(); } catch (Exception e) {};
try { if (conn != null) pool.releaseConnection(conn); } catch (Exception e) {};
}
Big hat tip to this SO post which got me thinking about your problem.
Ok So I have a program where I add new Players to a database, and where I load them users into a list. The problem is when I delete a user, then go to add a new user the new player gets added in to where the old user was. Basically because that spot is free now and I use:
rs.moveToInsertRow();
is there a way that when adding a new player it 'Always' adds to the end of the the database. Like when you delete a row from table to make the database compress so it has no gaps?
here is the code:
public static void Save() { try {
String Name = "#####";
String Pass= "#####";
String Host = "######";
Connection con = DriverManager.getConnection(String.format(
"jdbc:mysql://%s:%s/%s", Host, "####", "####"),
Name, Pass);
Statement stmt = con.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT * FROM Accounts";
ResultSet rs = stmt.executeQuery(sql);
rs.moveToInsertRow( );
String userName= TestForm.UsernameTextField.getText(); //make this equal to whats in textfield
String password= TestForm.PasswordTextField.getText(); //make this equal to whats in textfield
String insertQuery="insert into Accounts (`Username`,`Password`) values ('"+userName+"','"+password+"');";
stmt.executeUpdate(insertQuery);
stmt.close();
rs.close();
}
catch(Exception e)
{
System.out.println("ERROR");
e.printStackTrace();
}
What's your table create statement? SHOW CREATE TABLE Accounts ;
Seems like an AUTO_INCREMENT integer primary key in the table would help your issue.