JDBC

API:写好的接口和类
输出一个对象时相当于输出调用toString()方法

思路:

1、概念:

  • JDBC:java 数据库连接,使用java操作数据库
  • 本质:是官方定义的一套操作所有关系型数据库的规则,即接口。各个数据库厂商去实现接口,提供数据库jar包。我们可以使用这套接口,利用多态编程,真正实现的是jar包中的实现类。

2、步骤

  1. 导入驱动 :将驱动(jar包)复制到工程中,并且构建路径(build path),构建路径后此jar包才算真正添加到这个工程中,jar包中的类才可以通过导包的方式使用被使用。
  2. 注册驱动:为什么用forname
  3. 获取数据库连接对象(进行操作的对象)Connection。知道是哪个数据库并且得到操作数据库的权限
  4. 定义sql
  5. 获取执行sql的对象 Statement。将connection对象变成可以执行sql的对象
  6. 执行sql,并接收返回结果
  7. 处理结果
  8. 关闭资源

sun公司以接口的形式提供了一组规则,用来操作数据库。

  1. Driver 接口:提供用来注册和连接基于 JDBC 技术(“JDBC驱动程序”)的驱动程序的,通常仅由 DriverManager 类使用。
  2. Connection 接口:提供创建语句以及管理连接及其属性的方法
  3. DriverManager 类:建立与驱动程序的连接
  4. PreparedStatement:用于发送准备好的语句或基本 SQL 语句

3、获取连接

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.junit.Test;

public class ConnectionTest {
	@Test
	public void connectionTest() throws Exception
	{
		String className="com.mysql.jdbc.Driver";
		String user="root";
		String password="root";
		String url="jdbc:mysql://localhost:3306/test";
		Class.forName(className);
		Connection conn=DriverManager.getConnection(url, user, password);
		System.out.println(conn);
	}
}

读取文件法

public void getConnection() throws Exception
	{
				// 1.读取配置文件中的4个基本信息
				InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
				Properties pros = new Properties();
				pros.load(is);
				String user = pros.getProperty("user");
				String password = pros.getProperty("password");
				String url = pros.getProperty("url");
				String driverClass = pros.getProperty("driverClass");
				
				
				Class.forName(driverClass);
				Connection conn=DriverManager.getConnection(url, user, password);
				System.out.println(conn);
	}

4、获取执行sql的对象 PreparedStatement

