JDBC Database connection Java and some basic statements

Source: Internet
Author: User
Tags stmt

Connect to JDBC     1) Introduction to JDBC        -JDBC is the way to connect databases in Java        -we can execute SQL through JDBC Statement.      2) Get database connection        -java.sql.Connection database connection        -One of our team database Connection start        -get four parameters for database connection:            1. Address of the database url&nbsp ;               Syntax: JDBC: Sub-protocol: Vendor content                 M Format of Ysql: jdbc:mysql://hostname: Port number/database name                 Example: Jdbc:mysql://localhost :3306/test             2. Username user connection Database use user name             3. Password Password database password             4. Database-driven full class name driverclass        -Basic Steps:            1. Importing database-driven jar packages                 MYSQL-C Onnector-java-5.1.37-bin.jar            2. Prepare four parameters                -url  &N Bsp            -user               -password  & nbsp            -driverclass            3. Load Database driver     &N Bsp           Class.forName (driverclass)             4. by DriverManager Get database connection                    static Connection getconnection (String URL, St Ring user, String password)                    -core class:           -java.sql.drivermanager               -database-driven manager, responsible for Load database driver Get database connection                -static Connection getconnection (String URL, strin G User, STring password)                     -getconnection method is used to use the URL address, user name, Password and other parameters to get the database connection             -java.sql.connection          &NBS P    -database connection                -Statement createstatement ()    &NB Sp                -Create a statement object to execute SQL statements with statement objects             -java.sql.statement               -SQL statement actuator                    -Boolean execute (String sql)          &N Bsp              -executes an SQL statement and returns a Boolean value that executes successfully returns TRUE, and false for execution failure. Not much                    -ResultSet executeQuery (String sql)                         -Execute the query's SQL statement and return a result set                   &N Bsp -int executeupdate (String sql)                         - Executes the SQL statement that modifies the data (edit) and returns the number of rows affected             -java.sql.resultset      &NBS P        -the result set of the data being queried, the data we get through the JDBC query database is encapsulated in resultset             &NBSP ;  -Boolean next ()                     -the control cursor moves down one line if the cursor's current position is a Fterlast returns false, telling you that there is no data, do not read.                         If the cursor is moved, no afterlast returns true to read the data.                 -There are many getxxx (int) in resultset, such as GetString (), GetInt (), GetByte ()。                     Through these methods you can read the data for the current row, they need an int value as the parameter,  &nbsp                     int refers to the number of columns that read the data.                     The number of columns starts from 1.                 -There are many getxxx (String) in ResultSet, and it is consistent with the method above,                    Just what they need is a string parameter, and the parameter represents the current column name,        &NBS P               For example: we want to get the value of the ID                 &NBSP ;           GETINT ("id")                     &NBSP ;   to get the value of name                             Getstrin G ("name")                     NOTE: If the query's SQL uses an alias, the column name will be the alias.      3) data additions and deletions        //Create a SQL executor         Statement stat = Conn.createstatement ();        //Create an SQL statement         String sql = "INSERT in To T_stu (' name ', age) VALUES (' Sand Monk ', ') ';        //Execute SQL statement        //executeup Date is used to execute a statement that modifies SQL         //It requires a string type SQL as a parameter and returns a value of type int that represents the number of rows affected by the SQL statement after execution         int count = stat.executeupdate (SQL);     4) data query        //Create Statem ENT objects         Statement stmt = conn.createstatement ();       //Create an SQL statement   &NB Sp     String sql = "SELECT ID, Name sname, age from T_stu WHERE id=2";       //Execute query   &NB Sp     ResultSet rs = stmt.executequery (sql);       //control cursor Move Down line        //IF Current row has data, read         if (Rs.next ()) {            //Get Id,name,age         &NBSp   INT id = rs.getint ("id");            String name = rs.getstring ("sname");  &nbsp ;         int age = Rs.getint ("Age");             SYSTEM.OUT.PRINTLN ( Id+ "--" +name+ "--" +age ";       }         > The main difference between the query operation and the modification is that Query using ExecuteQuery (),            It will return the resultset result set, we need to read the result set.          > When we only need to read one data, use if.             When you need to read all the data, use while         > Code specification:    &NBS P      -Connection, Statement, ResultSet, these resources are required to establish a connection with the data               &N Bsp These resources do not always need to be used, and when we do not apply these resources, we need to close these resources.            -close resource order:               :  &N Bsp                 First off resultset                   Close statement              &NBSP ;     Closing connection           -Sample code:            &NB Sp  //definition of three variables                 Connection conn = null;                Statement stmt = null;                ResultSet rs = n ull;                 try{             &NBS P  }catch (Exception e) {                    E.printstacktrace () &nbsp ;              }finally{                 &N Bsp   if (rs!=null) {                       //Off resulset                       Try {            &NBSP ;               rs.close ();                       } catch (SQLException e) {                    &NBS P      //TODO auto-generated catch block                  &NBS P         e.printstacktrace ();                    &NBS P  }                   }           &N Bsp         if (stmt! = null) {                        Try {                            Stmt.close () ;                      } catch (SQLException e) {    &NBSP ;                       e.printstacktrace ();      &NBS P                }                  &N Bsp }                     IF (conn! = null) {                        Try {                &NBSP ;           conn.close ();                    &NBS P   catch (SQLException e) {                        &NBSP ;   E.printstacktrace ();                       }  &NB Sp &nbSp              }                } dao Data Access Object:    uses DAO classes in Java to interact with the database, while other classes no longer need to write JDBC-related code,        Instead, call DAO directly.     In practice, all of our JDBC-related code should be written in DAO,        java.sql The contents of this package should not appear outside of DAO    & nbsp t_user         CREATE TABLE T_user (            ID INT PRIMARY KEY A uto_increment,            username VARCHAR (+),            ' p Assword ' varchar,            Email VARCHAR (+),          &NBS P Nickname VARCHAR (       )      Create USERDAO (responsible for user object and database related operations)     & nbsp       User getuserbyusername (String username)--Find users based on user          int Saveuser (user user); --> Inserting user objects into the database          user Getuserbyusernameandpassword (string username, string password)-- > Find users by user name and password      login:        login is actually such a SQL statement:          &N Bsp SELECT * from T_user WHERE username= ' and password= '  

JDBC Database connects to Java and some basic statements

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.