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
Related
Hello everyone can someone tell me what is wrong here ?
I have a task i was asked and i am new in connecting oracle databases with java servlet.
here is me code:
try {
out.print("first");
Class.forName("oracle.jdbc.OracleDriver");
out.print("aaa");
Connection con
= DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "myusername", "mypassword");
out.print("111");
PreparedStatement ps = con
.prepareStatement(
"INSERT INTO signup
values(fn, ln, date, em, pa, crnum)
");
out.print("222");
ps.setString(1, fn);
ps.setString(2, ln);
ps.setString(3, da);
ps.setString(4, em);
ps.setString(5, pa);
ps.setString(6, cr);
int i = ps.executeUpdate();
if (i > 0) {
out.print("You are successfully registered...");
}
} catch (Exception e2) {
out.println(e2);
}
out.close();
response.sendRedirect("address");
/* when press next bottom
it'll take me to add.html*/
and after i ran the whole code i get this :java.sql.sqlexception: invalid column index
In your SQL statement, you have to provide the tokens or placeholders for your bind variable like in the following...
PreparedStatement ps = con.prepareStatement("INSERT INTO signup values(?,?,?,?,?,?)");
ps.setString(1,fn);
ps.setString(2,ln);
ps.setString(3,da);
ps.setString(4,em);
ps.setString(5,pa);
ps.setString(6,cr);
You need to use placeholder ?:
PreparedStatement ps = con.prepareStatement("INSERT INTO signup values (?,?,?,?,?,?)");
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.
I would like to add a date value from JXDatePicker into my SQL database, however I'm getting this error when running it:
java.sql.sqldataexception: the syntax of the string representation of a datetime value is incorrect
This is my code:
try {
String url = "jdbc:derby://localhost:1527/Members";
String username = "admin1";
String password = "admin1";
Connection con = DriverManager.getConnection(url, username, password);
Statement stmt = con.createStatement();
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES('"+txtMemberID.getText()+"', '"+txtName.getText()+"', "
+ "'"+txtContact.getText()+"', '"+txtEmail.getText()+"', "
+ "'"+comboDate.getDate()+"', '"+comboTime.getSelectedItem()+"')";
stmt.execute(query);
JOptionPane.showMessageDialog(null, "Booking created");
txtMemberID.setText(null);
txtName.setText(null);
txtContact.setText(null);
txtEmail.setText(null);
comboDate.setDate(null);
comboTime.setSelectedItem("00");
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
The datatype specified for the Date attribute in my database is Date.
Thank you.
Your problem is that you're trying to embed a Date value (or a String representation of one) into the INSERT statement. Instead of concatenating variables into the query literal, you should use parameterized SQL through a PreparedStatement. In addition to protecting your code from SQL injection, parameterized statements are re-usable by the database, which means that the DB doesn't need to parse the SQL before each execution -- this is especially important if you're running a large number of queries in a loop.
Another thing that you should take care of, is closing the resources you've opened. In your example code, the Connection and Statement are left open after they are no longer needed. This is easy to fix using the try-with-resources statement, which was introduced in Java 7. The resources declared within the try clause get automatically closed after the statement is executed.
Putting it all together, here's an example of what the modified code could look like:
String query = "INSERT INTO BOOKING(MEMBERID, NAME, CONTACT, "
+ "EMAILADDRESS, RESERVATIONDATE, RESERVATIONTIME) "
+ "VALUES(?, ?, ?, ?, ?, ?)";
try (Connection con = DriverManager.getConnection(url, username, password);
PreparedStatement ps = con.prepareStatement(query)) {
ps.setString(1, txtMemberID.getText());
ps.setString(2, txtName.getText());
ps.setString(3, txtContact.getText());
ps.setString(4, txtEmail.getText());
ps.setDate(5, new java.sql.Date(comboDate.getDate().getTime()));
ps.setString(6, comboTime.getSelectedItem().toString());
ps.executeUpdate();
JOptionPane.showMessageDialog(null, "Booking created");
/*clear the UI components etc.*/
} catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString(), JOptionPane.ERROR_MESSAGE);
}
I am not getting where I am wrong. Java code is running smoothly but MySQL database doesn't displays the values inserted through query. Can we use multiple try catch as I have used?Here is the main part of my code:
**Part of my main code::
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int regno;
String bname,aname;
double cost;
try{
regno = Integer.parseInt(textField_regno.getText());
bname = textField_bookname.getText();
aname = textField_authorname.getText();
cost = Double.parseDouble(textField_cost.getText());
Class.forName("com.mysql.jdbc.Driver");
try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:1521/book","username","passwrd");
PreparedStatement stmt = conn.prepareStatement("INSERT INTO book('reg_no','b_name','a_name','cost')Values(?,?,?,?)");
stmt.setString(1, "regno");
stmt.setString(2, "bname");
stmt.setString(3, "aname");
stmt.setString(4, "cost");
JOptionPane.showMessageDialog(null,"Successfully added to the database");
}
catch(Exception e){
e.printStackTrace();
}
}
catch(Exception e1){
JOptionPane.showMessageDialog(null,"Check your Values" +e1);
}
}
});**
stmt.setString(1, "regno");
stmt.setString(2, "bname");
stmt.setString(3, "aname");
stmt.setString(4, "cost");
Here everything is being passed as a String (regardless of variable's value). So try this:
stmt.setString(1, regno);
stmt.setString(2, bname);
stmt.setString(3, aname);
stmt.setString(4, cost);
Also, you haven't used stmnt.executeUpdate(). Add that after this.
And you don't need multiple try/catch. One does all the work. Just make sure you code it properly.
You are missing call to executeUpdate()
Add below line in your code -
stmt.executeUpdate()
After
stmt.setString(4, "cost");
Kunal,
All looks fine except That you have not executed your prepared statement.
stmt.executeUpdate();
You can take help from here.
Do close your connection in finally.
I don't have much experience in using JAVA with SQL Server or any other database, so I'm having some trouble at the moment.
I have the following code:
public void insertProjeto(Planejado p){
String verifica="SELECT cd_projeto FROM PROJETO WHERE cd_projeto = ?";
String sqlInsert="INSERT INTO PROJETO (cd_projeto, ds_projeto) VALUES (?, ?)";
String projeto = p.getProjeto();
String nomeProjeto = p.getNomeProj();
PreparedStatement stmt;
try {
stmt = getDBConnection().prepareStatement(verifica);
stmt.setString(1, projeto);
ResultSet rs = stmt.executeQuery();
if (rs.equals("") || rs.equals(null)) {
System.out.println("------------------");
stmt = getDBConnection().prepareStatement(sqlInsert);
stmt.setString(1, projeto);
stmt.setString(2, nomeProjeto);
stmt.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
My goal is insert a register without duplicates, but for some reason my "if" isn't working.
Can anybody help me find out why?
Thanks in advance
When obtaining a ResultSet, you must call its next() method to have it progress to the first row of data if any. In case there is no data in the ResultSet object, rs.next() will return false.
There are better ways to prevent duplicates on SQL tables depends on what SQL server you're using (MS SQL, MySQL etc.)
If you're using MySQL, you can make cd_projeto a primary key and call REPLACE INTO instead of INSERT INTO, it will result in updating the record for cases it exist and inserting a new one when it doesn't.
Solved.
try {
stmt = getDBConnection().prepareStatement(verifica);
stmt.setString(1, projeto);
ResultSet rs = stmt.executeQuery();
while(!rs.next()) {
System.out.println("------------------");
stmt = getDBConnection().prepareStatement(sqlInsert);
stmt.setString(1, projeto);
stmt.setString(2, nomeProjeto);
stmt.executeUpdate();
break;
}
} catch (SQLException e) {
e.printStackTrace();
}
Don't know if it's the best way to do it, but works.
Thank you for the tips