[Java]使用java进行JDBC编程

首先要从中央仓库下载api(类似驱动程序),为了链接java和mysql

下载jar包,需要注意的是jar包的版本要和mysql保持一致

下面是新建文件夹lib,把jar包放进去,并添加为库

sql固定的情况下运行

java 复制代码
import com.mysql.cj.jdbc.MysqlDataSource;

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

public class Main {
    public static void main(String[] args) throws SQLException {

        // 1.创建datasourse
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/qimo?characterEncoding=utf8&useSSL=false&serverTimezone=UTC");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2.和数据库服务器建立连接,连接好了后,才能进行后续的请求+相应
        Connection connection = dataSource.getConnection();

        //3.构造sql
        String sql = "insert into employee values(6,700)";
//        String sql = "select * from employee";

        PreparedStatement statement = connection.prepareStatement(sql);

        //4.执行sql
         int n = statement.executeUpdate();

        //5.关闭连接
        statement.close();
        connection.close();
    }
}

让用户输入数据进行插入

这是我选择的非常简单的数据表

java 复制代码
import com.mysql.cj.jdbc.MysqlDataSource;

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

public class Main {
    public static void main(String[] args) throws SQLException {

        // 1.创建datasourse
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/qimo?characterEncoding=utf8&useSSL=false&serverTimezone=UTC");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");

        //2.和数据库服务器建立连接,连接好了后,才能进行后续的请求+相应
        Connection connection = dataSource.getConnection();

        //3.构造sql
        String sql = "insert into employee values(?,?)";
//        String sql = "select * from employee";
        PreparedStatement statement = connection.prepareStatement(sql);
        //这里的index是从1开始算的
        statement.setInt(1,18);
        statement.setInt(2,250);

        //4.执行sql
         int n = statement.executeUpdate();

        //5.关闭连接
        statement.close();
        connection.close();
    }
}

运行结果是这样:

相关推荐
Ray Liang18 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Java水解18 小时前
Java 中间件:Dubbo 服务降级(Mock 机制)
java·后端
砖厂小工20 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心21 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心21 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
SimonKing1 天前
OpenCode AI辅助编程,不一样的编程思路,不写一行代码
java·后端·程序员
FastBean1 天前
Jackson View Extension Spring Boot Starter
java·后端
Kapaseker1 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴1 天前
Android17 为什么重写 MessageQueue
android
Seven971 天前
剑指offer-79、最⻓不含重复字符的⼦字符串
java