public void preparedStatementTest() {
		Connection conn = null;
		PreparedStatement pst = null;
		try {
			// 获取连接
			String className = "com.mysql.jdbc.Driver";
			String user = "root";
			String password = "root";
			String url = "jdbc:mysql://localhost:3306/test";
			Class.forName(className);
			conn = DriverManager.getConnection(url, user, password);
            //定义sql,?是占位符,数据用?表示
			String sql = "update customers set birth=? where id=?";
			//预编译sql对象
			pst = conn.prepareStatement(sql);
			
						
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			java.util.Date date=sdf.parse("1991-10-03");
			long l=date.getTime();
			Date date1=new Date(l);
			
			// 填充sql,可以全都使用pst.setObject(索引,sql中的数据值)
			pst.setDate(1, date1);//表示第一个?的值是变量date1,即birth=date1
			pst.setObject(2, 22);//表示第2个?的值为22,即id=22
			pst.execute();//执行sql
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if (pst != null)
					pst.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

因为连接和关闭资源步骤基本相同,可以进行封装

public static Connection getConnection() throws Exception {	
		InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
		Properties pros = new Properties();
		pros.load(is);

		String user = pros.getProperty("user");
		String password = pros.getProperty("password");
		String url = pros.getProperty("url");
		String className=pros.getProperty("driverClass");
		Class.forName(className);
		Connection conn = DriverManager.getConnection(url, user, password);
		return conn;
	}
	public static void closeResourse(Connection conn,PreparedStatement ps)
	{
		try {
			if(conn!=null)
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(ps!=null)
			ps.close();
		} catch (SQLException e) {	
			e.printStackTrace();
		}
	}

**

查询

Object	getObject(int columnIndex)
获取此的当前行中指定列的值 ResultSet作为对象 Object在Java编程语言。

**
1、JAVA和数据库类型对照表
在这里插入图片描述
初始化对象属性值的方法

  • 通过构造方法
  • 构造空的对象,然后给各个属性赋值

查询某一个表

	@Test
	//查找customers中的数据
	public void testQuery1() 
	{
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet r=null;	
		try {
			conn = msn_JDBCUtils.getConnection();
			String sql="select name,id,email,birth from customers where id=?";
			ps=conn.prepareStatement(sql);
			ps.setObject(1, 1);
			r=ps.executeQuery();
			if(r.next())
			{				
				String name=r.getString(1);
				int id=r.getInt(2);
				String email=r.getString(3);
				Date birth=r.getDate(4);
				msn_Customer customer =new msn_Customer( name,email,id, birth);
				System.out.println(customer);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			msn_JDBCUtils.closeResourse(conn, ps,r);
		}		
		
	}

查询customers表的任意一条数据

public msn_Customer queryCustomer(String sql,Object...args) 
	{
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		
		try {
			
			msn_Customer m=new msn_Customer();
			conn=msn_JDBCUtils.getConnection();
			
			 ps= conn.prepareStatement(sql);
			for(int i=0;i<args.length;i++)
			{
				ps.setObject(i+1, args[i]);
			}
			//执行
			rs = ps.executeQuery();
			//打印结果,需要知道结果集的列数和每一列的值,将值赋值给构造函数,
			ResultSetMetaData metaData = rs.getMetaData();
			int columnCount = metaData.getColumnCount();//结果集的列数
			if(rs.next())
			{
			for(int i=0;i<columnCount;i++)
			{
			
				Object o1=rs.getObject(i+1);//第一列的值
				
				String name=metaData.getColumnLabel(i+1);//获取列名
				
			
				Class c=msn_Customer.class;
				Field field = c.getDeclaredField(name);
				field.setAccessible(true);
				field.set(m, o1);	
				
			}
			}
			return m;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
	
	}finally {
				JDBCUtils.closeResource(conn, ps, rs);
			}
		return null;
}


注意

  • 如果表名和关键字相同,表明需要引起来,比如说order 在这里插入图片描述
    如果表名和属性名不一致,需要起别名
String sql="SELECT order_id orderId, order_name orderName,order_date orderDate FROM `order` WHERE order_id=?";
  • String getColumnLabel(int column):如果字段有别名,会获取别名。没有则获取原名

    String getColumnName(int column):获取字段的原名

查询所有表的通用操作,可以查询多条数据:使用集合

	@Test
	public void test() throws Exception
	{
		String sql = "select id,name,email from customers where id < ?";
		List<Customer> list =commonQuery(Customer.class,sql,12);
		list.forEach(System.out::println);
		
		String sql1 = "select order_id orderId,order_name orderName from `order`";
		List<Order> orderList =commonQuery(Order.class, sql1);
		orderList.forEach(System.out::println);
	}
	public <T> List<T> commonQuery(Class<T> clazz,String sql,Object...args) throws Exception
	{
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			conn = msn_JDBCUtils.getConnection();
			ps= conn.prepareStatement(sql);
			for(int i=0;i<args.length;i++)
			{
				ps.setObject(i+1, args[i]);
			}
			rs = ps.executeQuery();
			ResultSetMetaData rsmd = rs.getMetaData();
			int columnCount = rsmd.getColumnCount();//列数
			 ArrayList<T>list=new ArrayList<T>();
			while(rs.next())
			{
				T nst = clazz.newInstance();
				for(int i=0;i<columnCount;i++)
				{
					//得到值
					Object o = rs.getObject(i+1);
					//得到字段名
					String name = rsmd.getColumnLabel(i+1);
					Field f=clazz.getDeclaredField(name);
					f.setAccessible(true);
					f.set(nst,o);
					
				}
				list.add(nst);
				
			}
			return list;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCUtils.closeResource(conn, ps, rs);
		}		
		return null;		
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值