01_报错笔记(一)之数据库相关

1.连接关闭后的错误

  

  

   

        代码如下:

 1 package com.baidu.java.util;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 
 6 /**
 7  * 课程博客:https://www.cnblogs.com/newAndHui/category/1153640.html
 8  */
 9 public class JDBCUtil {
10     private static Connection connection=null;
11     static {
12         try {
13             Class.forName("com.mysql.jdbc.Driver");
14             connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/station_demo", "root", "admin");
15         } catch (Exception e) {
16             e.printStackTrace();
17         }
18     }
19     /**
20      * 获取一个连接对象
21      * @return
22      */
23     public static Connection getConnection() {
24         return connection;
25     }
26 
27 }
JDBCUtil

   dao实现类代码

 1  //1.增加   INSERT INTO proDuct (product_name,sale_price) vALUES ('苹果手机',5000)
 2     public void save2(String name,int salePrice){  // x=2     f(x)=x+2
 3         try {  //  MVC
 4             //1.加载
 5             Connection connection = JDBCUtil.getConnection();
 6             System.out.println("connection="+connection);
 7             //3.创建语句
 8             // Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库。
 9             Statement statement = connection.createStatement();
10             String sql="INSERT INTO product (product_name,sale_price) VALUES ('"+name+"',"+salePrice+")";
11             System.out.println(" sql=  "+sql);
12             statement.executeUpdate(sql);
13             //5.释放资源
14             statement.close();
15             connection.close();
16         } catch (Exception e) {
17             e.printStackTrace();
18         }
19     }
View Code

   测试代码:

1  @Test
2     public void testSave(){
3         //拿到dao对象   程序员不缺对象,差一个对象就new一个对象
4         ProductDao p =   new ProductDao();
5 
6         //调用方法
7         p.save2("苹果手机66",8066);
8         p.save2("苹果手机6699",889);
9     }
View Code

猜你喜欢

转载自www.cnblogs.com/newAndHui/p/9054979.html