• 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() ;
        }
    }
  • 相关阅读:
    find the safest road
    杭电1874(畅通工程续)
    Red and Black
    运行和控制 Nginx 命令行参数和信号
    对中文版“Siri”打个招呼吧!
    《星际迷航》语音翻译器成真
    程序员丰厚的待遇能持续多久?
    Nginx 日志分析 AWStats + JAWStats 安装配置
    RHEL 5.4 + Nginx + Mediawiki
    麻省理工科技创业之:Win 8新概念
  • 原文地址:https://www.cnblogs.com/ZHANG576433951/p/12183417.html
Copyright © 2020-2023  润新知