Write JSP Usuing MySql
Write JSP Usuing MySql
http://mrbool.com/jsp-with-mysql/29848
Creating a database:
In this article we will develop with creating an empty database. This
Program model consists of two jsp files. One is called index.jsp and
validation.jsp. The validation.jsp creates a new database or reports
an error in validation.jsp file.
<jsp:declaration>
Statement stmt;
Connection con;
String url = "jdbc:mysql://localhost:3306/";
</jsp:declaration>
Here we declare a Statement, Connection and a URL to connect. The
URL (connection)is having a protocol, host and a port number. The
default MySQL port number is 3306.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,"root","mrbool");
stmt = con.createStatement();
stmt.executeUpdate("Create Database Course..");
con.close();
mysql> create table course(id int not null primary key auto_increment,
cname varchar(30), duration varchar(40), amt int);
We create a course table first. The table will have five columns. The
fields are id, cname, duration of the course, amount of the course.
Now we see that the table which looks likes as using the MySQL
command line tools. The style.css file defines the style of our
application and it also defines the look and feel of input boxes,
buttons, tables and anchors. It also generates a navigation toolbar
for our project.
The index.jsp file is used to add new course into the database. In the
form we input data and submit it.
<%
String author = request.getParameter("id");
String title = request.getParameter("cname");
String year = request.getParameter("duration");
String remark = request.getParameter("amt");
%>
<br><br>
<form method="post" name="form">
<table border="1">
<tr><th>Course Id</th><th>Course
Name</th><th>Duration</th><th>Amount</th></tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "cei";
String driver = "com.mysql.jdbc.Driver";
String userName ="root";
String password="srimani";
int sumcount=0;
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db,userName,password);
out.println(con);
String q = "select * from course";
st = con.createStatement();
ResultSet rs = st.executeQuery(q);
%>
<%
while(rs.next())
{
%>
<tr><td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
<td><input type="button" name="edit" value="Edit" style="background-
color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRec (<
%=rs.getString(1)%>);" ></td>
<td><input type="Button" name="delete" value="Delete" style="background-
color:#ff0000;font-weight:bold;color:#ffffff;" onclick="deleteRec(<
%=rs.getString(1)%>);" ></td>
</tr>
<%
}
%>
<%
}
catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>