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.
Related
I'm doing a calendar program in Netbeans using Mysql database. there is a table for every event which has many column, one of them being a Boolean called "Tarea" (Task). This determines if the day will go on the table of Pending which should only display the date and title of the event.
To do this I used the following code:
void TablaPendientes(){
String url = "jdbc:mysql://localhost:3306/calendario";
String user = "root";
String pass = "password";
try(Connection connection = DriverManager.getConnection(url, user,pass))
{
DefaultTableModel model = (DefaultTableModel) tablaRecursos.getModel();
pst=connection.prepareStatement("select Fecha, TituloE from eventos where Tarea = 1");
rs=pst.executeQuery();
while (rs.next())
{
model.addRow(new String[]{rs.getString("Fecha"), rs.getString("TituloE")});
}
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
I called the function form my main but it still doesn't plot the table. Can I only put all of the values of the table? I ask this because in another table that has practically the same code except that in the statement it is "select * from", it plots correctly.
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.
This question already has answers here:
How to get the primary key to execute an update statement [closed]
(2 answers)
Closed 6 years ago.
I'm trying to update my table using Java JDBC. But I don't have any idea how can I call my primary key using prepared statement. I try to make an USER_ID object for the column of my database but don't know how where to start. How will I determine if I already updated my Database?
INSERT
private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
String inputEmployee = employeeTf.getText();
String inputDepartment = departmentTf.getText();
if(inputEmployee.isEmpty() && inputDepartment.isEmpty()){
JOptionPane.showMessageDialog(null, "Please fill up!");
}
else if(inputEmployee.isEmpty()){
JOptionPane.showMessageDialog(null, "Please enter your username");
}
else if(inputDepartment.isEmpty()){
JOptionPane.showMessageDialog(null, "Please enter your password");
}
else{
String myQuery = "INSERT INTO SAMPLE (EMPLOYEENAME,DEPARTMENT) VALUES (?,?)";
try(Connection con = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = con.prepareStatement(myQuery);
){
myPs.setString(1, employeeTf.getText());
myPs.setString(2, departmentTf.getText());
myPs.executeUpdate();
System.out.print("Record is inserted");
} catch (SQLException ex) {
DBUtilities.processException(ex);
}
}
}
Here if I insert a new value it will load the new values to database.
SELECT
private void searchBtnActionPerformed(java.awt.event.ActionEvent evt) {
String searchEmployee = searchName.getText(); //SWING COMPONENTS
String searchDept = searchDepartment.getText();//SWING COMPONENTS
String selectQuery = "SELECT EMPLOYEENAME,DEPARTMENT FROM SAMPLE WHERE USER_ID = ?";
try {
Connection con = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = con.prepareStatement(selectQuery,ResultSet.CONCUR_UPDATABLE,ResultSet.TYPE_SCROLL_INSENSITIVE);
ResultSet myRs = myPs.executeQuery();
while(myRs.next()){
String name = myRs.getString(1);
String department = myRs.getString(2);
}
} catch (SQLException ex) {
DBUtilities.processException(ex);
}
}
SCREENSHOT
After filling out the fields for searchName and searchDepartment textfields. As you can see here I here hit the "Search" button.
I want the value of searchName and searchDepartment will print out to the textfield of employeeTf and departmentTf
How will I use the setText here?
while(myRs.next()){
String name = myRs.getString(1);
String department = myRs.getString(2);
nameText.setText(name);
deptText.setText(department);
}
i supposed nameText and deptText are the object of swing text component
if these are not accessible here..then you can create object of all field and put data from result set and return the object and use there.
I have to insert values from jsp form to database table and to the same table I need to insert values for two columns from 2 different tables.
Here is the code:
public class ForgotPassWordDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public void createSecretQnA(ForgotPassWord forgotPassWord) {
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2)VALUES(?,?,?,?,?)"; // Here am inserting form values to database.
String sql1="INSERT INTO forgotpassword (CustId) SELECT CustId FROM signup";// Here am trying to get value from another table and insert
String sql2="INSERT INTO forgotpassword (LoginId) SELECT LoginId FROM login"; // Here am trying to get value from another table and insert
Connection conn = null;
try {
conn = dataSource.createConnection();
PreparedStatement ps = conn.prepareStatement(sql);
PreparedStatement ps1 = conn.prepareStatement(sql1);
PreparedStatement ps2 = conn.prepareStatement(sql2);
ps.setInt(1, forgotPassWord.getId());
ps.setString(2, forgotPassWord.getSq1());
ps.setString(3, forgotPassWord.getAnSq1());
ps.setString(4, forgotPassWord.getSq2());
ps.setString(5, forgotPassWord.getAnSq2());
ps.executeUpdate();
ps1.executeUpdate();
ps2.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
catch (NullPointerException e1){
}
finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
But on each executeUpdate() its incrementing and the values from the form are stored in one row and in the next row the values from the signup and login tables are getting stored. How to make all this get stored in a single row? Any help is appreciated.
You are doing 3 inserts, so at least 3 rows are created. Also, when you do SELECT CustId FROM signup, how can you ensure that only one and the right value of CustId is taken from signup table? With this query you are fetching all the CustId. Same goes for login table and query.
To merely resolve your problem you have to create a single query:
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2,CustId,LoginId)VALUES(?,?,?,?,?,(SELECT CustId FROM signup),(SELECT LoginId FROM login))";
^ ^ ^ ^
but I don't think you have thought this enough.
There should be something like:
SELECT LoginId FROM login WHERE CustId=? //Here I'm guessing, I don't know your tables.
The point is to get the correct value both in login table and signup table that corresponds to the user who forgot his password. This can be easily done with a WHERE clause (supposing your foreign key are setted correctly).
EDIT
As per your comment I'm going to clarify the way you should add your new user.
First of all you need to create the new user, so as soon as the information needed is sent and checked you insert a new row in signup table. But wait to execute the query.
You need the CustId. Because is an auto-increment column, you don't know which value MySQL created. You must fetch it and you can do it directly when you create the new user adding a parameter to the prepared statement:
PreparedStatement pstmt = conn.prepareStatement(sqlForNewUser, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
custId = keys.getInt(1);
Now you have the new user Id and can use it to insert the other values:
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2,CustId,LoginId)VALUES(?,?,?,?,?,(SELECT CustId FROM signup WHERE CustId = ?),(SELECT LoginId FROM login WHERE CustId = ?))";
//...
ps.setString(6, custId);
ps.setString(7, custId);
private void next_contactActionPerformed(java.awt.event.ActionEvent evt) {
String name, lName, add, em, cell = null;
try {
String Url = "Jdbc:Odbc:DirDSN";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(Url,"sa","mysql");
//Statement st = con.createStatement();
String sql = "SELECT * FROM PersonInformation";
PreparedStatement pstmt = con.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
name = rs.getString("First_Name");
lName = rs.getString("Last_Name");
add = rs.getString ("Address");
em = rs.getString("Email_Id");
cell = rs.getString("cell#");
jTextField2.setText(name);
jTextField3.setText(lName);
jTextField4.setText(add);
jTextField5.setText(em);
jTextField10.setText(cell);
}
con.close();
} catch(Exception sqlEx) {
System.out.println(sqlEx);
} finally {
}
}
I have written this next function for next button. I want when I click the next button the rs.Next() returns a new record of table on the screen. Now I am facing the problem that each time when I click the next button I get the first row of the table. I have also used while (rs.Next()) but it returns me the last row of table each time I click the next button. Please tell me how I can write this function such that each time I call this function it returns a new record from the table.
Change ResultSet rs to a member variable or save the position you're in and use it as a parameter for the method (see LIMIT).
At the moment, you create a new ResultSet with every click, always starting at index 0.