Servlet inserting records into the Database with Java Servlets.
Overview:
This article's next in the series of articles about selecting, inserting, updating and deleting records from the database Using JDBC. In this article we'll learn how to insert records into the database. If you have followed I earlier article about ' displaying Records from the Database ' then this article are not going to be Difficult at all. 90% of the code would be same. So if you haven ' t read that article then I'll suggest that your go through then article before starting this one as quite A few important things have been explained in detail there.
How to Insert Records?
To insert records into the database we'll have to learn about another JDBC class, PreparedStatement. Although we can insert records using the Statement class we discussed in the last article, the insert operation is less EF Ficient and not optimized in all. PreparedStatement fills that gap and lets us builds SQL queries which are compiled and thus more efficient.
Note that isn't all database vendors support PreparedStatement class but still it isn't a bad habit to use this class so th At the ones this does support PreparedStatement class get the extra efficiency.
PreparedStatement:
This class like other JDBC classes we have been discussing are present in the java.sql package. This are how to get handle on a PreparedStatement object:
String sql = "INSERT into Names (first_name, last_name) VALUES (?,?)";
Connection.preparestatement () returns a reference to the PreparedStatement object. The only argument to the Connection.preparestatement () method was an SQL statement containing optional '? ' (question mark) containing SQL statement.
Should put '? ' marks in the statement where you are are going to put or change the values, for example in my example above I placed '? ' marks at two places where I'll put different values depending on the values inserted by the user.
So how to set the values of '? ' parameters. The set the values by using a setxxx () methods of PreparedStatement class. Setxxx () are over methods whose syntax was setobject (int paramindex, Object o) where Paramindex is the number of '? ' K-from-right in the SQL statement. For example we'll use SetString (1, value1) and SetString (2, value2) methods to set the value of both parameters to two D Ifferent values.
Ps.setstring (1, "The Name of");
Ps.setstring (2, "last Name");
Ps.executeupdate ();
Once the parameters are set in the PreparedStatement object, we execute the query using Preparedstatement.executeupdate () Method. should use Preparedstatement.executeupdate () for INSERT, UPDATE and DELETE SQL queries and preparedstatement.executequ Ery () for any SQL statement that returns records.
On the next page we make use of PreparedStatement object to develop a user Form page in which a user can enter his-a nd last name and when presses the ' Submit ' button the records are inserted into the database using the methods we just dis cussed.
Insertservlet:
Create a new Insertservlet.java file in The/app_name/web-inf/classes/com/stardeveloper/servlets/db/folder. Note/app_name/is the path of your application within your application server, in Tomcat 4.0/app_name/will Be/catalina _home/webapps/star/where ' star ' is the name of the application.
Copy and paste the following code into the Insertservlet.java file:
catch (SQLException e) {
throw new Servletexception (e);
catch (ClassNotFoundException e) {
throw new Servletexception (e);
finally {
try {
if (Rs!= null)
Rs.close ();
if (stmt!= null)
Stmt.close ();
if (PS!= null)
Ps.close ();
if (Con!= null)
Con.close ();
catch (SQLException e) {}
}
Out.print ("</body>Out.close ();
}
}
Start your application server and point your browser to http://localhost:8080/star/servlet/ Com.stardeveloper.servlets.db.InsertServlet to the Servlet on your computer. To "to" the demo please "move on" to the "last page" of this article.
For explanation of Insertservlet code above, please proceed to the next page.
Explanation:
Our Insertservlet class extends from HttpServlet class and overrides two methods; Doget () and DoPost (). In Doget () "We simply display a Form to the" User with two input fields for the I and last names and two submit buttons, one For inserting and the other one for displaying records.
String a = Req.getparameter ("a"). Trim ();
String last = Req.getparameter ("last"). Trim ();
Boolean proceed = false;
if (!= null && last!= null)
if (first.length () > 0 && last.length () > 0)
proceed = true;
In DoPost () We retrieve the "I" and "Last Name values" entered by the user using Httpservletrequest.getparameter () method.
Using a double if statement we make sure so we are not entering null values into the database. If user has entered both and last name then we proceed.
Connection con;
Statement stmt;
ResultSet rs;
PreparedStatement PS;
We declare the objects we are going to use to interact with the database.
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
Con=drivermanager.getconnection ("JDBC:ODBC:ODBC_EXMP");
We load the Sun ' s JDBC/ODBC driver and establish connection to our database using the DSN ' ODBC_EXMP '. Notice This is the same database we used in ' displaying Records from the database '. Please consult this article to the steps of creating such a database and assigning DSN.
String sql = "INSERT into Names (first_name,");
SQL + + "last_name" VALUES (?,?);
PS = con.preparestatement (SQL);
stmt = Con.createstatement ();
We build the SQL statement which we'll use to insert records into the database. Next we create the PreparedStatement and Statement objects using Connection object ' s methods.
if (proceed) {
Ps.setstring (1, a);
Ps.setstring (2, last);
Ps.executeupdate ();
}
Next we set the two '? ' Mark parameters in our PreparedStatement object and insert the records using PreparedStatement.exe Cuteupdate () method.
rs = Stmt.executequery ("SELECT * from Names");
while (Rs.next ()) {
Out.print (Rs.getobject (1). ToString ());
Out.print ("T");
Out.print (Rs.getobject (2). toString ());
Out.print ("\t\t");
Out.print (Rs.getobject (3). ToString ());
Out.print ("\ n");
}
We Create our ResultSet object by executing the SELECT query. We then iterate through the records and display it to the user. Notice The new record we just inserted would also be visible to the user during this iteration.
if (Rs!= null)
Rs.close ();
if (stmt!= null)
Stmt.close ();
if (PS!= null)
Ps.close ();
if (Con!= null)
Con.close ();
Close all the objects that we created.
I Haven ' t mentioned try. Catch statements that "we used to catch different exceptions" "may be" thrown during opening and closing of database conn Ection.
On the next page I sum up what we learned in this article.
Summary:
In the step by step tutorial we learned what are PreparedStatement class and how-to-build fast SQL statements. We then moved forward to build a simple Form application in which a user enters his-a and last name and values a Re inserted into the database. After "All" the names entered are displayed to user.
The database we used in this article is a Microsoft Access database ' Odbc_exmp.mdb ' that we built in ' displaying Records From the Database ' article. The driver we used is JDBC/ODBC driver, this driver comes with Java Development kits so don ' t need to download and INS Tall it separately. For more information in how we built the ' Odbc_exmp.mdb ' database and what are different types JDBC drivers please consult The above mentioned article.
That ' s It's for this article. Kindly post your questions in the Forum. Hi.
There is no associated material for download
Click here to the demo
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.