JDBC and jdbc connect to the database

Source: Internet
Author: User

JDBC and jdbc connect to the database

JDBC-development instance-MVC Mode

1. Configure the database connection information in web. xml

Web. xml:

<Context-param>

<Param-name> server </param-name> // host name

<Param-value> localhost </param-value>

</Context-param>

<Context-param>

<Param-name> db </param-name> // Database

<Param-value> test </param-value>

</Context-param>

<Context-param>

<Param-name> user </param-name> // user name

<Param-value> root </param-value>

</Context-param>

<Context-param>

<Param-name> password </param-name> // password

<Param-value> 1234 </param-value>

</Context-param>

2. Data Layer-create entity class Student. java

Student. java:

Package gh. test. entity;

  

Public class Student {

Private int id;

Private String name;

Private int gender;

Private int age;

Private String address;

Private String tel;

Public void setId (int id) {// student id

This. id = id;

}

Public int getId (){

Return id;

}

Public void setName (String name) {// name

This. name = name;

}

Public String getName (){

Return name;

}

Public void setGender (int gender) {// gender

This. gender = gender;

}

Public int getGender (){

Retuen gender;

}

Public void setAge (int age) {// age

This. age = age;

}

Public int getAge (){

Return age;

}

Public void setAddress (String address) {// address

This. address = address;

}

Public String getAddress (){

Return address;

}

Public void setTel (String tel ){

Return tel;

}

}

3. Data access layer-create database operation class DB. java & StudentDao class StudentDao. java

DB. java:

Package gh. test. dao;

 

Import java. SQL. DriverManager;

Import java. SQL. Connection;

Import java. SQL. PreparedStatement;

Import java. SQL. ResultSet;

Import java. SQL. SQLException;

  

Public class DB {

Connection conn = null;

PreparedStatement ps = null;

ResultSet rs = null;

Public Connection getConn

(String server, String db, String user, String password) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {// get object

String driver = "com. mysql. jdbc. Driver ";

String url = "jdbc: mysql: //" + server + ": 3306/" + db + "? User = "+ user +" & password = "+ password +" & characterEncoding = UTF-8 ";

Class. forName (driver); // load the driver

Connection conn = DriverManager. getConnection (url); // create a Connection object

Return conn;

}

Public ResultSet executeQuery (String SQL, String [] params) {// execute the query operation

Try {

Ps = conn. prepareStatement (SQL );

If (params! = Null ){

For (int I = 0; I <params. length; I ++ ){

Ps. setString (I + 1, params [I]);

}

}

Rs = ps.exe cuteQuery ();

}

Catch (SQLException ex ){

Ex. printStackTrace ();

}

Return rs;

}

Public int executeUpdate (String SQL, String [] params) {// execute the update operation

Int n = 0;

Try {

Ps = conn. prepareStatement (SQL );

If (params! = Null ){

For (int I = 0; I <params. length; I ++ ){

Ps. setString (I + 1, params [I]);

}

N = ps.exe cuteUpdate ();

}

} Catch (SQLException ex ){

Ex. printStackTrace ();

}

Return n;

}

Public void closeAll (){

If (rs! = Null ){

Try {

Rs. close ();

} Catch (SQLException ex ){

Ex. printStackTrace ();

}

}

If (ps! = Null ){

Try {

Ps. close ();

} Catch (SQLException ex ){

Ex. printStackTrace ();

}

}

If (conn! = Null ){

Try {

Conn. close ();

} Catch (SQLException ex ){

Ex. printStackTrace ();

}

}

}

}

 

StudentDao. java:

Package gh. test. dao;

Import gh. test. entity. Student;

  

Public class StudentDao extends DB {

Public int addStudent (Student student ){

String name = student. getName ();

String gender = student. getGender () + "";

String age = student. getAge () + "";

String address = student. getAddress ();

String tel = student. getTel ();

String [] params = new String [] {name, gender, age, address, tel };

String SQL = "insert into studentInfo values (?,?,?,?,?) ";

Int result = super.exe cuteUpdate (SQL, params );

Return result;

}

}

 

