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

运行结果是这样:

相关推荐
Morwit几秒前
Qt qml创建c++类的单例对象
开发语言·c++·qt
面汤放盐1 分钟前
软件架构指南 Software Architecture Guide
java·微服务·devops
tkevinjd1 分钟前
JUC5(线程池)
java·线程池·多线程·juc
Tao____2 分钟前
如何对接Modbus-tcp协议(使用Thinlinks物联网平台)
java·物联网·网络协议·tcp/ip·modbus
古城小栈3 分钟前
Rust 已经自举,却仍需GNU与MSVC工具链的缘由
开发语言·rust
鱼跃鹰飞6 分钟前
经典面试题:K8S的自动缩扩容和崩溃恢复
java·容器·kubernetes
jarreyer7 分钟前
数据项目分析标准化流程
开发语言·python·机器学习
Winston Wood10 分钟前
Android图形与显示系统经典故障解决方案:从源码到实操
android·图形系统·显示系统
你怎么知道我是队长10 分钟前
C语言---printf函数使用详细说明
c语言·开发语言
Coder_Boy_11 分钟前
Spring Boot 事务回滚异常 UnexpectedRollbackException 详解(常见问题集合)
java·spring boot·后端