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);
        }
    }

}

全部评论

相关推荐

专心打鱼:互联网搬运工,贴子都要偷
点赞 评论 收藏
分享
11-02 09:49
已编辑
货拉拉_测试(实习员工)
热爱生活的仰泳鲈鱼求你们别卷了:没事楼主,有反转查看图片
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务