JDBC link and encapsulation, JDBC link Encapsulation

Source: Internet
Author: User

JDBC link and encapsulation, JDBC link Encapsulation
Import the jar package of mysql: this package can be used directly. If you do not want to see the source code SQL statement, note that when updating and deleting, pay attention to the where condition and write it !!!

Public static void add () {// try catch exception. If a try exception occurs, it will jump to catch Connection con = null; try {// 1. select the database to be connected --- JDBC load database Driver Class. forName ("com. mysql. jdbc. driver "); // 2. create Link (host name, port number, user name, password) --- url contains host name + port number + database con = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/yyy", "root", "123456"); // 3. select the database for the operation -- this action is integrated in the url in the previous step // 4. CREATE Command window write SQL statement PreparedStatement pstmt = con. prepareStatement ("insert int O zhuce (name, password, sex, id) value (?,?,?,?) "); Pstmt. setString (1, "8888"); pstmt. setString (2, "8888"); pstmt. setString (3, "F"); pstmt. setString (4, "8888"); // 5. run the SQL statement and view the result --- add, delete, modify, and call executeUpdate to return the affected number of rows; query and call executeQuery // return the query result set int result = pstmt.exe cuteUpdate (); System. out. println (result);} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated cat Ch block e. printStackTrace ();} finally {try {if (con! = Null) {con. close () ;}} catch (SQLException e) {e. printStackTrace () ;}} public static void main (String [] args) {add ();}

The above is the add method. The update and delete methods only change the SQL statement.

Update: // query PreparedStatement pstmt = con. prepareStatement ("update zhuce set sex = ?, Id =? Where name =? And password =? "); Pstmt. setString (1, "M"); pstmt. setString (2, "2222"); pstmt. setString (3, "2222"); pstmt. setString (4, "1111"); delete: // delete the primary key PreparedStatement pstmt = con. prepareStatement ("delete from zhuce where name =? And password =? "); Pstmt. setString (1," 8888 "); pstmt. setString (2," 8888 ");

 JDBC Encapsulation

Encapsulate the output of step 2 close SQL statement

Public class JdbcUtil {public static Connection getConnection () {Connection con = null; try {// 1. load the driver Class. forName ("com. mysql. jdbc. driver "); // 2. create connection con = DriverManager. getConnection ("jdbc: mysql: // localhost: 3306/yyy", "root", "123456");} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated catch block e. printS TackTrace () ;}return con;} public static void close (Connection con) {try {if (con! = Null) {con. close () ;}} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace () ;}} public static int executeUpdate (String SQL, Object [] params) {Connection con = getConnection (); int result = 0; try {PreparedStatement pstmt = con. prepareStatement (SQL); if (params! = Null) {for (int I = 0; I <params. length; I ++) {pstmt. setObject (I + 1, params [I]);} result = pstmt.exe cuteUpdate ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace () ;}finally {close (con) ;}return result ;}}
JAVABEANBean ing with tables in the database, such as bean
Package com. neuedu. bean; import com.sun.org. apache. xml. internal. security. init; public class Student {private Integer sid; private String sname; private Integer age; private Integer sex; // The code for these four statements is javabean public Integer getSid () {return sid ;} public void setSid (Integer sid) {this. sid = sid;} public String getSname () {return sname;} public void setSname (String sname) {this. sname = sname;} public Integer getAge () {return age;} public void setAge (Integer age) {this. age = age;} public Integer getSex () {return sex;} public void setSex (Integer sex) {this. sex = sex;} public Student (Integer sid, String sname, Integer age, Integer sex) {super (); this. sid = sid; this. sname = sname; this. age = age; this. sex = sex;} public Student () {super (); // TODO Auto-generated constructor stub} @ Override public String toString () {return "Student [sid =" + sid + ", sname =" + sname + ", age =" + age + ", sex = "+ sex +"] ";}}
Simplify the use of dynamic arrays // only one dynamic parameter can be included in a method // The dynamic parameter must be located at the end of the parameter list to change the previous object [] to a dynamic array object...
public static int executeUpdate(String sql,Object... params)

Simplified addition, deletion, and modification methods

public static int update(Student student){       return JdbcUtil.executeUpdate("update student set sname=?,age=?,sex=? where sid=?",student.getSname(),student.getAge(),student.getSex(),student.getSid());      }public static int  add(Student student) {       return JdbcUtil.executeUpdate("insert into student (sid,sname,age,sex) values(?,?,?,?)", student.getSid(),student.getSname(),student.getAge(),student.getSex());      }public static int  delete(int id){       return JdbcUtil.executeUpdate("delete from student where sid=?", id);      }

 

Queries are not suitable for arrays, because they do not know how much data they have. With collections, there are two types of ArrayList in the set. The sorted list is suitable for queries based on ArrayList (Vector, ArrayList), and the sorted list (linked list) is suitable for adding, delete operation. Cursor operation: rs. next () to check whether there is any data in the next row. If there is any data in the next row, the cursor is pushed to the next row and true is returned. Otherwise, false is returned. First, the first time rs. next () is called from the top, the next row of data in the first row will be called, that is, the first row of data.
public static List<Student> getStudents(){        Connection con = null;        List<Student> list = new ArrayList<>();        try {             Class.forName("com.mysql.jdbc.Driver");             con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yyy", "root", "123456");             PreparedStatement pstmt = con.prepareStatement("select * from student");             ResultSet rs = pstmt.executeQuery();             while(rs.next()){                   Student student=new Student();                   student.setSid(rs.getInt("sid"));                   student.setSname(rs.getString("sname"));                   student.setSname(rs.getString("age"));                   student.setSname(rs.getString("sex"));                   list.add(student);             }        } catch (ClassNotFoundException e) {              // TODO Auto-generated catch block              e.printStackTrace();        } catch (SQLException e) {            // TODO Auto-generated catch block               e.printStackTrace();        }finally{              try {                    if(con!=null){                          con.close();                    }              } catch (Exception e2) {                    // TODO: handle exception               }        }        return list;   }}public static void main (String[] args){    List<Student> students=getStudents();    System.out.println(students);}  

 

 

 

 

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.