JDBC将Java代码与数据库进行连接

mysql链接Java 操作步骤:

1.在官网下载https://dev.mysql.com/downloads/connector/j/

下载方法:https://blog.csdn.net/oZhengTuoJiaSuo/article/details/81666828

2.导入驱动

把jar包复制到项目中     右击jar包Build Path---Add to Build Path

3.加载具体驱动类(参考网址:https://blog.csdn.net/qq_35624642/article/details/77727262)

鼠标放在红框处,抛出异常

4.示例demo

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCDemo {
    private static final String URL = "jdbc:mysql://localhost:3306/user?serverTimezone=UTC";//防止出现乱码
    private static final String USERNAME = "root";
    private static final String PWD = "123";
    public static void update() {// 
        Connection connection = null;
        Statement stmt = null;
        try {
            // a.导入驱动加载驱动类
            Class.forName("com.mysql.cj.jdbc.Driver");// 加载具体的驱动类 
            // b.与数据库建立连接
            connection = DriverManager.getConnection(URL, USERNAME, PWD);
            // c.发送sql语句执行(增删改查)
            stmt = connection.createStatement();
            String sql = "insert into student values(2,'zs',23,'s1')";
//            String sql = "update student set STUNAME='ls' where stuno=1";
//            String sql = "delete from student where stuno=1";
            // 执行sql语句
            int count = stmt.executeUpdate(sql); // 
            // d.处理结果
            if (count > 0) {  
                System.out.println("操作成功!");
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                 if(stmt!=null) stmt.close();// 
                 if(connection!=null)connection.close();
            }catch(SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        update() ;
    }
}

猜你喜欢

转载自www.cnblogs.com/ZHANG576433951/p/12183417.html