4. Graphic Display layer &logic processing -addstudent.html & AddStudentServlet. java

AddStudent.html:

<Html>

<Head>

<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">

<Title> Add Student Information </title>

</Head>

<Body>

<Form name = "form1" action = "AddStudentServlet" method = "post">

<Table>

<Tr>

<Th colspan = "2"> Student Information </th>

</Tr>

<Tr>

<Td> name: </td>

<Td> <input type = "text" name = "name"/> </td>

</Tr>

<Tr>

<Td> Gender: </td>

<Td>

<Input type = "radio" name = "gender" value = "0" check = "checked"/> male & nbsp;

<Input type = "radio" name = "gender" value = "1"/> female

</Td>

</Tr>

<Tr>

<Td> Age: </td>

<Td>

<Select name = "age">

<Option value = "18" select = "selected"> 18 </option>

<Option value = "19"> 19 </option>

<Option value = "20"> 20 </option>

<Option value = "21"> 21 </option>

<Option value = "22"> 22 </option>

</Select>

</Td>

</Tr>

<Tr>

<Td> address: </td>

<Td> <input type = "text" name = "address"/> </td>

</Tr>

<Tr>

<Td> Tel: </td>

<Td> <input type = "text" name = "tel"/> </td>

</Tr>

<Tr>

<Td colspan = "2" align = "center">

<Input type = "submit" name = "tj" value = "submit" onclick = "check ();"/> & nbsp;

<Input type = "reset" name = "cz" value = "reset"/>

</Td>

</Tr>

</Table>

</Form>

<Script language = "javascript">

Function check (){

If (document. form1.name. value = ""){

Alert ("enter your name! ");

Document. form1.name. focus ();

Return false;

}

If (document. form1.age. value = ""){

Alert ("Enter age! ");

Document. form1.age. focus ();

Return false;

}

If (document. form1.address. value = ""){

Alert ("Enter the address! ");

Document. form1.address. focus ();

Return false;

}

If (document. form1.tel. value = ""){

Alert ("Enter your phone number! ");

Document. form1.tel. focus ();

Return false;

}

Return true;

}

</Script>

</Body>

</Html>

 

 

AddStudentServlet. java:

Package gh. test. servlet;

Import java. io. IOException;

Import java. io. PrintWriter;

Import java. SQL. SQLException;

Import javax. servlet. ServletContent;

Import javax. servlet. ServletException;

Import javax. servlet. http. HttpServlet;

Import javax. servlet. http. HttpServletRequest;

Import javax. servlet. http. HttpServletResponse;

 

Import gh. test. entity. Student;

Import gh. test. dao. StudentDao;

Public class AddStudentServlet extends HttpServlet {

Private static final long serialVersionUID = 1L;

Public AddStudentServlet (){

Super ();

}

Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

DoPost (request, response );

}

Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Request. setCharacterEncoding ("UTF-8 ");

Response. setContentType ("text/html; charset = UTF-8 ");

PrintWriter out = response. getWriter ();

String name = request. getParameter ("name ");

Int gender = Integer. parseInt (request. getParameter ("gender "));

Int age = Integer. parseInt (request. getParameter ("age "));

String address = request. getParameter ("address ");

String tel = request. getParameter ("tel ");

Student student = new Student ();

Student. setName (name );

Student. setGender (gender );

Student. setAge (age );

Student. setAddress (address );

Student. setTel (tel );

ServletContext ctx = this. getServletContext ();

String server = ctx. getInitParameter ("server ");

String db = ctx. getInitParameter ("db ");

String user = ctx. getInitParameter ("user ");

String password = ctx. getInitParameter ("password ");

StudentDao studentDao = new StudentDao ();

Try {

StudentDao. getConn (server, db, user, password );

If (studentDao. addStudent (student) = 1 ){

Out. print ("new student information added successfully! <Br> ");

}

Else {

Out. print ("failed to add! <Br> ");

}

Out. print ("<a href='addStudent.html '> return </a> ");

} Catch (ClassNotFoundException ex ){

Ex. printStackTrace ();

} Catch (Exception ex ){

Ex. printStackTrace ();

}

}

}

 

 

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.