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;}@Overridepublic String toString() {return "Product [id=" + id + ", name=" + name + ", price=" + price + ", info=" + info + ", param=" + param+ "]";}@Overridepublic 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;}@Overridepublic int hashCode() {// TODO Auto-generated method stubreturn 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 blocke.printStackTrace();}//有可能报错}//2.数据库链接public static Connection getConn() {Connection conn =null;try {conn= DriverManager.getConnection(url, user, password);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return conn;}public static void close(Connection conn,PreparedStatement pst) {try {//5.关闭数据库  conn.close();pst.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.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 blocke.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.执行SQLflag = pst.executeUpdate();} catch (SQLException e) {// TODO Auto-generated catch blocke.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赋值给pp.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 blocke.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 blocke.printStackTrace();}finally {//5.关闭数据库DBConnection.close(conn, pst);}  } catch (SQLException e) {// TODO Auto-generated catch blocke.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 blocke.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);;}}}}

java连接数据库实现基本的增删改查相关推荐

  1. java对数据库的增删改查_在java中对数据库进行增删改查

    代码区域: package com.oracle.jdbc.demo1; import java.sql.Connection; import java.sql.DriverManager; impo ...

  2. java对xml文件做增删改查------摘录

    java对xml文件做增删改查 package com.wss; import java.io.File; import java.util.ArrayList; import java.util.L ...

  3. Java Web(十) JDBC的增删改查,C3P0等连接池,dbutils框架的使用

    前面做了一个非常垃圾的小demo,真的无法直面它,菜的抠脚啊,真的菜,好好努力把.菜鸡. --WZY 一.JDBC是什么? Java Data Base Connectivity,java数据库连接, ...

  4. Java项目——模拟电话薄联系人增删改查

    该项目模拟了电话本记录联系人的业务功能,用来练习对数据库的增删改查等操作. 菜单类:Menu -- 用来封装主菜单和个选项的子菜单 Person类: Person--联系人的实体类 TelNoteRe ...

  5. Java对MySQL数据库进行增删改查的操作(一)

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

  6. ElasticSearch初体验之使用Java进行最基本的增删改查

    好久没写博文了, 最近项目中使用到了ElaticSearch相关的一些内容, 刚好自己也来做个总结. 现在自己也只能算得上入门, 总结下自己在工作中使用Java操作ES的一些小经验吧. 本文总共分为三 ...

  7. java indexof方法_【3-14】Java中集合类list的增删改查

    Hello,大家好,我是大家最亲爱的siki老师,每天都会在这里为大家带来一个Java语法中有趣的知识点,Q群175158287,欢迎同大家多多交流哈! 今天给大家带来的是Java中list类的使用, ...

  8. 双表查询java代码_多表增删改查

    [java]代码库package com.ww.service; import java.lang.reflect.Array; import java.sql.Connection; import ...

  9. java中容器里的增删改查_Java工程师的第八天——简单的增删改查的应用

    package day08; import java.util.Scanner; /** * * @author sun changxin * 习题:数组完成增删改查(CRUD) 1.字符串类型的数组 ...

  10. Java原始客户端操作Mongodb 增删改查

    Document方式操作增删改查 1.导入Pom依赖 2.java客户端代码 1.导入Pom依赖 <dependency><groupId>org.mongodb</gr ...

最新文章

  1. nginx rewrite重写与防盗链配置
  2. 找到表中某一列值相同的记录,而且只要其中一条记录的sql
  3. c++语言中如何写入文件,C++:在多线程程序中写入文件
  4. XPath element 格式
  5. (Oracle学习笔记) sql语言
  6. windows中如何设置开机自启tomcat,nginx,jdk等应用服务的解决办法
  7. airflow sql_alchemy_conn mysql_搭建AirFlow—— 一段波折后的总结
  8. net能和python结合吗_如何不用安装python就能在.NET里调用Python库
  9. 互联网日报 | 7月19日 星期一 | 美团外卖成立骑手服务部;金山办公发布“文档中台”;一汽-大众奥迪在华销量突破700万辆...
  10. 马斯克谈买比特币:当法币实际利率为负时 只有“傻子”才不放眼他处
  11. atitit prj mnrs 项目中的几种经理角色.docx
  12. WIN7的便签使用快捷键
  13. 怎样了解存在---辩证唯物主义认识论
  14. 将已购买的知乎Live课堂图片下载并导出的教程
  15. Echarts的x,y网格线样式
  16. python链家数据分析统计服_Python数据分析实战-链家北京二手房价分析
  17. .net EF 事务TransactionScope和BeginTransaction的用法
  18. ue4 培养罐液体效果
  19. Python之任意阶幻方的构造
  20. 贝叶斯网络学习总结与中科院…

热门文章

  1. OpenLayers 官网例子的中文详解 1
  2. Kafka(下):Kafka消费者API,producer拦截器(interceptor)及案例,kafka流Streams,Stream数据清洗案例,Kafka配置信息,flume对接Kafka
  3. Pycharm中文设置教程
  4. 趣味俄罗斯方块代码分享(C语言)
  5. 干扰网络信号的app_解决无线网络干扰的五种方法
  6. 如何学习离散数学和在计算机科学中应用
  7. linux windows双系统安装教程
  8. 软件设计师历年真题(链接在文末)
  9. Python多线程实例
  10. java JDK1.8中文手册