JDBC简单使用与DriverManager对象的初步学习

//在编写代码前,由于用的是mysql,所以先把mysql-connector的jar给加上并添加路径
package cw_jdbc;
import java.sql.*;
import java.util.Properties;
import org.junit.Test;
public class demo1 {
 /**
  * 使用jdbc实现查询数据库数据并显示在控制台中
  * @throws SQLException 
  */
 public static void main(String[] args) throws Exception {
  // 1.注册驱动,与数据库建立连接
   //不建议使用: DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    //导致驱动被注册两次,强烈依赖数据库的驱动jar
  //1.加载驱动
   Class.forName("com.mysql.jdbc.Driver");  //反射机制加载驱动类
  // 2.获取连接Connection
    //主机:端口号/数据库名
  Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/cw","root","root");
  // 3.得到执行sql语句的对象Statement
  Statement stmt = conn.createStatement();
  // 4.执行sql语句,并返回结果
  ResultSet rs=stmt.executeQuery("select *from users");
  // 5.处理结果
  while(rs.next()){
   System.out.println(rs.getObject(1));
   System.out.println(rs.getObject(2));
   System.out.println(rs.getObject(3));
   System.out.println(rs.getObject(4));
   System.out.println(rs.getObject(5));
   System.out.println("---------------------");
  }
  // 6.关闭资源
  rs.close();
  stmt.close();
  conn.close();
 }
 @Test
 public void test2() throws Exception{
    //1.加载驱动
     Class.forName("com.mysql.jdbc.Driver");  //反射机制加载驱动类
    // 2.获取连接Connection
      //主机:端口号/数据库名
        //map集合
    Properties info=new Properties();
    info.setProperty("user", "root");
    info.setProperty("password", "root");
    Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/cw",info);
    // 3.得到执行sql语句的对象Statement
    Statement stmt = conn.createStatement();
    // 4.执行sql语句,并返回结果
    ResultSet rs=stmt.executeQuery("select *from users");
    // 5.处理结果
    while(rs.next()){
     System.out.println(rs.getObject(1));
     System.out.println(rs.getObject(2));
     System.out.println(rs.getObject(3));
     System.out.println(rs.getObject(4));
     System.out.println(rs.getObject(5));
     System.out.println("---------------------");
    }
    // 6.关闭资源
    rs.close();
    stmt.close();
    conn.close();
 }
 @Test
 public void test3() throws Exception{
  //1.加载驱动
   Class.forName("com.mysql.jdbc.Driver");  //反射机制加载驱动类
  // 2.获取连接Connection
    //主机:端口号/数据库名
      //map集合
  Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/cw?user=root&password=root");
  // 3.得到执行sql语句的对象Statement
  Statement stmt = conn.createStatement();
  // 4.执行sql语句,并返回结果
  ResultSet rs=stmt.executeQuery("select *from users");
  // 5.处理结果
  while(rs.next()){
   System.out.println(rs.getObject(1));
   System.out.println(rs.getObject(2));
   System.out.println(rs.getObject(3));
   System.out.println(rs.getObject(4));
   System.out.println(rs.getObject(5));
   System.out.println("---------------------");
  }
  // 6.关闭资源
  rs.close();
  stmt.close();
  conn.close();
}
}


你可能感兴趣的:(Javaweb_)