How to insert data to database using a java mvc - java

I am trying to insert data into a database using java servlets and an mvc. I have a class called CheckoutDb that uses connection pool and prepared statements to insert data.
public class CheckoutDb {
public static int insert(Checkout checkout) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query
= "INSERT INTO Checkout (FirstName, LastName, EmailAddress, "
+ "BookTitle, DueDate) "
+ "VALUES (?, ?, ?, ?, ?)";
try {
ps = connection.prepareStatement(query);
ps.setString(1, checkout.getFirstName());
ps.setString(2, checkout.getLastName());
ps.setString(3, checkout.getEmailAddress());
ps.setString(4, checkout.getBookTitle());
ps.setString(5, checkout.getFormattedDate());
return ps.executeUpdate();
} catch (SQLException e) {
System.out.println(e);
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
The problem I seem to be having is actually inserting the data from the controller class. I have tried gettting the request params from the form and then storing them to the object and then calling the insert method from the CheckoutDb class, but it will not insert any data to the table. Any help would be greatly appreciated. If more code is needed to display, I will provide if needed. Thanks.
private String doCheckout(HttpServletRequest request,
HttpServletResponse response) {
String firstName= request.getParameter("first_name");
String lastName= request.getParameter("last_name");
String emailAddress= request.getParameter("email_address");
String bookTitle= request.getParameter("book_title");
Checkout checkout=new Checkout();
Date date= checkout.getDueDate();
//TODO: Implement code to check out the book here.
checkout=new Checkout(firstName,lastName,emailAddress,bookTitle,date);
CheckoutDb.insert(checkout);
return "/thankyou.jsp";
}

Solution:
After issuing ps.executeUpdate(), you need to issue connection.commit(). That will make the changes permanent to the database and you will be able to see the changes in the database using another connection. JDBC tutorial (http://docs.oracle.com/javase/tutorial/jdbc/TOC.html) can give you details on how to manage transactions using commit/rollback.

Related

JDBC Driver Problem in a Dynamic Web Project

I have a problem with a Dynamic Web Project, I've been with this error for a couple of weeks and I can not solve it, it's about jdbc driver.
public class DatosDAO {
private String url = "jdbc:mysql://localhost:3306/BCopia";
private String usuario = "root";
private String password = "";
public DatosDAO() {}
public boolean alta(Datos d) {
try {
Connection con = DriverManager.getConnection(url,usuario,password);
PreparedStatement ps = con.prepareStatement("INSERT INTO datos VALUES (null, ?, ?, ?, ?)");
ps.setString(1, d.getNombre());
ps.setString(2, d.getDirectorioOrigen());
ps.setString(3, d.getDirectorioDestino());
ps.setInt(4, d.getIntervaloDias());
ps.executeUpdate();
con.close();
} catch (Exception ex) {ex.printStackTrace();return false;}
return true;
}}
When attempt to run this method or any other method. I get the following error.
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/BCopia at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
modelo.DatosDAO.baja(DatosDAO.java:44) at
control.Securalia.baja(Securalia.java:43) etc
I have the driver in lib and have the driver called in the build path and everything else, it is a dynamic web project. Can someone tell me what happens? The DB exists, etc.
First of all you have to add the database driver to the project library. after that you should mention the driver class name here's an example with firebird driver :
Class.forName("org.firebirdsql.jdbc.FBDriver");
Check your mysql jdbc driver to find the class name
next you can establish a connection to you're database exactly like you've done with a connection URL and call the driver manager, here's an example :
String connectionURL = "jdbc:firebirdsql://127.0.0.1:3030/c:\\db.fdb";
Connection conn = DriverManager.getConnection(connectionURL, userName,password);
good luck !

Why is the Google App Engine JDBC connection URL not working?

I am developing a Website with a Registration page. I want to store the user details in the table of the MySQL database on Google App Engine. Following is the JDBC connection URL:-
Connection con = DriverManager.getConnection("jdbc:mysql://google/my_database_name?cloudSqlInstance=my_db_instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=My_Username&password=My_Password&useSSL=false", "root", "My_Password");
But this URL isn't working as even after registering, no details are stored in the table of my database. So, do suggest any alternatives. Thank you
The following is the RegistrationServlet code which takes input values from Register.jsp and I want it to store the values into my gcloud db table:-
#WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1 L;
public RegistrationServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String first_name = request.getParameter("f1");
String last_name = request.getParameter("l1");
String phone = request.getParameter("p1");
String email = request.getParameter("e1");
String uname = request.getParameter("uname");
String user_dob = request.getParameter("udate");
String password = request.getParameter("pwd");
UserData ud = new UserData();
ud.setFirst_name(first_name);
ud.setLast_name(last_name);
ud.setUname(uname);
ud.setPhone(phone);
ud.setEmail(email);
ud.setUser_dob(user_dob);
ud.setPassword(password);
// validate given input
if (first_name.isEmpty() || last_name.isEmpty() || phone.isEmpty() || email.isEmpty() || password.isEmpty()) {
RequestDispatcher rd = request.getRequestDispatcher("Register.jsp");
out.println("<font color=red>Please fill all the fields</font>");
rd.include(request, response);
} else {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// loads mysql driver
try {
Connection con = DriverManager.getConnection("jdbc:mysql://google/my_database_name?cloudSqlInstance=my_db_instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=My_Username&password=My_Password&useSSL=false", "root", "My_Password");
String query = "insert into users values(?,?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(query); //generates sql query
ps.setString(1, first_name);
ps.setString(2, last_name);
ps.setString(3, uname);
ps.setString(4, phone);
ps.setString(5, email);
ps.setString(6, user_dob);
ps.setString(7, password);
ps.executeUpdate();
System.out.println("successfully inserted");
ps.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpSession session = request.getSession();
session.setAttribute("username", first_name);
response.sendRedirect("Success.jsp");
}
}
I've followed the GCP CloudSQL for MySQL connection example and it has worked after deployment. I'll go step by step of the process I did so you can compare and see if there's some configuration step missing on your end.
Used a MySQL 2nd Gen Cloud SQL instance. This instance is in the same project as the Google App Engine I'll deploy the script in
Created a new database in the CloudSQL instance
Ran the command gcloud sql instances describe instance1 to get the instance connection name in the form of <MY-PROJECT>:<REGION>:<INSTANCE-NAME>
Downloaded the GCP Java code samples and got to the Java 8 App Engine standard Cloud SQL example:
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
cd java-docs-samples/appengine-java8/cloudsql/
Completed the fields <INSTANCE_CONNECTION_NAME>, <user>, <password> and <database> from the POM file with the connection values for my case. This fields will be used by the appengine-web.xml to create the cloudsql property that will be used as the connection URL by the code in CloudSqlServlet.java
Also in the appengine-web.xml, I changed the <service> name to default. There's actually no need to change anything on this file but I chose to change the service due to personal preference
The other required dependencies where already in the downloaded POM
Deployed to GAE with mvn appengine:deploy
This is a minimal example of a working GAE to Cloud SQL connection for MySQL. Try to follow this steps to test if the connection works poperly with the provided code example.

JDBC, connection is ok but does not execute query

I'm writing a small program with a mysql connection. I have to insert data into the database. The connection is ok but when I try to execute a query it doesn't work. all statements after executeQuery() statement doesn't work.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection connect=null;
PreparedStatement preparedStatement;
String JDBC_DRIVER="com.mysql.jdbc.Driver";
String DB_URL="jdbc:mysql//localhost/jarvis";
String USER = "test";
String PASS = "test";
try{
Class.forName(JDBC_DRIVER);
connect = DriverManager.getConnection(DB_URL, USER, PASS);
}
catch(ClassNotFoundException e){
out.println("Errore: "+e);
} catch (SQLException ex) {
Logger.getLogger(Prova.class.getName()).log(Level.SEVERE, null, ex);
}
out.println();
out.println("qui");
String query = "INSERT INTO users(Nome, Cognome, Username, Password) values(?, ?, ?, ?)";
try (PreparedStatement insert = connect.prepareStatement(query)) {
insert.setString(1, "name");
insert.setString(2, "sur");
insert.setString(3, "gvhgv");
insert.setString(4, "qfwe");
insert.executeUpdate();
}
catch(Exception e){
out.println("Errore "+e);
}
out.println("Fine");
}
on executeQuery it stop working and doesn't insert the values into the database.
P.S.: sorry for my English
foto
Firstly your JDBC Connection URL is wrong, it should be this
String DB_URL = jdbc:mysql://localhost/jarvis
instead of this:
String DB_URL = jdbc:mysql//localhost/jarvis
You can follow the MySQL documentation whenever you are in doubt about anything.
Please note that mentioning port is not necessary if it is skipped it would default to MySQL's default port 3306.
Secondly, use executeUpdate() method instead of executeQuery method. It is best suggested to test your code in chunks, like DB Connection is successful, able to retrieve data from the underlying DB and then inserting into the DB.
Or even a better way is to debug your code and at least provide where you find the NullPointerException as you say you're getting now!
Edit:
You must have your JDBC Connector/J jar available for your code to access it if you use an IDE (then in its build path) and in the CLASSPATH global variable (for references when we don't use an IDE). It is better to have it on your CLASSPATH if you are not going to change these dependencies any often.
Hope this helps!

I am try to insert data in mysql table

I want to insert data in 2 table with single query. bt it gives error
mycode is shown below.
public class Trains extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
int tid=Integer.parseInt(request.getParameter("tid"));
String tname=request.getParameter("tname");
String ttype=request.getParameter("ttype");
String stncode=request.getParameter("stn_code");
String stnname=request.getParameter("stn_name");
String availtime=request.getParameter("Avail_time");
String depttime=request.getParameter("Dep_time");
String halttime=request.getParameter("Halt_time");
String dist=request.getParameter("distance");
String[] avail_day=request.getParameterValues("week");
try {
String query="INSERT INTO Train_info(Train_ID,Train_Name,Train_Type,Runs_On) values(?,?,?,?); INSERT INTO Train_route(stn_code,stn_name,arrival_time,Destn_time,Halt_time,Distance) values(?,?,?,?,?,?)";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/Railway","root","mysql123");
PreparedStatement ps=con.prepareStatement(query);
ps.setInt(1, tid);
ps.setString(2, tname);
ps.setString(3, ttype);
ps.setString(4, stncode);
ps.setString(5, stnname);
ps.setString(6, availtime);
ps.setString(7, depttime);
ps.setString(8, halttime);
ps.setString(9, dist);
for(int i=0;i<avail_day.length;i++){
ps.setString(10, avail_day[i]);
}
int i=ps.executeUpdate();
if(i>0){
out.println("Successfully Registration");
response.sendRedirect("TrainRoute.jsp");
}
else{
out.println("Registration failed");
response.sendRedirect("Error.java");
}
}
catch(ClassNotFoundException ce){
ce.printStackTrace();
}
catch(Exception e){
out.println(e);
}
}
}
error is:-
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO Train_route(stn_code,stn_name,arrival_time,Destn_time,Halt_time,Dist' at line 1
See this: Java - Mysql - Multiple query
The INSERT INTO your syntax error message calls out the second insert in your query string. The MySQL JDBC driver, like most MySQL drivers, only accepts one query per call to Connection.preparedStatement() call.
You'll need to refactor your code to use two prepared statements, once for each table.
If you're used to working with other makes and model of SQL table servers, this restriction can trip you up.

MariaDB connector for JDBC for querying a database created in PhPMyAdmin

I have created a database named vidya with a table named students using PhPMyAdmin. I want to insert values to the database using a Java code. Here's the code but currently has problem with MariaDB JDBC connector plus I am not sure if my DB_URL is correct anyways if it is running on the localhost.
/**
* Created by jalal on 7/6/2016.
*/
import java.sql.*;
import java.util.Calendar;
public class TestPhpMyAdmin
{
public static void main(String[] args)
{
try
{
//static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// create a mysql database connection
String myDriver = "org.mariadb.jdbc";
String DB_URL = "jdbc:mysql://localhost/vidya";
Class.forName(myDriver);
// Database credentials
final String USER = "root";
final String PASS = "newpass";
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into students (ID, last_name, first_name, birthday, hometown)"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setInt(1, 808027);
preparedStatement.setString(2, "Davis");
preparedStatement.setString(3, "Felicita");
preparedStatement.setDate(4, startDate);
preparedStatement.setString(5, "Venice");
// execute the preparedstatement
preparedStatement.execute();
conn.close();
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
I get this error:
org.mariadb.jdbc
Here's the directory structure:
MariaDB's version is 10.1.13-MariaDB
JDBC drivers register themself with DriverManager.registerDriver.
Using DriverManager.getConnection(...), DriverManager will asked each driver if url like 'jdbc:mariadb:..." is handled. If a driver answer is yes, Drivermanager will create a connection using this Driver.
(That will permit to have for example a H2 database for developpement environnement, and a MariaDB database for production just changing the url)
Driver for MariaDB is "org.mariadb.jdbc.Driver", not "org.mariadb.jdbc" that is the driver package, but in fact isn't usefull in this case. This portion of code that is causing the error can be suppressed :
String myDriver = "org.mariadb.jdbc";
Class.forName(myDriver);
According to ojacobson in Java IRC channel there's no need for Class.forName(myDriver); hence I commented it and the value was inserted onto the database table:
Here's the correct code for the reference:
/**
* Created by jalal on 7/6/2016.
*/
import java.sql.*;
import java.util.Calendar;
public class TestPhpMyAdmin
{
public static void main(String[] args)
{
try
{
// create a mysql database connection
String DB_URL = "jdbc:mysql://localhost/vidya";
// Database credentials
final String USER = "root";
final String PASS = "newpass";
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into students (ID, last_name, first_name, birthday, hometown)"
+ " values (?, ?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setInt(1, 808027);
preparedStatement.setString(2, "Davis");
preparedStatement.setString(3, "Felicita");
preparedStatement.setDate(4, startDate);
preparedStatement.setString(5, "Venice");
// execute the preparedstatement
preparedStatement.execute();
conn.close();
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}
For mariadb is: jdbc:mariadb://localhost/ and don't need classforname if your java version above 1.6
ClassForName is for java below 1.6.
Change this line:
import java.sql.*;
import java.sql.Date;
And java.sql.Date make change for Date only.
Don't use import java.sql.*;

Categories