JDBC连接数据库(1)

      /*
       * Driver 是一个接口:数据库厂商必须提供实现的接口。能从其中获取数据库连接。
       * 可以通过Driver的实现类对象获取数据库连接。
       * 加入MySQL驱动程序。
       * 在当前目录下新建lib目录。
       * build path --》add to BuildPath*/
	public void testDriver()throws SQLException{
		//1创建一个Driver实现类的对象。
		Driver driver=new com.mysql.jdbc.Driver();//与程序耦合太大。
		//2准备连接数据库的基本信息:url,user,password
		String url="jdbc:mysql://127.0.0.1:3306/test";
		Properties info=new Properties();
		info.put("user","root");
		info.put("password","root");
		//3调用Driver接口的connect方法,获取数据库连接。
		Connection connection=driver.connect(url, info);
		System.out.println(connection);
		
	}
最简单的情况:
public void testMyConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc","root","root");
System.out.println(connection);
 

/*
* 编写一个通用的方法,在不修改源程序的情况下获取任何数据库的连接。
* 解决方案:把数据库驱动Driver实现类的全类名,url,user,password放入一个配置文件中,通过修改配置
* 文件的方式实现和具体的数据库解耦。*/

	public Connection getConnection()throws Exception{
		String driverClass=null;
		String jdbcUrl=null;
		String user=null;
		String password=null;
		//读取类路径下的jdbc.properties文件。
		InputStream in=
				getClass().getClassLoader().getResourceAsStream("jdbc.properties");
		Properties properties=new Properties();
		properties.load(in);
		driverClass=properties.getProperty("driver");
		jdbcUrl=properties.getProperty("jdbcUrl");
		user=properties.getProperty("user");
		password=properties.getProperty("password");
		
		Driver driver=
				(Driver) Class.forName(driverClass).newInstance();
		
		Properties info=new Properties();
		info.put("user", user);
		info.put("password", password);
		Connection connection=driver.connect(jdbcUrl, info);
		return connection;
	}
	public void testGetConnection1() throws Exception{
		System.out.println(getConnection());
	}
	//使用DriverManager
	public void testDriverManager() throws SQLException, IOException, ClassNotFoundException{
		/*
		 * DriverManager是驱动的管理类。
		 * 1.可以通过重载getConnection()方法获取数据库连接,较为方便
		 * 2.可以管理多个驱动程序。*/
		
		//1准备数据库的4个字符串。
		//驱动的全类名。
		String driverClass=null;
		String jdbcUrl=null;
		String user=null;
		String password=null;
		//读取类路径下的jdbc.properties文件。
		InputStream in=
				getClass().getClassLoader().getResourceAsStream("jdbc.properties");
		Properties properties=new Properties();
		properties.load(in);
		driverClass=properties.getProperty("driver");
		jdbcUrl=properties.getProperty("jdbcUrl");
		user=properties.getProperty("user");
		password=properties.getProperty("password");
		//2加载数据库驱动程序。(对应的Driver实现类中注册驱动的静态代码块。)
		//DriverManager.registerDriver(Class.forName(driverClass).newInstance());
		//此处可以注册,他可以管理多个驱动程序。
		Class.forName(driverClass);
		//通过DriverManager的getConnection()方法获取数据库连接。
		Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
		System.out.println(connection);
	}
	public Connection getConnection2() throws IOException, ClassNotFoundException, SQLException{
		//1.准备连接数据库的4个字符串。
		  //1)z创建jdbc.properties对象。
		Properties properties=new Properties();
		  //2)加载对应的输入流。
		InputStream in=
				this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
		//3)加载2)对应的输入流 
		  properties.load(in);
		//4)具体决定user,password等4个字符串。
		  String user=properties.getProperty("user");
		  String password=properties.getProperty("password");
		  String driver=properties.getProperty("driver");
		  String jdbcUrl=properties.getProperty("jdbcUrl");
		//2.加载数据库驱动(对应的Driver实现类中有注册驱动的静态代码块)
		  Class.forName(driver);
		//3.通过DriverManager的getConnection()方法获取数据库连接。
		  return DriverManager.getConnection(jdbcUrl,user,password);
	}
	public void testGetConnection() throws IOException, ClassNotFoundException, SQLException{
		System.out.println(getConnection2());
	}
	/*
	 * 通过JDBC向数据库插入数据。*/
	public void testStatement() throws IOException, ClassNotFoundException, SQLException{
		/*Statement:用于执行SQL语句的对象
		 * * 通过Connection的CreateStatement()方法来获取
		 * *通过executeUpdate(sql)可以执行SQL语句
		 * *传入的SQL可以是insert,update,delete但不能是Select
		 * Connection,Statement都是应用程序和数据库服务器的连接资源。使用后一定要关闭。
		 * 需要在finally关闭。*/
		//1获取数据库连接
		Connection conn=null;
		Statement statement=null;
		try{
		conn=getConnection2();
		//3准备插入的SQL语句
	//	String sql="insert into customers(name,email,birth)values('abc','1222222@qq.com','1992-12-28')";
	//	String sql="delete from customers where ID= 1";
		String sql="update  customers set  name= 'Tom' "+"Where id = 2";
		System.out.println(sql);
		//执行插入
		//1)获取操作Statement对象
		statement=conn.createStatement();
		//2)调用Statement的executeUpdate(sql)
		statement.executeUpdate(sql);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
	try{	//5,关闭Statement对象
		if(statement!=null)
		statement.close();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
		//2.关闭连接
		if(conn!=null)
		conn.close();
		}
	}
	}
	public void update(String sql) throws SQLException{
	
		Connection conn=null;
		Statement statement=null;
		try{
		conn=JDBCTools.getConnection();
		statement=conn.createStatement();
		statement.executeUpdate(sql);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
	    JDBCTools.release(null,statement, conn);
	}
}
	/*
	 * ResultSet:结果集,封装了使用JDBC进行查询的结果。
	 * 1调用Statement对象的executeQuery(Sql)可以得到结果集
	 * 2ResultSet:返回的实际上就是一张数据表,有一个指针指向数据表的第一行的前面。
	 * 可以调用next()方法检测下一行是否有效,若有效则下移相当于hasNext和next结合体
	 * 3.当指针定位到一行时通过调用getXxx(index)或getXxx(columnName)
	 * 获取每一列的值getXxx(1),getString(name)
	 * 4ResultSet当然也需要进行关闭。*/
	public void testResultSet(){
	 //获取id=4的customers数据表的记录,并打印
		Connection conn=null;
		Statement statement=null;
		ResultSet rs=null;
		try{
		//1获取Connection
		conn=JDBCTools.getConnection();
		//2获取Statement
		statement=conn.createStatement();
		//3准备SQL
		String sql="SELECT * "+
		"From customers ";
		//4执行查询,得到ResultSet
		rs=statement.executeQuery(sql);
		//5处理ResultSet
		while(rs.next()){
			int id=rs.getInt(1);
			String name=rs.getString("name");
			String email=rs.getString(3);
			Date birth=rs.getDate(4);
			System.out.println(id);
			System.out.println(name);
			System.out.println(email);
			System.out.println(birth);
			
		}
		//6关闭数据库连接资源。
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCTools.release(rs, statement, conn);
		}
		
		
	}
