JSP (3)----JDBC Programming 2

Source: Internet
Author: User

Connect to the following section:

http://4440271.blog.51cto.com/4430271/1661684 to the upper section

Program Modification:

package com.jike.jdbc;import java.sql.connection;import java.sql.drivermanager;import  java.sql.sqlexception;import java.sql.statement;public class transactiontest {public  Static connection getconnection ()  {connection conn = null;try { Class.forName ("Com.mysql.jdbc.Driver"); Conn = drivermanager.getconnection ("Jdbc:mysql://localhost : 3306/info ", " * * * * * * * * * ", " ****** ");}  catch  (exception e)  {// todo: handle exceptione.printstacktrace ();} Return conn;}   Inserting data into the user table//  Code modification Public static void insertuserdata (connection conn)   Throws sqlexception {// ctrl+shift+f format Code string sql =  "Insert into tbl _user (id, name, password, email) "+ " VALUES (10,  ' Tom ',  ' 2525252 ',  ' [email  protected] "; Statement st = conn.createstatement (); int count  = st.executeupdate (SQL); System.out.println ("Insert"  + count +  "bar data into user table");// conn.close ();}   Inserting data into the Address Table Public static void insertaddressdata (connection conn)  throws  sqlexception {string sql =  "Insert into tbl_address (Id, city, country,  user_id) "+ " VALUES (1,  ' Shanghai ',  ' China ',  ' 10 ') "; Statement st = conn.createstatement (); int count = st.executeupdate (SQL); System.out.println ("entry to the Address table"  + count +  "records");// conn.close ();} Public static void main (String[] args)  {connection conn = null;try  {conn = getconnection (); Conn.setautocommit (false); //  prohibit transactions from automatically committing Insertuserdata (conn); INSERTADDRESSDATA (conn);//  here, the commit Insertaddressdata method is to throw an exception, the exception is caught, so the transaction is rolled back. Commit Transaction Conn.commit ();}  catch  (exception e)  {system.out.println ("************* capture to sq anomaly * *"); E.printstacktrace (); Try {conn.rollback ();  //rollback SYSTEM.OUT.PRINTLN If commit failed (" transaction rollback succeeded ");}  catch  (Exception e2)  {// todo: handle exceptione2.printstacktrace ();}} Finally{try {if (conn != null) {conn.close ();}}  catch  (EXCEPTION E3)  {// todo: handle exceptione3.printstacktrace ();}}}



Output Result:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6E/6E/wKioL1V8dG3j-FrNAAPgFJyMhHQ266.jpg "title=" Qq20150614021257.jpg "alt=" Wkiol1v8dg3j-frnaapgfjymhhq266.jpg "/>

In the database:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6E/71/wKiom1V8cv3DuuSAAAD8jBiZGdQ758.jpg "title=" Qq20150614021402.jpg "alt=" Wkiom1v8cv3duusaaad8jbizgdq758.jpg "/>

The data is not inserted, indicating that the rollback was successful and that the consistency of the data was not compromised.




JDBC Programming Optimizations:


Extract the configuration information and put it in the properties file:

Create the properties file: Right-click in the SRC directory and tap new--> Other---general-->file-->next---> file name. Properties-->finish

Click Add to add the following:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6E/6E/wKioL1V85AKxicIvAAEPnDc4aCE796.jpg "title=" Qq20150614100839.jpg "alt=" Wkiol1v85akxicivaaepndc4ace796.jpg "/>

Click on the source below to see:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6E/72/wKiom1V84rXCTZspAACkbpeJf3c725.jpg "title=" Qq20150614101036.jpg "alt=" Wkiom1v84rxctzspaackbpejf3c725.jpg "/>


Create the following two classes:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6E/6E/wKioL1V85Nzh6lFKAABoDc97saM116.jpg "title=" Qq20150614101210.jpg "alt=" Wkiol1v85nzh6lfkaabodc97sam116.jpg "/>

To add code to the factory class:

package com.jike.jdbc.util;import java.io.inputstream;import java.sql.connection;import  java.sql.drivermanager;import java.util.properties;//  Create a database connection factory class, placed under the Util package public class  connectionfactory {//  creates four member variables to hold the read-out database configuration information in the subordinate file private static string driver; private static string dburl;private static string user;private static  string password;private static final connectionfactory factory = new  ConnectionFactory ();//define Connection type variable to keep the data connection private connection conn;//  read the configuration information static{// Static code blocks are used to initialize classes, assign values to the properties of a class, and static code blocks execute only once properties prop = new properties ();//define attribute classes to hold key-value pairs in a property file to try  {inputstream in = connectionfactory.class.getclassloader (). GetResourceAsStream (" Dbcofig.properties ");//  gets the contents of the properties file//  first obtains the class loader of the current class, and then reads the contents of the properties file through the getResourceAsStream method in the loader.   This method reads the contents of the properties file into an input stream prop.load (in);//from the input streamRead the list of properties in the properties file, which is the list of key-value pairs in the} catch  (exception e)  {// TODO: handle  EXCEPTIONSYSTEM.OUT.PRINTLN ("Read configuration file Error");} Assign the value read to the member variable Driver = prop.getproperty ("Driver");d Burl = prop.getproperty ("Dburl");  = prop.getproperty ("user");p assword = prop.getproperty ("password");}   Defines the default constructor private connectionfactory () {}//  used to get the ConnectionFactory instance public static  Connectionfactory getinstance () {return factory;}   How to get a database connection public connection makeconnection () {try {class.forname (driver); conn =  drivermanager.getconnection (Dburl, user, password);}  catch  (exception e)  {// todo: handle exceptione.printstacktrace ();} Return conn;}}


Add the following code to the test class:

Package Com.jike.test;import Java.sql.connection;import Com.jike.jdbc.util.connectionfactory;public class connectionfactorytest {/** * @param args */public static void main (string[] args) throws exception{//TODO auto-generated Method Stubconnectionfactory CF = Connectionfactory.getinstance (); Connection conn = Cf.makeconnection (); System.out.println (Conn.getautocommit ());}}


Test result is: true


Then create the appropriate DTO

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6E/72/wKiom1V86XXy9K0qAAA4NwvXzuI726.jpg "title=" Qq20150614103911.jpg "alt=" Wkiom1v86xxy9k0qaaa4nwvxzui726.jpg "/>

Add the corresponding entity class:

In the Identity class:

Package com.jike.entity;//encapsulating primary key information public abstract class IdEntity {protected Long id;public long getId () {return ID;} public void SetId (Long id) {this.id = id;}}


In the user class:

package com.jike.entity;//  entity class to create user information public class  user extends identity {//  adds a member property corresponding to the user table's property one by one in the database private string name;private  string password;private string email;public string getname ()  {return  Name;} Public void setname (String name)  {this.name = name;} Public string getpassword ()  {return password;} Public void setpassword (String password)  {this.password = password;} Public string getemail ()  {return email;} Public void setemail (String email)  {this.email = email;} @Overridepublic  string tostring ()  {return  "User [name="  + name +  ",  password="  + password +  ",  email=" + email +  ",  id="   + id +  "]";}} 


In the address class:

package com.jike.entity;public class address extends  IdEntity {private String city;private String country;private Long  Userid;public string getcity ()  {return city;} Public void setcity (string city)  {this.city = city;} Public string getcountry ()  {return country;} Public void setcountry (String country)  {this.country = country;} Public long getuserid ()  {return userid;} Public void setuserid (Long userid)  {this.userid = userid;} @Overridepublic  string tostring ()  {return  "address [city="  + city +   ",  country="  + country +  ",  userid=" + userid +  ",  id="  + id +  "]";}} 


This completes the creation of the entity class.


Create DAO

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6E/73/wKiom1V9BC6wkTLJAABSFDLcZSg309.jpg "title=" Qq20150614123319.jpg "alt=" Wkiom1v9bc6wktljaabsfdlczsg309.jpg "/>

Add in Interface Userdao:

Package Com.jike.dao;import Java.sql.connection;import Java.sql.sqlexception;import com.jike.entity.user;//  Define the behavior of the implementation class public interface Userdao {//define operations on the database public void Save (Connection conn, user user) throws Sqlexception;public void Update (Connection conn, Long ID, user user) throws Sqlexception;public void Delete (Connection conn, user user) throws SQL Exception;}


Add in the implementation class Userdaoimpl of the interface

Package com.jike.dao.impl;import java.sql.connection;import java.sql.preparedstatement;import  java.sql.SQLException;import com.jike.dao.UserDao;import com.jike.entity.User;public  class userdaoimpl implements userdao {/* *  Saving user information  */@Overridepublic   Void save (Connection conn, user user)  throws sqlexception {// todo  auto-generated method stub//preparedstatement is one of the APIs that JDBC uses to execute SQL query statements to perform parameterized queries//? is the placeholder preparedstatement ps = conn.preparestatement ("Insert into tbl_user (name,  Password, email)  values  (?,?,?) "); /Parameter Setting ps.setstring (1, user.getname ());//index starting from 1 ps.setstring (2, user.getpassword ());p s.setstring (3,  user.getemail ());p s.execute ();//Save the relevant information in the user object passed in the parameter to the database table}/* *  Update the user information based on the user ID  */@ Overridepublic void update (Connection conn, long id, user user)  throws &nbsp sqlexception {// todo auto-generated method stubstring updatesql =  " Update tbl_user set name=?, password=?, email=? where id=? "; Preparedstatement ps = conn.preparestatement (Updatesql);p s.setstring (1, user.getName ()); Ps.setstring (2, user.getpassword ());p s.setstring (3, user.getemail ());p S.setlong (4, id); Ps.execute ();} /* *  Delete the specified user information  */@Overridepublic  void delete (connection conn, user  User)  throws SQLException {// TODO Auto-generated method  Stubpreparedstatement ps = conn.preparestatement ("Delete from tbl_user where  id=? "); Ps.setlong (1, user.getid ());p S.execute ();}}


To add a test program:

package com.jike.test;import java.sql.connection;import com.jike.dao.userdao;import  com.jike.dao.impl.userdaoimpl;import com.jike.entity.user;import  com.jike.jdbc.util.connectionfactory;public class userdaotest {/** *  @param  args  */public static void main (String[] args)  {// todo auto-generated  method stubConnection conn = null;try {conn =  Connectionfactory.getinstance (). MakeConnection (); Conn.setautocommit (false); System.out.println (Conn.getautocommit ()); Userdao userdao = new userdaoimpl (); User tom = new user (), Tom.setname ("Tom"), Tom.setpassword ("123"); Tom.setemail ("[email  Protected] Userdao.save (Conn, tom); Conn.commit ()  //Commit transaction} catch  (exception e)   {// todo: handle exceptiontry {conn.rollback ();}  catch  (EXCEPTION E2)  {// TODO:&NBSp;handle exceptione2.printstacktrace ();}}} 


View the database and submit the newly added data successfully.







Geek College: http://www.jikexueyuan.com/course/566_6.html?ss=2



JSP (3)----JDBC Programming 2

Related Article

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.