jdbc连接数据库三种方式

---恢复内容开始---

第一种:

public class Demo1 {

//连接数据库的URL

private String url = "jdbc:mysql://localhost:3306/shu";

                    // jdbc协议:数据库子协议:主机:端口/连接的数据库

private String user = "root";//用户名

private String password = "root";//密码 

@Test

public void test1() throws Exception{

//1.创建驱动程序类对象

Driver driver = new com.mysql.jdbc.Driver(); //最新版本

  //Driver driver = new org.gjt.mm.mysql.Driver(); //旧版本

//设置用户名和密码

Properties props = new Properties();

props.setProperty("user", user);

props.setProperty("password", password);

//2.连接数据库,返回连接对象

Connection conn = driver.connect(url, props);

System.out.println(conn);

}

/*

 * 第二种使用驱动管理器类连接数据库(注册了两次,没必要)

 * @throws Exception

 */

@Test

public void test2() throws Exception{

Driver driver = new com.mysql.jdbc.Driver();

//Driver driver2 = new com.oracle.jdbc.Driver();

//1.注册驱动程序(可以注册多个驱动程序)

DriverManager.registerDriver(driver);

//DriverManager.registerDriver(driver2);

//2.连接到具体的数据库

Connection conn = DriverManager.getConnection(url, user, password);

System.out.println(conn);

}

/**

 * 第三种:现在最常用的(推荐使用这种方式连接数据库)

 * 推荐使用加载驱动程序类  来注册驱动程序

 */

public static void main(String[] args) throws Exception {
       //注册成功
        Class.forName("com.mysql.jdbc.Driver");
       //获取数据库的连接
        Connection coon=DriverManager.getConnection("jdbc:mysql://localhost:3306/why?user=root&&password=123456");
        //创建代表sql语句的对象
       Statement stmt=coon.createStatement();
       //执行sql语句
       String sql="select stuname,scores from student";
       //如果是查询语句返回查询结果
       ResultSet rs=stmt.executeQuery(sql);
       while(rs.next())//如果有新行就返回true,否则返回false
       {
           //数据库表中的字段是什么类型就用get***来代替
           //对应数据库的字段名,不区分大小写但必须一致
           String ename=rs.getString("stuname");
           int i= rs.getInt("scores");
           System.out.println(ename+":::"+i);
       }
       //释放资源
       if(rs!=null){
           rs.close();
       }
       if(stmt!=null){
           stmt.close();
       }
       if(coon!=null){
           coon.close();
       }
    }

---恢复内容结束---

猜你喜欢

转载自www.cnblogs.com/wanghuaying/p/9489533.html