Java connects, queries, and modifies MySQL database (RPM)

Source: Internet
Author: User

Java connects, queries, and modifies the MySQL database

0. General process:

(1) Call the Class.forName () method to load the driver.

(2) Call the Getconnection () method of the DriverManager object to obtain a connection object.

(3) Create a statement object and prepare an SQL statement that can be a statement object (the statement executed immediately), A PreparedStatement statement (a precompiled statement) or a CallableStatement object (the statement that the stored procedure invokes).

(4) Call the Excutequery () method to execute the SQL statement and save the result in the ResultSet object, or call Executeupdate () to execute the SQL statement without returning the result of the ResultSet object.

(5) The return of the ResultSet object to display the equivalent of processing.

(6) Releasing resources.

1. Connect to the database

(1) Download MySQL connection driver

Web site: http://dev.mysql.com/downloads/connector/j/, downloaded and placed in Dr. F:\ research materials \ Database learning \mysql related program files, decompression.

(2) Loading the JDBC driver

How to do this: in Eclipse, select the appropriate project, click Java Build Path in Project-properties, Add Mysql-connector-java-5.1.21-bin.jar in libraries and click OK.

(3) Build a simple database as follows:

                  

Import java.sql.*;p Ublic class Getconnection {public    static void Main (string[] args) {        try{            // Call the Class.forName () method to load            the driver class.forname ("Com.mysql.jdbc.Driver");            SYSTEM.OUT.PRINTLN ("Load MySQL driver successfully!") ");        } catch (ClassNotFoundException E1) {            System.out.println ("MySQL driver not found!");            E1.printstacktrace ();        }                String url= "Jdbc:mysql://localhost:3306/mysql";    JDBC URL            //Call the Getconnection () method of the DriverManager object to obtain a Connection object        Connection conn;        try {            conn = drivermanager.getconnection (URL,    "root", "");            Create a Statement object            Statement stmt = conn.createstatement ();//Create Statement Object            System.out.print ("Successfully connected to the database! ");            Stmt.close ();            Conn.close ();        } catch (SQLException e) {            e.printstacktrace ();}}    }

2. Querying Data Sheets

When you query a data table, you need to use the ResultSet interface, which is similar to a data table, through which an instance of the interface can obtain the result set and the interface information of the corresponding data table.

Import java.sql.*;p Ublic class Selecttable {public static void main (string[] args) {try{//call CLA            The Ss.forname () method loads the driver Class.forName ("Com.mysql.jdbc.Driver"); SYSTEM.OUT.PRINTLN ("Load MySQL driver successfully!")                            ");    String url= "Jdbc:mysql://localhost:3306/aniu";            JDBC URL Connection conn;            conn = drivermanager.getconnection (URL, "root", ""); Statement stmt = Conn.createstatement (); Create the Statement object System.out.println ("Successfully connected to the database!            ");    String sql = "SELECT * from Stu"; SQL ResultSet to execute rs = stmt.executequery (sql);//Create Data Object System.out.println ("number" + "\ T" + "name" + "\ T" +                "Age");                    while (Rs.next ()) {System.out.print (Rs.getint (1) + "\ T");                    System.out.print (rs.getstring (2) + "\ T");                    System.out.print (Rs.getint (3) + "\ T");                System.out.println ();                }Rs.close ();                Stmt.close ();            Conn.close ();            }catch (Exception e) {e.printstacktrace (); }    }}

3. modifying and deleting databases

Modify Delete data import java.sql.*;p Ublic class Updatedeletedemo {public static void main (string[] args) throws exception{            try{//Call the Class.forName () method to load the driver Class.forName ("Com.mysql.jdbc.Driver"); SYSTEM.OUT.PRINTLN ("Load MySQL driver successfully!")                            ");    String url= "Jdbc:mysql://localhost:3306/aniu";            JDBC URL Connection conn;            conn = drivermanager.getconnection (URL, "root", ""); Statement stmt = Conn.createstatement (); Create the Statement object System.out.println ("Successfully connected to the database!            ");    Code for querying data String sql = "SELECT * from Stu"; SQL ResultSet to execute rs = stmt.executequery (sql);//Create Data Object System.out.println ("number" + "\ T" + "name" + "\ T" +                "Age");                    while (Rs.next ()) {System.out.print (Rs.getint (1) + "\ T");                    System.out.print (rs.getstring (2) + "\ T");                    System.out.print (Rs.getint (3) + "\ T"); System.oUt.println (); }//Modify the code of the data String sql2 = "Update stu set name=?"            where number=? ";            PreparedStatement PST = conn.preparestatement (SQL2);            Pst.setstring (1, "8888");            Pst.setint (2,198);                            Pst.executeupdate ();            Code to delete data String sql3 = "Delete from Stu where number=?";            PST = Conn.preparestatement (SQL3);            Pst.setint (1,701);                            Pst.executeupdate ();            ResultSet rs2 = stmt.executequery (sql);//Create Data Object System.out.println ("number" + "\ T" + "name" + "\ T" + "age");                while (Rs.next ()) {System.out.print (Rs2.getint (1) + "\ T");                System.out.print (rs2.getstring (2) + "\ T");                System.out.print (Rs2.getint (3) + "\ T");            System.out.println ();            } rs.close ();            Stmt.close ();            Conn.close ();  }catch (Exception e)          {E.printstacktrace (); }    }}

Java connects, queries, and modifies MySQL database (RPM)

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.