java连接数据库实现基本的增删改查

65 篇文章 0 订阅
61 篇文章 1 订阅

java连接数据库

步骤

  • 1.加载数据库

    Class.forName("com.mysql.jdbc.Driver");
    
  • 2.链接数据库

    public static final String url="jdbc:mysql://localhost:3306/Product?userUnicode=true&characterEncoding=utf8&useSSL=false";
    		public static final String user ="root";
    		public static final String password="root";
    Connection conn = DriverManager.getConnection(url, user, password);
    
  • 3.数据库操纵对象

    String sql="SQL语句";	
    PreparedStatement pst=conn.prepareStatement(sql);
    //表示预编译的SQL语句的对象。 
    //SQL语句已预编译并存储在PreparedStatement对象中。 然后可以使用该对象多次有效地执行此语句
    
  • 4.执行SQL语句

    pst.execute();
    
  • 5.关闭数据库

    conn.close();
    pst.close();
    

基础的增删改查

思路: 先将基本的框架写出来 ,增删改查都在方法里面写

创建商品类

商品类 大概就是创建属性,get set 方法,构造有参无参方法,toString方法等几个

package com.po;
//重写equals和HashCode两个方法
public class Product {
	private int id;
	private String name;
	private double price;
    
    
    
	public Product(int id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	public Product(String name, double price) {
		super();
		this.name = name;
		this.price = price;
	}
	private String info;
	private String param;
	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 double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}
	public String getParam() {
		return param;
	}
	public void setParam(String param) {
		this.param = param;
	}
	public Product() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Product(int id, String name, double price, String info, String param) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.info = info;
		this.param = param;
	}
	public Product(String name, double price, String info, String param) {
		super();
		this.name = name;
		this.price = price;
		this.info = info;
		this.param = param;
	}
	@Override
	public String toString() {
		return "Product [id=" + id + ", name=" + name + ", price=" + price + ", info=" + info + ", param=" + param
				+ "]";
	}
	@Override
	public boolean equals(Object obj) {
		boolean flag=false;
		if(this==obj) {
			flag=false;
		}else  if(obj instanceof Product){
			Product p=(Product)obj;
			if(this.id==p.id&&this.name.equals(p.name)) {
				flag=true;
			}
		}
		return flag;
	}
	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		return id+name.hashCode();
	}
	
	
}

创建接口方法类

定义出增删改查的方法类;

public interface IPoroductDAO {
	//增加的方法
    int add(Product p);
     //删除的方法
    int delete(int id);
	//修改的方法
	int update(Product p);
    //根据id查询的方法
	Product query(int id);
    //全部查询的方法
	List<Product> query();
}

因为连接数据库有冗余所以将连接数据库的公共各部分提出到新的类里面

即连接数据库的第1 ,2,5步提出来

package com.util;

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

public class DBConnection {
	
		
		public static final String url="jdbc:mysql://localhost:3306/Product?useUnicode=true&charaEncoding=utf8";
		public static final String user ="root";
		public static final String password="123456";
	//类第一次加载的时候执行一次
	static {
		
		try {
			
	//1.加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//有可能报错
	}
	
	
	//2.数据库链接
	public static Connection getConn() {
		
		
		Connection conn =null;
		
		 try {
			 
			conn= DriverManager.getConnection(url, user, password);
		
		 } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}return conn;
	}
	
	public static void close(Connection conn,PreparedStatement pst) {
		try {
	//5.关闭数据库	
			conn.close();
			pst.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
}

创建方法实现的类

public class ProductDAOmp1 implements IPoroductDAO {

	//将声明放在公共部分以便调取 
    
    //与特定数据库的连接(会话)。 执行SQL语句并在连接的上下文中返回结果。 Connection对象的数据库能够提供描述其表,其支持的SQL语法,其存储过程,此连接的功能等的信息。 该信息是用getMetaData方法获得的。 




    Connection conn =null;
	PreparedStatement pst =null;



}

增删改查的方法都在ProductDAOmp1类中

一下是为了更直观的浏览

增加商品方法

    public int add(Product p) {
        try {
        //获取到含有连接数据库信息的类
        conn=DBConnection.getConn();
        
        //3.数据库操纵对象
        String sql="Insert into goods (name,price,info,param) values(?,?,?,?)"
        pst=conn.prepareStatement(sql);//SQL语句已预编译并存储在PreparedStatement对象中。 
       
        
        
        //setString(int parameterIndex, String x) 将指定的参数设置为给定的Java String值
        pst.setString(1,p.getName()); //即将p.getName()所获得值赋给第1个问号的地方
    
        pst.setDouble(2.p.getPrice());//同理将getPrice()所获得的值赋给第2个问号地方
        pst.setString(3, p.getInfo());
		pst.setString(4,p.getParam());

        //执行sql语句
        pst.executeUpdate();
            } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//5.关闭数据库
		
		
		DBConnection.close(conn, pst);
			
		}
        
        
        
         }


}

删除商品的方法

public int delete(int id) {
		int flag = 0;
		
		
		try {
			//调用写好的数据库驱动类
			conn=DBConnection.getConn();
			//3.数据库操纵对象
			String sql="delete from goods where id=?";
			pst= conn.prepareStatement(sql);
		
					//给参数赋值
			pst.setInt(1, id);//parameterIndex 代表第几个?
			
			//4.执行SQL
			flag = pst.executeUpdate();
		
			
		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//5.关闭数据库
		
			
			DBConnection.close(conn, pst);
		}
		
	
		return flag;
	}

根据id进行查询的方法

