Java using the JDBC operations database Simple instance _java

Source: Internet
Author: User

Haven't written about database application for a long time, here is a review of Java JDBC.

1. Using Java JDBC Operations database typically takes 6 steps:

(1) Set up JDBC Bridge, load database drive;

(2) Connect the database, obtain the connection object (use database connection address, username, password);

(3) Obtaining the Database statement object;

(4) Perform database operation;

(5) Read the result;

(6) Close the database connection;

2. Use Java JDBC Operation database (MySQL) code:

Connect MySQL database, need to import MySQL database jar package, this code uses Mysql-connector-java-5.1.18-bin.jar.

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.Statement;

Import Java.sql.ResultSet;
    public class MyTest {public static void main (String args[]) {Connection con = null;
    Statement st = null;
    ResultSet rs = null;
      try {//Get MySQL-driven instance class.forname ("Com.mysql.jdbc.Driver"). newinstance ();
    
      Get the Connection object (provide: address, username, password) con = drivermanager.getconnection ("Jdbc:mysql://127.0.0.1/weather", "root", "root");
      if (!con.isclosed ()) System.out.println ("Successfully connected");
      
      Else System.out.println ("Failed connected");
      Establish a statement, database object st = Con.createstatement ();
      Run SQL query Statement rs = st.executequery ("select * from Weather.question_type_1;");
        Read result set while (Rs.next ()) {System.out.println ("Column1:" +rs.getint (1));
        System.out.println ("Column2:" +rs.getstring (2));
        System.out.println ("Column3:" +rs.getstring (3)); System.out.prIntln ("Column4:" +rs.getstring (4));
    //Close link con.close ();
    catch (Exception e) {System.err.println ("Exception:" + e.getmessage ());
 }
  }
}

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.