I am trying to connect to jdbc database from servlet.I have separate class dbconnect for connection and inserting data to database.
Here is my dbconnect class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class dbconnect {
Connection conn;
Statement stm;
dbconnect(){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection
("jdbc:derby://localhost:1527/type","nika",
"mypass");
stm = conn.createStatement();
System.out.println("success");
String sql = "INSERT INTO USERS " + "VALUES (\"[email protected]\", \"nika\", \"nika\", \"kaci\")";
stm.executeUpdate(sql);
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}
In servlet I create new dbconnect object which must insert data to database,but it does not happen.
Can anyone tell me why it does not work? I guess I make fundamental mistake.
Thank you.
For more details I have jsp file which sends html form data to this servlet and then I try to write these data to database using dbconnect class.
I have changed dbconnect class like this,now I use preparedstatement to write files but still does not work.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class dbconnect {
Connection conn;
Statement stm;
dbconnect(){
try{
Class.forName("org.apache.derby.jdbc.ClientDriver");
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/type","nika","nika");
stm = conn.createStatement();
System.out.println("success");
String sql = "INSERT INTO NIKA.USERS (mail, pass, gender, saxeli) VALUES (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, "tsogiaidze");
statement.setString(2, "nika");
statement.setString(2, "nika");
statement.setString(2, "kaci");
int rowsInserted = statement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("A new user was inserted successfully!");
}
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}