java JDBC MySQL database connection

Another: Preparations 

Computer to install MySQL, MySQL installation visualization tools Workbench, create a good database.

A: connect to the database

Related jar package --1-- introduced mysql: mysql-connector-jar (manual procedure in another article package guide)

--2-- load the driver

By --3-- Connection class, fill the database to be connected to the basic information

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by Seadragon on 2019-12-26.
 */
public class JdbcConnect {
    public static void main(String[] args) throws ClassNotFoundException {
        Connection connection = null;
        Statement statement = null;
        try {
            //初始化驱动,加载驱动
            Class.forName ( "com.mysql.jdbc.Driver" ); 


            // Connection object's connection, fill in the information to be connected to the database. Connection-related database 
            Connection = DriverManager.getConnection ( "? Jdbc: MySQL: //127.0.0.1: 3306 / ksea characterEncoding = UTF-8" ,
                     "root", "root" ); 
            System.out.println ( "connection success: "+ connection.toString ()); 


            // create sql statements related objects of statement 
            of statement = Connection.createStatement (); 
            System.out.println ( " get sql statement object: "+ of statement); 


            // prepare the relevant sql statement
             // increment primary key positions can send NULL 
            String sql = ";
             Int I = 100 ;
             the while (I = 0! ) { 
                Statement.execute (SQL); 
                I - ; 
            } 
        } the catch (SQLException E) { 
            e.printStackTrace (); 
        } the finally {
             // close the connection, the release of resources
             / / closed first statement, then off Connection 
            IF (Statement =! null ) {
                 the try { 
                    Statement.close (); 
                } the catch (SQLException E) { 
                    e.printStackTrace ();
                }
            }
            if (connection!=null)
            {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("关闭:"+statement+"----"+connection);
        }
    }
}
jdbc-mysql-connect

 

II: database operations

Connection object is used to connect the database

--1-- calling method to invoke mysql driver class, DriverManager.getConnection (url)

Statement object is used to operate the sql statement,

--1-- created: connection.createStatement

--2-- execution: executeQuery () [perform a query returns a ResultSet object]; execute [Update additions, can be queried by getResultSet, returns a Boolean]; executeUpdate [not query that returns the data is affected data several]

ps: sql statement from growth can be used instead of null

PreparedStatement Statement for the upgraded version, sql statement can be abbreviated, fast speed precompiled mechanism can prevent sql injection attacks

--1 - sql injection attacks: sql statement structure changes, for example: splicing "sql" + "or 1 = 1", that statement is executed unlimited

--2 - PreparedStatement only the set value, and perform pre-compiled into two phases, and can not be changed sql structure, it can inject the defense

package jdbc;

import java.sql.*;

/**
 * Created by Seadragon on 2019-12-26.
 */
public class JdbcPreparedStatemen {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = null;
        Statement statement = null;

        String sql_preState = "insert into hero values(null,?,?)";
        String sql_state = "insert into hero VALUES (null,"+"'提莫',"+12+")";

        //执行sql语句的两种方式
        connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?","root","root");
        statement = connection.createStatement();
        PreparedStatement preparedStatement = connection.prepareStatement(sql_preState);
        statement.execute(sql_state);
        preparedStatement.setString(1,"提莫pre");
        preparedStatement.setInt(2,1233);
        preparedStatement.execute();


    }
}
Statement and PreparedStatement

 

Three: database metadata

That database name, which some basic data tables, which are to get through the DatabaseMetaData object, calls the method getMetaData

package jdbc;

import java.sql.*;

/**
 * Created by Seadragon on 2019-12-27.
 */
public class getMetaData {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?","root","root");
        DatabaseMetaData databaseMetaData = connection.getMetaData();
        System.out.println(databaseMetaData.getDatabaseProductName());
        System.out.println(databaseMetaData.getDatabaseProductVersion());
    }
}
getMeta

 

Four: Transaction

