[Java]使用java进行JDBC编程

发布于:2025-03-11 ⋅ 阅读:(15) ⋅ 点赞:(0)

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

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

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

sql固定的情况下运行

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

让用户输入数据进行插入

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

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

运行结果是这样: