JDBC--Java Database Connectivity

        JDBC is a Java API(Application Programming Interface) that can be used to execute SQL statements. .

        MySQL

 

Now I give code below that teach you how to do it:

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

    }
}
import com.mysql.cj.jdbc.Driver;
new com.mysql.cj.jdbc.Driver()

sql statement:

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";

You need to add the jar to a new directory (here I named it libs).

Where is jar named mysql-connector-j ? Look here:

MySQL :: Download MySQL Connector/J (Archived Versions)icon-default.png?t=N6B9https://downloads.mysql.com/archives/c-j/

 

 

Move  "mysql-connector-j-8.0.32.jar" to directory.

Then add as library..

Run the code just given in your IDEA, refresh your MYSQL.

Try it.​​​​​​​

 

猜你喜欢

转载自blog.csdn.net/m0_72572822/article/details/132082931