That is to perform several sql statements packaged together, if only all the successful implementation of the implementation, if not a whole fails to perform. Close approach of automatically submit to manual submission.

--1---

connection.setAutoCommit(false)

{sql}

connection.commit()

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by Seadragon on 2019-12-27.
 */
public class JdbcTransaction {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?","root","root");
        Statement statement =  connection.createStatement();
        connection.setAutoCommit(false);
        String sql = "insert into user values(NULL,"+"'kkk',"+"'12345'"+")";
        String sql_false = "insert into rrrr values(NULL,"+"'kkk',"+"'12345'"+")";
        statement.execute(sql);
        statement.execute(sql_false);
        connection.commit();

        System.out.println("你是否要删除该数据");

    }
}
jdbc-mysql-transaction

 

Five: ORM

Object mapping data, i.e. to each of the data with a database object map database package I would be understood in java

package jdbc;
import hero.Hero;
import jdbc.*;

import java.security.PublicKey;
import java.sql.*;

/**
 * Created by Seadragon on 2019-12-27.
 */
public class JdbcORM {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
       Hero hero =  get(3);
       Hero hero_add = new Hero("男枪",12);
       add(hero_add);
       delete("男枪");
       update(1);
        System.out.println(hero.getName()+":"+hero.getPrice());
    }

    public static Connection connectMysql() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?","root","root");
        return connection;
    }

    //ID查询
    public static Hero get(int id) throws ClassNotFoundException, SQLException {
        Hero hero = null;
        Connection connection = connectMysql();
        Statement statement = connection.createStatement();
        String sql = "select * from hero where idHero = "+id;
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
            hero = new Hero();
            String name = resultSet.getString("name");
            int price = resultSet.getInt("price");
            hero.setName(name);
            hero.setPrice(price);
        }
        return hero;
    }

    //add方法
    public static void add(Hero hero) throws ClassNotFoundException, SQLException {
        Connection connection = connectMysql();
        String sql = "insert into hero values(null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,hero.getName());
        preparedStatement.setInt(2,hero.getPrice());
        preparedStatement.execute();
    }

    //delete方法
    public static void delete(String heroname) throws SQLException, ClassNotFoundException {
        Connection connection = connectMysql();
        String sql = "DELETE FROM hero WHERE NAME = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,heroname);
        preparedStatement.execute();
    }

    //update
    public static void update(int id) throws SQLException, ClassNotFoundException {
        Connection connection = connectMysql();
        String sql = "UPDATE hero SET name = ?,price = ? WHERE idHero = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,"修改的英雄名称");
        preparedStatement.setInt(2,1234);
        preparedStatement.setInt(3,id);
        preparedStatement.execute();
    }
}
jdbc-mysql-ORM

 

Six: Connection Pooling

Create a database to create a connection and reduce time to close connections, create a connection pool, which opened the n connection is never closed.

If desired connect to the database, the application to the connection pool, the pool has an idle connection if the connection is to it; but is not directly returned to the pool closed in the idle state after using the connection.

Involving multi-threaded related

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Seadragon on 2019-12-28.
 */
public class JdbcConnectionPool {
    List<Connection> connections = new ArrayList<Connection>();
        int size;
        public JdbcConnectionPool(int size) throws SQLException, ClassNotFoundException {
                this.size=size;
                init();
        }
        public void init() throws ClassNotFoundException, SQLException {
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0;i<size;i++) {
                Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/ksea?", "root", "root");
                connections.add(connection);
            }
        }
        public synchronized Connection getConnection() throws InterruptedException {
            while (connections.isEmpty()){
                this.wait();
            }
            Connection connection = connections.remove(0);
            return connection;
        }
        public synchronized void returnConnection(Connection connection){
            connections.add(connection);
            this.notifyAll();
        }

}
jdbc-mysql-connectionPool

Guess you like

Origin www.cnblogs.com/KSea/p/12095970.html