栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JDBC笔记(自用)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JDBC笔记(自用)

标题JDBC

在Java中 ,数据库存取技术客服呢为如下几类:
1.JDBC 直接访问数据库
2.JDO(java data object)技术
3.第三方O/R工具 , 如Hibernate,Mybatis 等

JDBC是JAVA访问数据库的基石,JDO Hibernate MyBatis 等只是更好封装了JDBC

JDBC 是一个独立于特定数据库管理系统 通用的SQL数据库存取和操作的公共接口
,定义了用来访问数据库的标准java类库,使用这些类库可以以一种标准的方法方便地访问数据库资源。

获取连接
方式一:
1.导入mysql驱动 下载连接 添加链接描述

Driver  d = new com.mysql.cj.jdbc.Driver();
	//jdbc :  mysql协议
	//localhost: ip地址
	//3306 : 默认mysql的端口号
	//test :  要连接的数据库名
	String url ="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
	//将用户名密码封装在propertise中
	Properties info=new Properties(); 
	info.setProperty("user", "root");
	info.setProperty("password", "root");
	
 Connection  c= d.connect(url, info);
 
 System.out.println(c);
	
	

方式二: 对方式一的迭代
1.获取Driver实现类对象 用反射来实现
Class .forname

public class 方式二 {
	public static void main(String[] args) throws Exception {
		Class clazz= Class.forName("com.mysql.jdbc.Driver");
		
	Driver  driver=(Driver) clazz.newInstance();
	
	String url ="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
	//将用户名密码封装在propertise中
	Properties info=new Properties(); 
	info.setProperty("user", "root");
	info.setProperty("password", "root");
	
 Connection  c= driver.connect(url, info);
 
 System.out.println(c);


	}

}
  方式三    使用DriverManager替换Driver
  public class 方式三 {
  public static void main(String[] args) throws SQLException {
	  //1.获取driver实现类的对象
	  Driver  d = new com.mysql.cj.jdbc.Driver();
	//注册驱动
	
	  //获取连接
		String url ="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
		String user="root";
		String password="root";
	  Connection connection = DriverManager.getConnection(url,user,password);
	  System.out.println(connection);
}
}
  
 

```java
方式四   相较于方式三更加省略 可以只是加载驱动,不用显示注册驱动过了
 public class 方式四{
  public static void main(String[] args) throws SQLException, ClassNotFoundException {
	  //1.获取driver实现类的对象
	     Class.forName("com.mysql.cj.jdbc.Driver");
	//注册驱动
	  //获取连接
		String url ="jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
		String user="root";
		String password="root";
	  Connection connection = DriverManager.getConnection(url,user,password);
	  System.out.println(connection);
}
}

最终版 将 数据库连接需要的四个基本信息声明在配置文件中,通过夺取配置文件的方v式,获取连接

获取数据库连接

标题**JDBC**

放在src目录下的配置文件

public class finaly {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
	//1.读取配置文件中的四个基本信息
	InputStream is = finaly.class.getClassLoader().getResourceAsStream("jdbc.properties");
	Properties p =new Properties();
	p.load(is);
	String user = p.getProperty("user");
	String password = p.getProperty("password");
	String url = p.getProperty("url");
	String driver = p.getProperty("driver");
	Class.forName(driver);
	Connection connection = DriverManager.getConnection(url, user, password);
	  System.out.println(connection);
}
}

好处 :1.实现了数据和代码的分离。
2.如果需要修改配置文件信息,可以避免程序重新打包。

PreparedStatement的使用

标题**JDBC**
PreparedStatement的使用 添加操作 成功了!!

public static void main(String[] args)  {
		//1.读取配置文件中四个基本信息
		 //获取连接
		Connection connection=null;
		java.sql.PreparedStatement ps=null;
		try {
			InputStream is = PreparedStatement.class.getClassLoader().getResourceAsStream("jdbc.properties");
			 Properties p =new Properties();
			 p.load(is);
			 String user = p.getProperty("user");
			 String password = p.getProperty("password");
			 String url = p.getProperty("url");
			 String driver = p.getProperty("driver");
			 //加载驱动
			 Class.forName(driver);
			 connection = DriverManager.getConnection(url, user, password);		
			 //预编译sql语句返回PreparedStatement的实例
			String sql ="insert into customers(name,email,birth)values(?,?,?)";
			// System.out.println(connection);

			 ps = connection.prepareStatement(sql);
			 //.填充占位符   和数据库交互索引从1开始
			 ps.setString(1, "哪吒");
			 ps.setString(2, "333@qq.com");
			 //日期的格式
			 SimpleDateFormat  ss =new SimpleDateFormat("yyyy-MM-dd");
			 java.util.Date dd = ss.parse("1000-01-01");
			 ps.setDate(3, new Date(dd.getTime()));
			 //执行SQL语
			 ps.execute();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		finally
		{		
			//资源的 关闭 注意处理异常
			try {
				if(ps!=null)
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				if(connection!=null)
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
		}
		 
		 
		 
		 
		 
	}
}

平时使用的时候可以把各个操作封装成一个个方法 以便使用的时候更加方便`
获取连接操作

