JDBC执行SQL语句基础

package com.cskaoyan.JDBCDemo;

import org.junit.Test;

import java.sql.*;

public class JDBCStatement {
    
    
    /**
     * 创建一个连接到数据库的连接
     * @return 连接
     * @throws SQLException   连接失败会抛出SQL异常
     */
    public Connection createConnetion() throws SQLException {
    
    
        Connection connection = null;
        String url = "jdbc:mysql://localhost:3306/db3";
        String user = "root";
        String pwd = "yang19960421";
        connection = DriverManager.getConnection(url, user, pwd);
        return connection;
    }

    /**
     * 创建数据库
     */
    @Test
    public void createDatabases() throws SQLException {
    
    
        Connection connection = createConnetion();
        Statement statement = connection.createStatement();
        String sql = "create database if not  exists  db3";
        statement.execute(sql);

    }

    /**
     * 创建表
     */
    @Test
    public void createTable() throws SQLException {
    
    
        Connection connection = createConnetion();
        Statement statement = connection.createStatement();
        String sql = "create table if not exists tb1 (id int primary key,a int)";
        statement.execute(sql);
    }
    /**
     * 插入数据
     */
    @Test
    public  void insertInto() throws SQLException {
    
    
        Connection connection = createConnetion();
        Statement statement = connection.createStatement();
        String sql = "insert into tb1 values(1,2),(2,33),(3,44)";
        statement.execute(sql);
    }
    /**
     *查询数据
     */
    @Test
    public void selectData() throws SQLException {
    
    
        Connection connetion = createConnetion();
        Statement statement = connetion.createStatement();
        String sql = "select * from tb1";
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()){
    
    
            int id = resultSet.getInt("id");
            int a = resultSet.getInt("a");
            System.out.println(id+" "+ a);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_31702655/article/details/105267065