public Product query(int id) {
//与之前不同的是需要用到集合 将从ResultSet取到的值赋给Arraylist以便输出
  //连接数据库  
    conn=DBConnection.getConn();

//创建集合 
List<Product> list=new ArrayList<Product>();
 //3.数据库操纵对象
	String sql="select * from goods where id=?";
	pst=conn.prepareStatement(sql);
	
	pst.set(1,p.getId());
    //因为executeQery会有ResultSet的返回值
    ResultSet rs=pst.executeQuery();
    
    //将rs中的值取出给到集合里面
    while(rs.next()){
        Product p=new Product();
        p.setId(rs.getInt("id"));//将rs中获取到的id赋值给p
        p.setName(rs.getString("name"));
		p.setPrice(rs.getDouble("price"));
		p.setInfo(rs.getString("info"));
		p.setParam(rs.getString("param"));
		//添加到容器
				list.add(p);
        
    }
    //遍历输出
    for(int i=0;i<list.size();i++) {
					System.out.println(list.get(i));
				}
    } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//关闭
			DBConnection.close(conn, pst);
			
		}
		
		
		
		return null;
	}

将所有元素都查询出来

public List<Product> query() {
    //连接数据库
    ArrayList list=new ArrayList<Product>();
	conn=DBConnection.getconn();
    
    //数据库操纵对象
    
    String sql="select * from goods"
    pst=conn.prepareStatement(sql);
    
    ResultSet rs= pst.executeQuery();
    
    while(rs.next()){
       Product p new Product();
        p.setInt(rs.getInt("id"));
        p.setString(rs.getString("name"));
        p.setDouble (rs.getDouble("price"));
      	p.setInfo(rs.getString("info"));
		p.setParam(rs.getString("param"));
        list.add(p);
        
    }
    for(int i=0;i<;list.size();i++){
        System.out.println(list.get(i));
    }	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//5.关闭数据库
		
		
			DBConnection.close(conn, pst);
			
		}	} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//5.关闭数据库
		
		
			DBConnection.close(conn, pst);
			
		}
    
}

根据id对数据进行修改

	public int update(Product p) {
//连接数据库
conn=DBConnection.getconn();
//数据库操纵对象
    
        String sql="update goods set name=?,price=? where id =?"
         pst=conn.prepareStatement(sql);
        
        pst.setString(1,p.setName());
        pst.setDouble(2,p.setPrice());
        pst.setInt(3,p.getId());
        pst.executeUpdate();
        
    }
 } catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 
		return 0;
	}

}

这样几种方法就构造完成

编写test类进行测试

package com.view;

import java.util.List;
import java.util.Scanner;

import com.dao.IPoroductDAO;
import com.dao.ProductDAOmp1;
import com.po.Product;

public class Test {

	public static void main(String[] args) {
		// 循环写一个菜单的切换
		// 输入1--添加 2--删除 3--查询
		Scanner sc = new Scanner(System.in);
		IPoroductDAO pro = new ProductDAOmp1();
		while (true) {
			System.out.println("请输入你的操作:1--添加   2--删除   3--查询单个  4--查询所有 5--进行商品修改 6-退出系统");
			int k = sc.nextInt();
			if (k == 1) {
			
				System.out.println("输入name:");
				String name = sc.next();
				System.out.println("输入price:");
				double price = sc.nextDouble();
				System.out.println("输入info:");
				String info = sc.next();
				System.out.println("输入param:");
				String param = sc.next();
				Product p = new Product( name, price, info, param);
				pro.add(p);
			} else if (k == 2) {
				System.out.println("输入要删除的id:");
				int id = sc.nextInt();
				// 调用delete方法

				int flag = pro.delete(id);
				if (flag == 1) {
					System.out.println("成功删除id为"+id+"的商品");
				} else if(flag == 0){
					System.out.println("没找到此商品");
				}
			} else if (k == 3) {
				System.out.println("输入要查询的id:");
				int id = sc.nextInt();
				 pro.query(id);

				 
			}else if(k==5){
				System.out.println("请输入要修改商品的id号码");
				int a=sc.nextInt();
				System.out.println("请输入要修改的名称");
				String b=sc.next();
				System.out.println("请输入要修改的价格");
				Double c=sc.nextDouble();
				Product p  = new Product(a,b,c);
				
				pro.update(p);
			
				
			}else if(k==6) {
				System.exit(0);;
			}

		}
	}

}

先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦

  • 4
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java连接数据库可以使用JDBC(Java Database Connectivity)技术来实现增删改查操作。 首先,需要引入Java的JDBC驱动程序,例如MySQL的驱动可以通过在项目中导入相应的JAR包来完成。 接下来,需要创建数据库连接。可以使用Connection对象来表示数据库连接。使用DriverManager类的getConnection()方法来获取数据库连接,方法参数包括数据库的URL、用户名和密码等。 连接成功后,可以创建Statement或者PreparedStatement对象来执行SQL语句。 实现增加数据操作时,可以使用INSERT INTO语句,例如: String sql = "INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...)"; Statement statement = connection.createStatement(); statement.executeUpdate(sql); 实现删除数据操作时,可以使用DELETE语句,例如: String sql = "DELETE FROM table_name WHERE condition"; Statement statement = connection.createStatement(); statement.executeUpdate(sql); 实现修改数据操作时,可以使用UPDATE语句,例如: String sql = "UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition"; Statement statement = connection.createStatement(); statement.executeUpdate(sql); 实现查询数据操作时,可以使用SELECT语句,例如: String sql = "SELECT * FROM table_name"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) { // 处理查询结果 } 完成操作后,需要及时关闭数据库连接和释放资源,可以使用close()方法来完成,例如: resultSet.close(); statement.close(); connection.close(); 通过以上步骤,可以使用Java连接数据库实现数据库的增删改查功能。注意在操作数据库时需谨慎处理SQL语句,以避免SQL注入等安全问题。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值