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

}

全部评论

相关推荐

10-09 09:39
门头沟学院 C++
HHHHaos:这也太虚了,工资就一半是真的
点赞 评论 收藏
分享
专心打鱼:互联网搬运工,贴子都要偷
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务