Struts2 connect with mysql
Aim:
In struts2, how to connect with mysql.
Procedure:
Step 1:
Open mysql
Step 2:
Create database such as Struts2.
Mysql > create database struts2;
Step 3:
Mysql> use struts2;
Step 4:
Create table such as student.
Mysql > create table student (username varchar(40));
Step 5:
Create project mySQLProject
Step 6:
Create Action mysqlAction.java
Include following coding into mysqlAction.java
package example;
import com.opensymphony.xwork2.ActionSupport;
import java.sql.*;
public class mysqlAction extends ActionSupport
{
private String username;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public mysqlAction()
{
}
public String execute() throws Exception
{
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/struts2","root","sure");
stmt=con.createStatement();
int i= stmt.executeUpdate("insert into student values('"+username+"')");
if(i==0)
return "failure";
else
return "success";
}
}
Step 7:
Create home.jsp
< %@taglib uri="/struts-tags" prefix="s" % >
< html >
< head >
< meta content=”keyword” name=”struts2 mysql Example" >
< title > Home < /title >
< /head >
< body >
< s:form action="exam" method="post" >
< s:textfield label="UserName" name="username"/ >
< s:submit value="OK"/ >
< /s:form >
< /body >
< /html >
success.jsp
< %@taglib uri="/struts-tags" prefix="s" % >
< html >
< head >
< meta content=”keyword” name=”struts2 mysql Example" >
< title > Home < /title >
< /head >
< body >
< h2 > Successfully inserted < /h2 >
< /body >
< /html >
Step 8:
Made some changes in struts.xml
< !DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
http://struts.apache.org/dtds/struts-2.0.dtd >
< struts >
< package name="example" namespace="/example" extends="struts-default" >
< action name="exam" class="example.mysqlAction" >
< result name="input" > /example/home.jsp < /result >
< result name="success" > /example/success.jsp < /result >
< /action >
< /package >
< /struts >
Step 9:
Add mysql-connector-java-5.1.6-bin
Right click on MySQLProject and select properties where under categories select library and select compile and click Add JAR/Folder and select where you stored mysql-connector-java-5.1.6-bin and ok.
Step 10:
Run home.jsp
you enter any values such as sureshkumar
Mysql> use struts2;
ReplyDeleteThis isnt a mysql command?
Consider There are some databases available in mysql. How to change the database to database? Which command is used?
DeleteSend What is the use of USE in mysql?