JAVA basic JDBC connection database

JDBC connect to the database

JDBC, database purpose?

Database driven

What do you think of first when you see the driver?
In life: sound cards, graphics cards, and network cards are all necessary for computers, and they cannot be started without a computer.
Insert picture description here

Our program will deal with the database through the database driver.

JDBC

In the future, SUN will simplify the operation of developers (unification of the database) and provide a specification (for JAVA operation of the database), commonly known as: JDBC
The implementation of these plans is done by specific vendors~

Insert picture description here

Java programs access the database mysql, there is a standard JDBC (java database connect)

Driver: Provided by the database vendor

jar包:mysql/oracle

Register the driver:

See clearly, there is only one sentence to register the driver:

Class.forName(“com.mysql.jdbc.Driver”);

DriverManage

The DriverManager class is used to load the JDBC driver and create a connection to the database.

DriverManger (drive manager) has two functions:

注册驱动:这可以让JDBC知道要使用的是哪个驱动
获取Connection:如果可以获取到Connection,那么说明已经与数据库连接上了

Connnection

Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mydb1”,”root”,123);

The Connection interface represents the connection between the Java program and the database. Only after obtaining the connection object can you access the database and operate the data table.

The Connection object represents the connection, and communication with the database is carried out through this object:

Connection最为重要的一个方法就是用来获取Statement对象;

Statement

Statement stmt = con.createStatement();
//Statement是用来向数据库发送要执行的SQL语句的!

The statement object in Jdbc is used to send SQL statements to the database. If you want to complete the addition, deletion, and modification check of the database, you only need to send the addition, deletion, modification, and check statement to the database through this object.

The executeUpdate method of the Statement object is used to send addition, deletion, and modification sq| statements to the database. After executeUpdate is executed, it will return an integer (that is, the addition, deletion, and modification statement caused several rows of data in the database to change).

The Statement.executeQuery method is used to generate query statements to the database, and the executeQuery method returns a ResultSet object representing the query result.

Statement is used to send SQL statements to the database, so that the database will execute the SQL statements sent:

void executeUpdate(String sql): Perform update operations (insert, update, delete, etc.)

1. Use executeUpdate(String sql) method to complete the data addition operation, example operation:

Statement statement = connection.createStatement();
        String sql = "insert into user(...) values(...)";
        int num = statement.executeUpdate(sql);
        if(num>0){
    
    
            System.out.println("插入成功");
        }

2. Use executeUpdate(String sql) method to complete the data deletion operation, example operation:

Statement statement = connection.createStatement();
        String sql = "delete from user where id =1";
        int num = statement.executeUpdate(sql);
        if(num>0){
    
    
            System.out.println("删除成功");
        }

3. Use executeUpdate(String sql) method to complete data modification operation, example operation:

Statement statement = connection.createStatement();
        String sql = "update user set name ='' where name = ''";
        int num = statement.executeUpdate(sql);
        if(num>0){
    
    
            System.out.println("修改成功");
        }

ResultSetexecuteQuery(String sql): execute query operation, the database will put the query result after the query is executed, the query result is ResultSet

Use executeUpdate(String sql) method to complete data query operation, example operation:

Statement statement = connection.createStatement();
        String sql = "select * from  user where id =1";
        ResultSet rs= statement.executeQuery(sql);
        if(rs.next()){
    
    
            System.out.println("");
        }

ResultSet

The ResultSet interface is used to save the result set returned when JDBC executes a query. The result set is encapsulated in a logical table.
A large number of getXxx() methods are defined in the ResultSet interface, and which getXxx() method is used depends on the data type of the field.

boolean next(): Move the "line cursor" to the next line, and return whether the moved line has
XXX getXXX(int col): Get the value on the specified column of the current line, the parameter is the number of columns, the number of columns starts from 1, Instead of 0

Get data from the database and return the result table

The ResultSet is a two-dimensional table with a "line cursor" inside. The default position of the cursor is "above the first line". We can call the next() method of the rs object to move the "line cursor" down by one line. When the next() method is called once, the "line cursor" is at the position of the first row record. At this time, you can use the getXXX(int col) method provided by ResultSet to get the data of the specified column:

rs.next();//光标移动到第一行
rs.getInt(1);//获取第一行第一列的数据

When you use the rs.getInt(1) method, you must be sure that the data type of the first column is an int type. If you are not sure, then it is best to use rs.getObject(1). A series of getXXX() methods are provided in the ResultSet class. The more commonly used methods are:

