How to get value as integer from JTextField in swing? - java

Actually i'm using oracle jdbc type4 thin driver. And I'm creating registration form in swing with eclipse with following columns pid,name,addrs.
the problem is i'm getting only string value which method is ps.setString=(2,JTextfiled.getText());
but i'm not able get int value like ps.setInt(1.getxxx());
can anyone guide me how to insert int value to database.
//prepare query
String query1 ="insert into employee values(?,?,?,?,?)";
//create preapare Statement
ps = con.prepareStatement(query1);
//set params
ps.setString(1,textField.getText());
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
ps.setString(4,textField_3.getText());
ps.setString(5, textField_4.getText());
//execute query
int count = ps.executeUpdate();
if(count==0)
{
JOptionPane.showMessageDialog(null, "Record not Inserted");
}
else
{
JOptionPane.showMessageDialog(null, "Record inserted into database successfuly");
}

Use Integer.parseInt to convert your string to an int, then use PreparedStatement#setInt to set it on the statement for insertion. E.g.:
ps.setInt(1, Integer.parseInt(textField.getText()));
You'll want to catch NumberFormatException in case the values in the text fields are not valid integers.

Related

Java Swing: Insert JTable column into mysql database

I was trying to INSERT data into mysql database from java swing form where I have two textfield value and one table column value. There I am getting problem with my Insertion process. I am trying to Insert the rows of a jtable column into database, but I found there Inserted that value of last row in the database.
I did the following code.
String customer_name = nametf.getText();
String phone = phonetf.getText();
PreparedStatement ps;
ResultSet rs = null;
String salesQuery = "INSERT INTO `sales`(`Customer_Name`, `Phone`,`Items`) VALUES (?,?,?)";
try {
ps = my_con.getConnection().prepareStatement(salesQuery);
ps.setString(1, customer_name);
ps.setString(2, phone);
for(int i=0; i<table1.getRowCount();i++){
ps.setString(3, table1.getValueAt(i, 0).toString());
}
if(ps.executeUpdate() != 0){
JOptionPane.showMessageDialog(null,"\nSave Succesfully\n\n","Saved",1);
}
else {
JOptionPane.showMessageDialog(null,"\nCheck Error\n\n","Error",1);
}
}
catch (SQLException ex) {
Logger.getLogger(registration.class.getName()).log(Level.SEVERE, null, ex);
}
but I found there Inserted that value of last row in the database.
In your loop you keep setting the 3rd parameter.
You only invoke the executeUpdate(...) statement once so only the last row is updated.
You need to execute your SQL statement for every row in the table:
for(int i=0; i<table1.getRowCount();i++){
ps.setString(1, customer_name);
ps.setString(2, phone);
ps.setString(3, table1.getValueAt(i, 0).toString());
ps.executeUpdate();
}
Note you can also do a batch update of the database. Check out: updating mysql table using where parameter from jtable cell for an example of this approach. You will need to combine the code in the question with the code in the answer to see the full batch implementation.

The number of values assigned is not the same as the number of specified or implied columns [duplicate]

This question already has an answer here:
SQLException: Number of values not same
(1 answer)
Closed 6 years ago.
I tried to saved data in javadb using JDBC.
It gave an error.
Error Occured : The number of values assigned is not the same as the number of specified or implied columns.
This is my JDBC code:
try {
//loading driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app");
PreparedStatement ps = con.prepareStatement("insert into Student values(?,?,?,?,?)");
ps.setString(1, Title);
ps.setString(2, Artist);
ps.setString(3, Country);
ps.setString(4, Price);
ps.setString(5, Year);
int i = ps.executeUpdate();
if (i > 0) {
out.println("You are sucessfully register");
}
} catch (Exception se) {
out.println("Error Occured : \n" + se.getLocalizedMessage());
se.printStackTrace();
}
You did not specify the columns you try to insert. SQL then assumes you may want to add each column defined for the table Student.
I assume there are more columns in the Student table than you have values in your insert statement. That is where the error occurs.
Define the columns you insert the values for explicitly.
insert into Student (Col1,Col2,Col3,Col4,Col5) values (?,?,?,?,?)
If all other columns are optional or auto-generated it will work that way. Otherwise you will get another error telling you which column is missing.

How to write a single query for multiple data manipulation in mysql?

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);

java.sql.SQLException : "Driver does not support this function"

