JDBC编程

一.引包:

JDBC编程_第1张图片

JDBC编程_第2张图片

二.代码:

JDBC编程_第3张图片

JDBC编程_第4张图片

1.插入数据:

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class demo1 {
    public static void main(String[] args) throws SQLException {
        // 1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test1?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        // 2.和数据库服务器建立连接
        // 此处导包不能弄错,认准java.sql.Connection
        Connection connection = dataSource.getConnection();

        // 输入数据
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        scanner.nextLine();
        String name = scanner.nextLine();

        // 3.构建sql语句
        String sql = "insert into student values(?, ?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        statement.setString(2, name);

        // 4.执行sql语句
        // n表示影响的数据条数
        int n = statement.executeUpdate();
        System.out.println(n);

        // 5.释放资源,关闭连接,注意顺序
        statement.close();
        connection.close();
    }
}

 2.查询数据:

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class demo2 {
    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/test1?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        Connection connection = dataSource.getConnection();
        String sql = "select * from student";

        PreparedStatement statement = connection.prepareStatement(sql);

        // 使用ResultSet类型接收返回值(一个表格)
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = " + id + " name = " + name);
        }
        resultSet.close();
        statement.close();
        connection.close();

    }
}

你可能感兴趣的:(java,mysql,数据库)