Object getObject(int col)
String getString(int col)
int getInt(int col)
double getDouble(int col)

shut down

Like the IO stream, everything needs to be closed after use! The order of closing is to get the first to close, and to get the last to close first.

rs.close();
stmt.close();
con.close();

MySQl database

Commonly used commands
Create database: create database database name;
delete database: drop database database name;
use database: use database name;
create database table: create table table name (field name 1 field type [default default value] [constraint], …) ;
Delete database table: drop table table name;
view table structure: desc table name;
view all databases: show databases;
view all tables of a database: show tables;

SQL syntax basis (Structured Query Language, structured query statement) powerful database language

DML-Data Manipulation Language: Retrieve or modify data
DDL-Data Definition Language: define the structure of data, create, modify, and delete
DCL-Data Control Language: define the authority of database users


step:

1) Download jar package, driver package

https://mvnrepository.com/search?q=mysql

2) Idea creates a project, jdbc2011

3) src flush the lib directory in the directory, put the jar into it

4) Notify this project that I have to rely on this jar package so that I can call

5) Select the project structure menu under the file menu

Select the modules module, select the Dependencies page folder

6) Binding the jar to this project, we can use it in the code

+ Sign, select the first jars. . .

7) Go to your own location

IdeaProjects\jdbc2011\lib\mysql-connector-java-5.1.32.jar is
successful: there is a small arrow in front of the jar, you can click to open it, and display the package to represent success

Steps:

Idea create a project project, the project name is: jdbc2011, then create a new lib folder, drag into the jar package

Insert picture description here

Configure the jar package call environment, click File-Project~

Insert picture description here

Select Modules-DEpendencles-finally select the + sign, select the first jars. . .

Insert picture description here

After the pop-up window, select the configured jar package, click ok after selection

Insert picture description here

Configuration is complete, you can call

Insert picture description here

My first JDBC program format

public class TestJDBC {
    
    
    public static void main(String[] args){
    
    
     //1. 加载驱动
        Class.forName("com.mysql.jdbc.Driver");//固定写法
        //2. 用户信息和url
        //useUnicode=true&characterEncoding=utf8&&useSSL=true
        String url ="jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&&useSSL=false";
        //mysql 默认3306
        //协议://主机地址:端口号/数据库名?参数1&参数2&参数3

       //Oracle--1521
       //jdbc:oralce:thin:@localhost:1521:sid
        String name = "root";//数据库账号
        String password = "123456";//数据库密码



        //3. 连接成功,返回数据库对象  connection代表数据库  PrepareStatement 执行SQL的对象
        Connection connection= DriverManager.getConnection(url,name,password);
        //connection代表数据库
        connection.rollback();//事务回滚
        connection.commit();//事务提交
        connection.setAutoCommit();//数据库设置自动提交


        //4. 执行SQL的对象 statement 执行SQL的对象
        Statement statement = connection.createStatement();
        statement.executeQuery();
        statement.execute();
        statement.executeUpdate();//更新,插入,删除,返回一个受影响的行数

        //5. 执行SQL的对象 去执行SQL   可能存在结果,查看返回结果
        String sql="SELECT * FROM users";

        //ResultSet 查询的结果集,封装了所以的查询结果
        //获得指定的数据类型
        ResultSet resultSet = statement.executeQuery(sql);//返回的结果集,结果集中封装了我们全部查询的结果
        resultSet.getObject();//在不知道列类型下使用
        //如果知道则指定使用
        resultSet.getString();
        resultSet.getInt();
        resultSet.getChar();

        //遍历,指针
        while(resultSet.next()){
    
    
        resultSet.next(); //移动到下一个
        resultSet.afterLast();//移动到最后
        resultSet.beforeFirst();//移动到最前面
        resultSet.previous();//移动到前一行
        resultSet.absolute(row);//移动到指定行

           System.out.println("id+"+resultSet.getObject("id"));
            System.out.println("name+"+resultSet.getObject("NAME"));
            System.out.println("password+"+resultSet.getObject("PASSWORD"));
            System.out.println("email+"+resultSet.getObject("email"));
            System.out.println("birthday+"+resultSet.getObject("birthday"));
        }
        //6. 释放连接
        resultSet.close();
        statement.close();
        connection.close();//耗资源
    }
}

Execute JDBC connection code

import java.sql.*;

