• 使用jdbc连接mysql数据库


    1.提供mysql的jdbc驱动(我的博客文件里提供了驱动jar包)

    2.使用IDEA工具,把jar包添加到项目里(具体步骤如下) 

      1)打开模块设置

              

      2)选择libraries功能,点击+号,选择java,找到jar包所在的目录位置,添加即可。

      

      3)jar包添加后,项目下方的External Libraries的目录下,可以看到已经添加完成的jar包。

           

    3.创建jdbc类  

    public class JdbcUtils {

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

        Connection connection = null;
          Statement statement = null;
          ResultSet resultSet = null;

        //1.加载jdbc驱动类
        try {

           //用反射机制,获取mysql-jdbc驱动中的Driver类。com.mysql.jdbc.Driver代表mysql-jdbc驱动中com.mysql.jdbc包下的Driver类。
          Class.forName("com.mysql.jdbc.Driver");  

        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        }

        //2.创建数据库连接  

        //数据库的连接地址 -->dbc:mysql:表示mysql数据库的通信协议 -->localhost表示mysql数据库所在服务器的ip地址 -->3306表示数据库访问端口 -->test表示数据库库名

        String url = "dbc:mysql://localhost:3306/test";    

        String username = root;    //数据库账号

        String password = root;    //数据库密码   

        try {
          connection = DriverManager.getConnection(url, username, password);  //这里会报异常,所以用try{}catch(){} 处理一下
        } catch (SQLException e) {
          e.printStackTrace();
        } 

        //3.获取执行sql语句的对象   

        try {
          statement = connection.createStatement();
        } catch (SQLException e) {
          e.printStackTrace();
        }    

        //4.执行sql语句
        try {
          resultSet = statement.executeQuery("select * from person");
        } catch (SQLException e) {
          e.printStackTrace();
        }

        //5.查看结果集(查询数据库返回的结果)
        while (resultSet.next()) {
          //获取表中name字段的值
          String name = resultSet.getString("name");
          System.out.println("name = " + name);
          //获取表中age字段的值
          String str = resultSet.getString("age");
          int age = Integer.parseInt(str);
          System.out.println("age = " + age);
        } 

        //6.关闭-->结果集对象-->执行sql语句对象-->数据库连接对象
        if (resultSet!=null) {
          resultSet.close();
        }
        if (statement!=null) {
          statement.close();
        }
        if (connection!=null) {
          connection.close();
        }

      }
    }

     

  • 相关阅读:
    [Swift]LeetCode32. 最长有效括号 | Longest Valid Parentheses
    [Swift]LeetCode31. 下一个排列 | Next Permutation
    [Swift]LeetCode30. 与所有单词相关联的字串 | Substring with Concatenation of All Words
    [Swift]LeetCode29. 两数相除 | Divide Two Integers
    时光轴的设计理念
    ITFriend开发日志20140611
    ITFriend开发日志20140611
    高中生活--第7篇–我为什么不交作业
    高中生活--第7篇–我为什么不交作业
    ITFriend网站内测公测感悟
  • 原文地址:https://www.cnblogs.com/w1440199392/p/13950586.html
Copyright © 2020-2023  润新知