I am doing a project on Hotel Management whose GUI is being designed using Swings and SQl Server Management Studio,2008 to store the data.But the problem I am facing is,i am getting an exception as "Driver does not support this function"...I am not able to sort out this problem...kindly enlighten me where I am going wrong..Thanks in advance..:)
I have created 2 forms:SignUp form and Login form...Here is my SignUp form where I am stuck...
btnSubmit = new JButton("SUBMIT");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
if(textField.getText().equals("") || textField_2.getText().equals("") ||
textField_5.getText().equals("") || textField_6.getText().equals("") ||
textField_7.getText().equals("") || passwordField.getPassword().equals("")
|| passwordField_1.getPassword().equals("")){
JOptionPane.showMessageDialog(null,"Fields cannot be left
empty!!!");
}
else{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:SignUp_DSN");
String firstname=textField.getText();
String lastname=textField_1.getText();
String email_id=textField_2.getText();
String country=textField_5.getText();
String state=textField_6.getText();
String ph_no=textField_7.getText();
char[] password=passwordField.getPassword();
char[] retype_password=passwordField_1.getPassword();
if(!password.equals(retype_password)){
JOptionPane.showMessageDialog(null,"Passwords are not
matching.Enter again!!!"); }
if(password.length<8 || retype_password.length<8){
JOptionPane.showMessageDialog(null,"Password should be more than 8
characters!!!");
}
String sql="insert into Sign_Up(`Firstname`,`Lastname`,`Email_id`,`Password`,`Retype_Password`,`Country`,`State`,`Phone_no`) values(?,?,?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, firstname);
ps.setString(2, lastname);
ps.setString(3, email_id);
ps.setString(6, country);
ps.setString(7, state);
ps.setString(8,ph_no);
ps.setString(4, new String(password));
ps.setString(5, new String(retype_password) );
ResultSet rs=ps.executeQuery(sql);
while(rs.next()){ }
con.close();
ps.close();
//rs.close();
}
}catch(Exception ex){
String str=ex.toString();
JOptionPane.showMessageDialog(null,str);
}
}
});
And also the condition for Password matching is not working...I get a Dialogue message saying passwords doesn't match always;whether the password match or not!!!
I think I see the problem,
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, firstname);
ps.setString(2, lastname);
ps.setString(3, email_id);
ps.setString(6, country);
ps.setString(7, state);
ps.setString(8,ph_no);
ps.setString(4, new String(password));
ps.setString(5, new String(retype_password) );
ResultSet rs=ps.executeQuery(sql); // <-- here.
You set-up your PreparedStatement query and bind the parameters, but then you call the unbound query again when you pass String sql to executeQuery()!
ResultSet rs=ps.executeQuery();
Also, you should add a finally block to close rs and ps.
Your column name 'state' is a keyword. Rename the column to something else.
There are two questions in your one question:
Why isn't the password check working? It's because you can't compare two char-Arrays using equals. Arrays don't override equals(), so it is basically a ==-check. Use Arrays.equals(password, retype_password)
As Elliott said: you are already setting your sql-query in the prepareStatement - don't pass it again in executeQuery()
There are some other issues I want to point out:
There's no need to store password and retype_password - they are equal anyway.
NEVER STORE PASSWORDS IN CLEARTEXT. Always use a suitable hash-function with salt like PBKDF2
The error is parameters not compatible.
The executeQuery function in PreparedStatement is executeQuery() without parameters

Invalid column index - Delete, using prepared statements

This is code section:
public int deleteStatement() throws SQLException {
Connection conn = null;
try {
conn = getConnectivity(conn);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String sql = "DELETE from USER_DETAILS where USERNAME=?";
getConnectivity(conn);
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(4, "rother09");
int rows = ps.executeUpdate();
System.out.println(rows + " DELETED");
return rows;
}
Connection Valid
Connection Valid
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
atoracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.jav a:5360)
at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5352)
atcom.platform.BilalsProject.DataAccessUtility.deleteStatement(DataAccessUtility.java:163)
at com.platform.BilalsProject.DataAccessUtility.main(DataAccessUtility.java:40
I am trying to delete from my table and it keeps giving me "invalid column index", can't see where I am going wrong.
In my database I have column 4 as password and 5 as username. The code works fine in sql worksheet.
First thing why getConnectivity(conn); twice in the same method
Secondly your query
String sql = "DELETE from USER_DETAILS where USERNAME=?"; takes in one parameters
so in that case your ps.setString(4, "rother09");
should change to
ps.setString(1, "rother09");
Note it that setString(int parameterIndex, String x) doesnot mean you column index it actually means the index of the parameters used in the query suppose you query is like
SELECT * from USER_DETAILS WHERE USERNAME=? AND PASSWORD = ?
Then
ps.setString(1, "rother09");// for the first parameter i.e USERNAME
ps.setString(2, "password");// for the second parameter i.e PASSWORD

Categories

Resources