public class TestJDBC {
    
    
    public static void main(String[] args)
            throws ClassNotFoundException, SQLException {
    
    
        //通过java访问mysql数据库,查询
        //这个对象获取数据库链接
        //注册驱动,输入链接地址,用户名,密码
        String driver = "com.mysql.cj.jdbc.Driver";
        //mysql 8.0 (oracle) 把驱动包路径改了,
        //8.0之前  com.mysql.jdbc.Driver
        //8.0之后  com.mysql.cj.jdbc.Driver

        //访问本机的mysql数据库,端口3306,数据库名
        String url = "jdbc:mysql://localhost:3306/mysql-db?serverTimezone=Asia/Shanghai&characterEncoding=UTF8";
        String username = "root";
        String password = "root";

        Class.forName(driver);
        //获取到数据库链接
        Connection cn = DriverManager.getConnection(url, username, password);
        //创建一个Statement语句对象
        Statement stat = cn.createStatement();
        //执行SQL语句
        String sql = "select * from student";
        //把查询的结果(表记录)存放到ResultSet对象中,结果集
        ResultSet rs = stat.executeQuery(sql);

        //获取这个表有几个字段,元数据(描述数据的数据)
        int cols = rs.getMetaData().getColumnCount();
        System.out.println("表的列数:" + cols);

        //展示表的字段名称
        //索引值是从1开始(数据库要求)
        for(int i=1;i<=cols;i++){
    
    
            //"\t"代表转义,代表tab键,多个空格
            System.out.print(rs.getMetaData().getColumnName(i) + "\t");
        }
        System.out.println();//换行

        //展示数据,行数while循环,next()取下一条记录,如果没有,循环就结束
        //next()有记录就返回ture,如果到最后面了,就返回false
        while (rs.next()){
    
    
            for (int i = 1; i <= cols; i++) {
    
    
            //获取他的字段内容
            System.out.print(rs.getString(i)+"\t");
          }
          System.out.println(); //换行
        }
    }
}

SQL injection:

There are vulnerabilities in sql, which can be attacked and cause data leakage == SQL will be spliced ​​or ==

public class SQL注入 {
    
    
    public static void main(String[] args) {
    
    
    login("root","123456");//正常登陆

        //SQL注入
 login("' or '1=1","123456");
    }
    public static void login(String name,String password){
    
    
        Connection conn =null;
        Statement st = null;
        ResultSet rs =null;
        String driver = "com.mysql.cj.jdbc.Driver";
         String url = "jdbc:mysql://localhost:3306/mysql-db?serverTimezone=Asia/Shanghai&characterEncoding=UTF8";
        String username = "root";
        String password = "root";
        Class.forName(driver);
        Connection cn = DriverManager.getConnection(url, username, password);
        Statement stat = cn.createStatement();
        
        String sql = "select * from users where `NAME`='"+ name +"'  AND `PASSWORD`='"+ password +"'" ;
        ResultSet resultSet = statement.executeQuery(sql);
        while (rs.next()){
    
    
             System.out.println(rs.getString("NAME"));
        }
       //6. 释放连接
        resultSet.close();
        statement.close();
        connection.close();//耗资源
    }
}

PreparedStatement object

PreparedStatement can prevent SQL injection and is more efficient.
The essence of PreparedStatement to prevent lSQL injection is to treat the passed parameters as characters.
Assuming there are escape characters, such as' will be directly escaped

新增
删除
查询
            //区别
            //使用问好占位符代替参数
            String sql = "insert into users(id,`NAME`) values(?,?)";
            pstm = connection.prepareStatement(sql);//预编译sql,先写sql然后不执行
            //手动给参数赋值
            pstm.setInt(1,4);//id
            pstm.setString(2,"qingfeng");
            pstm.setString(2,"1043051018");
            pstm.setString(2,"[email protected]");
            //注意点:
            //sql.Date   数据库    java.sqL.Date()
            //util.Date  Java     new Date().getTime()获得时问激
            st.setDate( parameterlndex: 5,new java.sql.Date(new Date( ).getTime()));

            //执行
            int i = pstm.executeUpdate();
            if (i>0){
    
    
                System.out.println("插入成功");
            }

Use IDEA to connect to the database

Insert picture description here
Choose your database

Insert picture description hereConnect to the database to
Insert picture description hereselect the database to be displayed
Insert picture description here

to sum up:

Insert picture description here

Guess you like

Origin blog.csdn.net/QQ1043051018/article/details/112234055