JDBC -- Java データベース接続

        JDBC は、SQL ステートメントを実行するために使用できる Java API(Application Programming Interface) です。

        MySQL

 

 

次に、その方法を説明するコードを以下に示します。

package com.jdbc;

import com.mysql.cj.jdbc.Driver;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

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

        //前置工作,在项目下创建一个文件夹libs
        //将 mysql.jar 加入到项目中
        //1. 注册驱动
//        Driver driver = new Driver(); //创建driver
        Driver driver = new Driver();
        // new com.mysql.jdbc.Driver().var
        //     com.mysql.cj.jdbc.Driver

        //2. 得到连接
        String url = "jdbc:mysql://localhost:3306/j_db01";

        //将 用户名和密码放入到Properties 对象
        Properties properties = new Properties();
        properties.setProperty("user", "root");
        properties.setProperty("password", "123456");

        Connection connect = driver.connect(url, properties);

        //3. 执行sql
//        String sql = "insert into actor values(null, '李华', '男', '2000-11-11', '1100')";
//        String sql = "update actor set name='小明' where id = 1";
        String sql = "delete from actor where id = 1";

        //statement用于执行静态SQL语句并返回其生成的结果的对象
        Statement statement = connect.createStatement();
        int rows = statement.executeUpdate(sql); //如果是dml语句,返回的就是影响行数

        System.out.println(rows > 0 ? "成功" : "失败");

        //4.关闭连接
        statement.close();
        connect.close();

    }
}
com.mysql.cj.jdbc.Driver をインポートします。
新しい com.mysql.cj.jdbc.Driver()

SQL文:

String sql = "insert into actor values(null, '李华', '男', '2000-11-11', '1100')";
String sql = "update actor set name='小明' where id = 1";
String sql = "delete from actor where id = 1";

jar を新しいディレクトリに追加する必要があります (ここでは libs という名前を付けています)。

mysql-connector-j という名前の jar はどこにありますか? ここを見て:

MySQL :: MySQL Connector/J をダウンロード (アーカイブ バージョン) icon-default.png?t=N6B9https://downloads.mysql.com/archives/cj/

 

 

「mysql-connector-j-8.0.32.jar」をディレクトリに移動します。

次に、ライブラリとして追加します。

IDEA で指定されたコードを実行し、MYSQL を更新します。

試してみてください。

 

 

 

おすすめ

転載: blog.csdn.net/m0_72572822/article/details/132082931