JDBC连接数据库

1.SQL server

  (加载sql server的JDBC驱动)

  ①databaseName=数据库名

  ②以sa用户名登录,登录密码为135345

  ③如果是执行增删改操作,不用rs来接收值,直接用ps.executeUpdate

  代码如下:

    PreparedStatement ps = null;
        Connection ct = null;
        ResultSet rs = null;
        try {
            //初始化我们的对象
            //1.加载驱动
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            //2.得到连接
            ct = DriverManager
                    .getConnection(
                            "jdbc:sqlserver://localhost:1433;databaseName=training",
                            "sa", "135345");
            //3.创建火箭车
            ps = ct.prepareStatement("select * from Salers");
            //4.执行(如果是增加,删除,修改 executeUpdate(),如果是查询 executeQuery())
            rs = ps.executeQuery();
            //循环取出
            while (rs.next()) {

                System.out.println(rs.getString(2) + " " + rs.getString(3));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                ps.close();
                ct.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

2.mysql

  (加载mysql的JDBC驱动)

  基本与sql server一样

  代码如下:

   // 驱动程序名
        String driver = "com.mysql.jdbc.Driver";
        // URL指向要访问的数据库名scutcs
        String url = "jdbc:mysql://127.0.0.1:3306/cloud";
        // MySQL配置时的用户名
        String user = "root";
        // MySQL配置时的密码
        String password = "liuliu159";
        try {
            // 加载驱动程序
            Class.forName(driver);
            // 连续数据库
            Connection conn = DriverManager.getConnection(url, user, password);
            if (!conn.isClosed())
                System.out.println("Succeeded connecting to the Database!");
            conn.close();
        } catch (ClassNotFoundException e) {
            System.out.println("Sorry,can`t find the Driver!");
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

原文地址:https://www.cnblogs.com/lzhc/p/4673142.html