其中jdbc.properties文件内容为:

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/atguigu
user=root
password=root
放在src目录下。

封装的JDBCTools.java

/*
 * 操作JDBC的工具类,其中封装了一些工具方法
 * 通过读取配置文件从数据库服务器获取一个连接*/
public class JDBCTools {
	public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException{
		//1.准备连接数据库的4个字符串。
		  //1)z创建jdbc.properties对象。
		Properties properties=new Properties();
		  //2)加载对应的输入流。
		InputStream in=JDBCTools.class.getClassLoader().getResourceAsStream("jdbc.properties");
		//3)加载2)对应的输入流 
		  properties.load(in);
		//4)具体决定user,password等4个字符串。
		  String user=properties.getProperty("user");
		  String password=properties.getProperty("password");
		  String driver=properties.getProperty("driver");
		  String jdbcUrl=properties.getProperty("jdbcUrl");
		//2.加载数据库驱动(对应的Driver实现类中有注册驱动的静态代码块)
		  Class.forName(driver);
		//3.通过DriverManager的getConnection()方法获取数据库连接。
		  return DriverManager.getConnection(jdbcUrl,user,password);
	}
	/*
	 *关闭Statement,Connection */
	public static void  release(ResultSet rs,Statement statement,Connection conn){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	    if(statement!=null){
	    	  try{
	    		  statement.close();
	    	  }catch(Exception e2){
	    	  e2.printStackTrace();
	        }
	      }
	      if(conn!=null){
	    	  try{
	    		  conn.close();
	    	  }catch(Exception e2){
	    	  e2.printStackTrace();
	      }
	    }
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值