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

运行结果是这样:

相关推荐
咖啡Beans1 小时前
使用OpenFeign实现微服务间通信
java·spring cloud
我不是混子1 小时前
说说单例模式
java
间彧3 小时前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
间彧3 小时前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java
间彧3 小时前
为什么说SimpleDateFormat是经典的线程不安全类
java
MacroZheng4 小时前
横空出世!MyBatis-Plus 同款 ES ORM 框架,用起来够优雅!
java·后端·elasticsearch
ace望世界4 小时前
android的Parcelable
android
用户0332126663674 小时前
Java 查找并替换 Excel 中的数据:详细教程
java
顾林海4 小时前
Android编译插桩之AspectJ:让代码像特工一样悄悄干活
android·面试·性能优化