Cannot add or update a child row: a foreign key constraint fails (dbprojeto.avaliacao, CONSTRAINT fk_cliente_avaliacao FOREIGN KEY (cliente) REFERENCES cliente (idcliente) ON DELETE NO ACTION ON UPDATE NO ACTION)
I got the above error message when trying to insert some datas in the Data Base. The table has 5 fields, 2 of them are foreign key though. I was told that I have to recover the ids(foreign keys) first so that I could insert correctly. One of the ID's that has to be caught is on the session which is in the JSP page, when users are already logged in. Guess there's nothing wrong with the DAO class once that debug project shows me that is all correct. Might be something with the Servlet I certainly think.
SERVLET
try {
Avaliacao avaliacao = new Avaliacao();
Prestador prestador = new Prestador();
Cliente cliente = new Cliente();
avaliacao.prestador = new Prestador();
AvaliacaoDAO dao = new AvaliacaoDAO();
avaliacao.setNota(Integer.parseInt(request.getParameter("nota")));
avaliacao.setComentario(request.getParameter("comentario"));
HttpSession session = request.getSession(true);
avaliacao.cliente = (Cliente) session.getAttribute("cliente");
avaliacao.cliente.setIdcliente(avaliacao.cliente.getIdcliente());
dao.inserirAvaliacao(avaliacao);
avaliacao.prestador.setIdprestador(PrestadorDAO.retornarId());
request.setAttribute("msg", "Gravado com sucesso!");
request.getRequestDispatcher("cadastrado.html").forward(request, response);
DAO Insert method
public boolean inserirAvaliacao(Avaliacao avaliacao) throws SQLException {
try {
Connection conexao = Conexao.getConexao();
Statement stmt = conexao.createStatement();
String sql = "insert into avaliacao(idavaliacao, nota, comentario, cliente, prestador)values(?,?,?,?,?)";
PreparedStatement pstmt = conexao.prepareCall(sql);
avaliacao.cliente = new Cliente();
avaliacao.prestador = new Prestador();
pstmt.setInt(1, avaliacao.getIdavaliacao());
pstmt.setInt(2, avaliacao.getNota());
pstmt.setString(3, avaliacao.getComentario());
pstmt.setInt(4, avaliacao.cliente.getIdcliente());
pstmt.setInt(5, avaliacao.prestador.getIdprestador());
pstmt.execute();
conexao.close();
return true;
} catch (ClassNotFoundException ex) {
System.out.println(ex);
return false;
} catch (SQLException sql) {
System.out.println(sql);
return false;
}
}
Session in the JSP
<%
Cliente cliente = (Cliente) session.getAttribute("cliente");
if (cliente == null) {
cliente = (Cliente) session.getAttribute("cliente");
}
%>
I would say avaliacao.cliente.getIdcliente()); returns a value that does not exist in your cliente database table.
Related
Hello I want to populate a table from database but I have some difficult to do since I am newbie in java programming
here is the Users.java where the method getData(select) is implemented:
#Override
public Users getData(Users u) throws Exception {
Connection con = null;
Users user = null;
ResultSet rs = null;
PreparedStatement ps = null;
try{
con = getConnection();
String sql = "SELECT * FROM USERS";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
user = new Users();
user.setFirstName(rs.getString("First_NAME"));
user.setLastName(rs.getString("LAST_NAME"));
user.setAge(rs.getInt("AGE"));
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage());
}finally{
rs.close();
ps.close();
closeConnection(con);
}
return user;
}
Well the data is stored in Users object now and I want to display it on a jTable which is located in patientJframe file can you tell me how to do that?
I created a method on patientJframe but I dont know what to do Im stuck onhere.
PatientJframe :
public void PopulatejTable(){
try {
Users u = null;
Users user = UsersDB.getInstance().getData(u);
if(user== null){
DefaultTableModel dtm = (DefaultTableModel)jTable.getModel();
dtm.setRowCount(0);
Vector vector = new Vector();
vector.add(user.getCin());
vector.add(user.getLastName());
vector.add(user.getFirstName());
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
The method it is correct ? please can you help me ?
I'm making book store and so far i only have 3 tables.
Book:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null
Cart:
-id:(int) primary key, autoincrement, not null
and
Article:
- id:(int) primary key, autoincrement, not null,
- title:(varchar) not null,
- price: (decimal) not null,
- cart_id:(int) foreign key referencing cart
For me it's logical when user clicks on "add to cart" button to check if cart already exist, if exist i will return that cart if not create new. And user will put multiple articles in one cart. This is my class for inserting Cart in db:
public class CartDAO {
private static DataSource dataSource;
private static int autoIncKey = -1;
public static void insertCart() {
Connection conn = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("jdbc/NemkeDB");
conn = dataSource.getConnection();
String insert = "insert into cart() values()";
PreparedStatement ps = conn.prepareStatement(insert, RETURN_GENERATED_KEYS);
ps.executeUpdate();
rs = ps.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} catch(Exception e){
System.err.println(e);
}
In CartDAO i want to have that check, something like this:
if(cart == null){
'insert into cart()values()'
}else{ // if cart exist i want to return that cart id}
i don't know how to do that with GeneratedKeys.
Below is the class where i'm passing the id from cart in ArticleDAO
public class ArticleDAO {
private static DataSource dataSource;
private static ArrayList<Article> articleList = new ArrayList<>();
public static void insertArticle(String title, double price) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
InitialContext ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("jdbc/NemkeDB");
conn = dataSource.getConnection();
st = conn.createStatement();
CartDAO.insertCart(); // Here is where i call(insert) Cart
String insert = "insert into article(title,price,cart_id) values(?,?,?)";
PreparedStatement ps = conn.prepareStatement(insert);
ps.setString(1, title);
ps.setDouble(2, price);;
ps.setInt(3, CartDAO.getAutoIncKey()); // Here i pass that id
ps.executeUpdate();
rs = st.executeQuery("select * from artical");
while (rs.next()) {
String articalTitle = rs.getString("title");
double articalPrice = rs.getDouble("price");
Artical artical = new Artical(articalTitle, articalPrice);
articalList.add(artical);
}
} catch (Exception e) {
System.err.println(e);
}
My question is what is the proper way to make that check? Maybe with session? And how to return id if cart exist? I know it's a long question but i think it's easy for anyone with any working experience with java. Thanks everyone who invested time to read and reply this problem.
I'm creating a simple app which uses JDBC to get data from MySQL. I use a dao to get data from the database. All but one are working fine (code is the same for all DAOs). Also I'm committing INSERT and UPDATE methods manually.
Workbench returns valid result even if I set isolation level read committed manually.
JDBCSessionDao create method:
public void create(Session session) throws SQLException{
try(PreparedStatement ps = conn.prepareStatement(INSERT_SESSION)){
conn.setAutoCommit(false);
LocalTime start = session.getStartTime();
LocalTime end = session.getEndTime();
System.out.println(start + ", " + end);
System.out.println(Time.valueOf(start) + ", " + Time.valueOf(end));
ps.setTime(1, Time.valueOf(start));
ps.setTime(2, Time.valueOf(end));
ps.setDate(3, Date.valueOf(session.getDate()));
ps.setLong(4, session.getMovieId());
ps.executeUpdate();
conn.commit();
conn.setAutoCommit(true);
}
catch (SQLException e){
logger.error(e.getMessage());
conn.rollback();
}
}
JDBCSessionDao findByDate method
public List<Session> findByDate(LocalDate date) {
List<Session> sessions = new ArrayList<>();
SessionMapper mapper = new SessionMapper();
try(PreparedStatement ps = conn.prepareStatement(SELECT_BY_DATE_ORDER_BY_TIME_ASC)){
ps.setDate(1, Date.valueOf(date));
ResultSet rs = ps.executeQuery();
System.out.println(rs.getFetchSize());
while(rs.next()){
Session s = mapper.extractFromResultSet(rs);
sessions.add(s);
}
}
catch (SQLException e){
logger.error(e.getMessage());
}
return sessions;
}
Query:
String SELECT_BY_DATE_ORDER_BY_TIME_ASC = "SELECT * FROM sessions WHERE session_date=? ORDER by start_time ASC";
JDBCDaoFactory getConnection() method:
private Connection getConnection(){
String url = "jdbc:mysql://localhost:3306/cinemajee?useLegacyDatetimeCode=false&serverTimezone=Europe/Kiev";
String user = "root";
String password = "root";
try{
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(url, user, password);
}
catch (SQLException | ClassNotFoundException e){
e.printStackTrace();
throw new RuntimeException();
}
}
Query result in workbench:
query result
Try modifying the query in your code. Perhaps the session_date parameter isn't working. So change from this:
"SELECT * FROM sessions WHERE session_date=? ORDER by start_time ASC"'
to this:
"SELECT * FROM sessions ORDER by start_time ASC LIMIT 5"'
I've forgot to change column names in SessionMapper, they were written in camel case (e.g. sessionId) but my db columns is in snake case (e.g. session_id).
When Try to fetching Data in database result it come zero row but when try to copy and past query on mysql has return specific number of rows needed.
Connection to mysql server
private Connection connection() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/olesdb", "root", "");
} catch (Exception e) {
//System.out.println("Connection error");
}
return con;
}
**
My function for fetching data
**
public List<AcademicYearCourses> getStudentCourse(int studentID, int academicYear,int semester) throws SQLException{
List<AcademicYearCourses> list = new ArrayList<>();
PreparedStatement sta = connection().prepareStatement("SELECT courseCode,courseName FROM courses co,studentprograms stpro,academicyearcourse acco WHERE stpro.studentID=? AND acco.academicYearID=? AND acco.semesterID=? AND stpro.programID= acco.programID AND stpro.studyYear=acco.studyYear AND acco.courseID=co.courseID");
sta.setInt(1, studentID);
sta.setInt(2, academicYear);
sta.setInt(3, semester);
ResultSet res = sta.executeQuery();
while(res.next()){
AcademicYearCourses acco = new AcademicYearCourses();
acco.setAcdemicYearCourseID(rs.getInt("acdemicYearCourseID"));
acco.setCourseName(rs.getString("courseName"));
acco.setCourseCode(rs.getString("courseCode"));
list.add(acco);
}
return list;
}
So I need help to solve this issue it very important in my project and Cant continue without this data
Your are doing rs.getInt("acdemicYearCourseID") but column acdemicYearCourseID is not in your SELECT columns list.
Also try changing getInt("..."), getString("...") to getInt(1), getString(2)
So here's what I've done so far. it is also already connected to the database with the username as the primary key.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
Accounts bean = new Accounts();
bean.setUsername(request.getParameter("uname"));
bean.setName(request.getParameter("fname"));
bean.setEmail(request.getParameter("email"));
bean.setPassword(request.getParameter("password"));
AccountsDAO aO = new AccountsDAO();
aO.addAccount(bean);
response.sendRedirect("Stream.jsp");
}
finally{
}
}
what i want is, when i try to register an account with the same username/email of any existing user in the database, it will redirect to another with another page also using a response.sendRedireect("file.jsp"); that will require the user to register again with another username/email. Thank you in advance!
here is my AccountsDAO
public void addAccount(Accounts bean) {
try {
bConnector = new DBConnector();
Connection c = bConnector.getConnection();
String query = "insert into account (username, name, email, password) values (?,?,?,?)";
PreparedStatement preparedstatement = c.prepareStatement(query);
preparedstatement.setString(1, bean.getUsername());
preparedstatement.setString(2, bean.getName());
preparedstatement.setString(3, bean.getEmail());
preparedstatement.setString(4, bean.getPassword());
preparedstatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(AccountsDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
Once you have username as primary it will not allow to insert duplicates . so try like this
try
{
//query to insert your username which you get from user
}
If it is duplicate it will throw an exception as ora- so handle the exception using page redirect using catch block.
catch(Exception e)
{
system.out.print(e);
response.sendRedirect("file.jsp");
}
Update
Declare an integer variable to check whether you have inserted the value . Also change the return type of the method addAccount(Accounts bean) to int
public int addAccount(Accounts bean) {
int count=0;
try {
bConnector = new DBConnector();
Connection c = bConnector.getConnection();
String query = "insert into account (username, name, email, password) values (?,?,?,?)";
PreparedStatement preparedstatement = c.prepareStatement(query);
preparedstatement.setString(1, bean.getUsername());
preparedstatement.setString(2, bean.getName());
preparedstatement.setString(3, bean.getEmail());
preparedstatement.setString(4, bean.getPassword());
count=preparedstatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(AccountsDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return count;
}
In your servlet,
int count=0;
try {
Accounts bean = new Accounts();
bean.setUsername(request.getParameter("uname"));
bean.setName(request.getParameter("fname"));
bean.setEmail(request.getParameter("email"));
bean.setPassword(request.getParameter("password"));
AccountsDAO aO = new AccountsDAO();
count=aO.addAccount(bean);
if(count>0){
response.sendRedirect("Stream.jsp"); \\Success condition here
}
else{
response.sendRedirect("file.jsp"); \\ failure condition here
}
}
catch(Exception e)
{
system.out.print(e);
}
Hope this helps!