封装获取连接方法

标题**JDBC**

public  static Connection getConnection() throws Exception{
	InputStream is = finaly.class.getClassLoader().getResourceAsStream("jdbc.properties");
	Properties p =new Properties();
	p.load(is);
	String user = p.getProperty("user");
	String password = p.getProperty("password");
	String url = p.getProperty("url");
	String driver = p.getProperty("driver");
	Class.forName(driver);
	Connection connection = DriverManager.getConnection(url, user, password);
	return connection;
}

封装关闭连接方法

标题**JDBC**
关闭连接操作

public static void closeResource(Connection conn, PreparedStatement ps){
		
		//资源的 关闭 注意处理异常
		try {
			if(ps!=null)
			ps.close();
		} catch (SQLException e) {  
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			if(conn!=null)
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	
	}

操作步骤
1.获取数据库连接
2.预编译SQL语句,返回PreparedStatement的实例
3.填充占位符
4.执行
5.资源的关闭

修改用封装好之后的

public class 修改 {

	public static void main(String[] args)  {
	  Connection c =null;
	PreparedStatement ps =null;
	try {
		c = JDBCUtils.getConnection();
		 String sql ="update customers  set name =? where id=?";
		 ps = c.prepareStatement(sql);
		 ps.setObject(1, "为什么不能修改");
		 ps.setObject(2, 20);
		 ps.execute();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally{
		
		JDBCUtils.closeResource(c, ps);
	}
	
	  
	}

}

通用增删改方法

标题**JDBC**
所以写一个通用的增删改操作

	                                        //可变形参 不知道有多少个??
public static   void update(String sql,Object ...args) {
	//获取数据库连接
   Connection conn=null;
//预编译Sql语句  返沪PreparedStatement实例
PreparedStatement ps=null;
try {
	conn = JDBCUtils.getConnection();
	   ps = conn.prepareStatement(sql);
	   
	    for(int i=0 ;i 

调用

import JDBCUtil.JDBCUtils;

public class 修改2 {
 public static void main(String[] args) {
	String sql ="delete from customers where id = ?";
	 JDBCUtils.update(sql, 20);
}
}

若表名有关键字在表名前加 ``

查询

标题**JDBC**
查询操作 1.针对一张表的查询

1.建查询表的一个类

public class Customers {

	private int id ;
	private String name;
	private String email;
	private  Date  date;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public Date getDate() {
		return date;
	}
	public void setDate(Date date) {
		this.date = date;
	}
	public Customers(int id, String name, String email, Date date) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
		this.date = date;
	}
	@Override
	public String toString() {
		return "Customers [id=" + id + ", name=" + name + ", email=" + email + ", date=" + date + "]";
	}
	public Customers() {
		super();
	}
	
	

}

然后

package com.jdbc;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.javabean.Customers;

import JDBCUtil.JDBCUtils;


public class 查询 {
public static void main(String[] args) throws Exception {
	Connection conn=null;
	PreparedStatement ps=null;
	ResultSet resultSet=null;
	try {
		conn = JDBCUtils.getConnection();
		String sql = "select id,name,email,birth from customers where id = ?";
		ps = conn.prepareStatement(sql);
		  //执行并返回结果集
		ps.setObject(1, 2);
		resultSet = ps.executeQuery();
		 //处理结果集	
		if(resultSet.next())//判断结果集下一条是否有数据,如果有数据返回true 并指针下移  如果返回false 指针不下移直接结束
		{  
			//获取当前数据的各个字段级
		 int id = resultSet.getInt(1);
		 String name =resultSet.getString(2);
		 String email =resultSet.getString(3);
		 Date  d  =resultSet.getDate(4);
		//方式一直接显示
		 System.out.println(id+name+email+d);
		 //方式二
		 Object []data =new Object[]{id,name,email,d};
		 
		 //方式三将数据封装为一个对象(推荐方法)
		  Customers c =new Customers(id, name, email, d);
		  	
		  System.out.println(c);	
		 
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally
	{
		
		JDBCUtils.closeResource(conn, ps, resultSet);
	}
	
}
}

封装关闭查询方法

标题**JDBC**

public static void closeResource(Connection conn, PreparedStatement ps,ResultSet rs)
{
	//资源的 关闭 注意处理异常
	try {
		if(ps!=null)
		ps.close();
	} catch (SQLException e) {  
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	try {
		if(conn!=null)
		conn.close();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}	
	try {
		if(rs!=null)
		rs.close();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}	
}

设置成针对表的通用方法、

查询封装表用到了反射还看不懂

标题**JDBC**

//针对customers 表的一个适应性查询操作
public static Customers qfc( String sql,Object ...args) {
   Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
	conn = JDBCUtils.getConnection();	
	   ps = conn.prepareStatement(sql);
	   //填充占位符
	    for( int i=0 ;i 
import java.sql.Connection;

import com.javabean.Customers;

import JDBCUtil.JDBCUtils;

public class 查询二 {
public static void main(String[] args) {
	
	String sql="select id,name,email,birth from customers where id = ?";
	 Customers qfc = JDBCUtils.qfc(sql, 2);
	 System.out.println(qfc);
	
	
	
	
	
}
	
} 

类中的名和数据库中表的属性值名不一致的解决办法

标题**JDBC**

!!!!!!!!!!!!
类中的名和数据库中表的属性名不一致的情况下 要起别名!!! 起别名要拿类的属性起
起别名:”和类中属性保持一致

	String sql="select id a  ,name b,email c,birth d from customers where id = ?";

这时就不能用get.ColumnName (获取列的列名)了 要用 getColumnLabel (获取列的别名)

String geiColumnLabel = rsmd.getColumnLabel (i+1); 替换
String columnName = rsmd.getColumnName(i+1);

``

针对不同的表的通用的查找操作返回表中的一条记录

标题**JDBC**
使用泛型

//使用PreparedStatementQueryTest 实现针对于不同表的通用查询操作

public static   T getInstance(Class  clazz,String sql , Object...args){
	  Connection conn=null;
	  PreparedStatement ps=null;
	  ResultSet rs=null;
	  try {
	  	conn = JDBCUtils.getConnection();	
	  	   ps = conn.prepareStatement(sql);
	  	   //填充占位符
	  	    for( int i=0 ;i 
package com.jdbc;

import com.javabean.Customers;

import JDBCUtil.JDBCUtils;

public class 查询三 {
public static void main(String[] args) {
	
	 
	
	String sql ="select name from customers where id= ?";
	
	Customers instance = JDBCUtils.getInstance(Customers.class, sql, 4);
	System.out.println(instance);
	
}
}

查询多行数据

标题**JDBC**

public  static    List getList(Class  clazz,String sql , Object...args){
	 Connection conn=null;
	  PreparedStatement ps=null;
	  ResultSet rs=null;
	  try {
	  	conn = JDBCUtils.getConnection();	
	  	   ps = conn.prepareStatement(sql);
	  	   //填充占位符
	  	    for( int i=0 ;i list = new  ArrayList();
	  	   while(rs.next())
	  	    {      T t = clazz.newInstance();
	  	            //处理结果集一行数据中的每一个列
	  	         for(int i=0;i 
package com.jdbc;

import java.util.Iterator;
import java.util.List;

import com.javabean.Customers;

import JDBCUtil.JDBCUtils;

public class 查询四 {
public static void main(String[] args) {
	
	
	String sql="select id ,name from customers where id  list= JDBCUtils.getList(Customers.class, sql, 20);
//
//Iterator iterator = list.iterator();
//  
//while(iterator.hasNext())
//{
//	Customers s= new Customers();
//	s=iterator.next();
//	System.out.println(s);
//}
 
list.forEach(System.out::println);

小细节
若想要插入删除操作有返回提示 可以把增删改方法设置为int 型 然后 不使用
ps.execute() 而是直接**return ps.executeUpdate();**返回>0则成功 返回0则失败

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769606.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号