数据库连接

数据库连接:

原始方式:

原始的方式:getConnection()===>connection===>statement===>**statement*(executeQuery(sql);executeUpdate(sql);)

通过statement来获取结果rs或者int。
public static void main(String[] args) {
        //把它们提出来是为了下面能关闭资源,代码的作用范围{}    
	   	Connection connection=null;
		Statement statement=null;
		ResultSet rs=null;
		try {
			//1、加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			
			//2、建立连接
			String url="jdbc:mysql://localhost:3306/javatest";
			String user="root";
			String password="root";
			//自动创建对象ctrl+1
			connection = DriverManager.getConnection(url, user, password);
			
			//3、创建对象
			statement = connection.createStatement();
			
			//4、执行sql语句
			String sql="SELECT * FROM test";
			
			
//			1、select
			rs = statement.executeQuery(sql);
			while(rs.next()) {//这里返回的是一个boolean类型的值
				//两种方式标志,一是行数从1开始,二是列名。
				System.out.println(rs.getInt(1)+rs.getString(2)+" "+rs.getString("psd"));
				
			}
            
//            2、insert、update、delect
             修改+删除+插入:statement.executeUpdate(sql);。插入的话如果有自增的的属性(id),换成null。
			 int n = statement.executeUpdate(sql);//n表示受影响的行数;
           
            
            
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
				try {
					if(rs!=null)
						rs.close();
					if(statement!=null)
						statement.close();
					if(connection!=null)
						connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			
		}
	}

进步方式:防止SQL注入

方式:getConnection()===>connection===>PreparedStatement===>
**PreparedStatement(executeQuery(sql);executeUpdate(sql);)

通过PreparedStatement来获取结果rs或者int。
public static void main(String[] args) {
        //把它们提出来是为了下面能关闭资源,代码的作用范围{}    
	   	Connection connection=null;
		PreparedStatement ps=null;
        ResultSet rs=null;

    
		try {
			//1、加载驱动
			Class.forName("com.mysql.jdbc.Driver");
			
			//2、建立连接
			String url="jdbc:mysql://localhost:3306/javatest";
			String user="root";
			String password="root";
			//自动创建对象ctrl+1
			connection = DriverManager.getConnection(url, user, password);
			
            String sq3="SELECT dothing,dotime FROM dothing WHERE carnumber=?";
            ////////////////////////////////////////////精华
			ps = connection.prepareStatement(sq3);
            /////////////////////////////////////////////
			ps.setString(1, carnumber);
			
            
//            1、select
			rs = ps.executeQuery();
			while(rs.next()) {
				dothing=dothing+rs.getString(2)+"\n"+rs.getString(1)+"\n";
			}
            
//            2、insert、update、delect
            int i=ps.executeUpdate();
            
            
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
				try {
					if(rs!=null)
						rs.close();
					if(ps!=null)
						ps.close();
					if(connection!=null)
						connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			
		}
	}

关闭类:解决后面的繁琐关闭流程

public class Utils {
	//Closeable是一个接口实现了所有的流类,Closeable 是可以关闭的数据源或目标。调用 close 方法可释放对象保存的资源(如打开文件)。 
	public static void close(Closeable...closeables) {
		for(Closeable closeable:closeables) {
			if(closeable!=null)
				try {
					closeable.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
 
}

配合数据库连接池(druid)来配置jdbc:

文件配置:

image-20230702213310988

    //1. 获取Connection
    //3. 加载配置文件
    Properties prop = new Properties();
    prop.load(new FileInputStream("jdbc-demo/src/druid.properties"));
    //4. 获取连接池对象
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    //5. 获取数据库连接 Connection
    Connection conn = dataSource.getConnection();
public void testUpdate() throws Exception {
    // 接收页面提交的参数
    
    //1. 获取Connection
    //3. 加载配置文件
    Properties prop = new Properties();
    prop.load(new FileInputStream("jdbc-demo/src/druid.properties"));
    //4. 获取连接池对象
    DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
    //5. 获取数据库连接 Connection
    Connection conn = dataSource.getConnection();
    //2. 定义SQL
    String sql = " update tb_brand\n" +
        "         set brand_name  = ?,\n" +
        "         company_name= ?,\n" +
        "         ordered     = ?,\n" +
        "         description = ?,\n" +
        "         status      = ?\n" +
        "     where id = ?";

    //3. 获取pstmt对象
    PreparedStatement pstmt = conn.prepareStatement(sql);

    //4. 设置参数
    pstmt.setString(1,brandName);
    pstmt.setString(2,companyName);
    pstmt.setInt(3,ordered);
    pstmt.setString(4,description);
    pstmt.setInt(5,status);
    pstmt.setInt(6,id);

    //5. 执行SQL
    1、select
    int count = pstmt.executeUpdate(); // 影响的行数
    
    2、insert、update、delect
    ResultSet rs = pstmt.executeQuery();
    while (rs.next()){
        //获取数据
        int id = rs.getInt("id");
        
    }
    
    
    
    //6. 处理结果
    System.out.println(count > 0);

    //7. 释放资源
    pstmt.close();
    conn.close();
}

事务java代码:

一般对于增删改

语法:

  • 开启事务

    START TRANSACTION;
    或者  
    BEGIN;
    
  • 提交事务

    commit;
    
  • 回滚事务

    rollback;
    
SELECT * FROM shiwu_test;

update shiwu_test set money=1000 where name='zwk';
update shiwu_test set money=1000 where name='zcm';

BEGIN

update shiwu_test set money=money-500 where name='zwk';

update shiwu_test set money=money+500 where name='zcm';

--ROLLBACK;//连接时try-catch,该行代码放到catch里面,MySQL如果中间语句出错了,下面的代码不会执行

--COMMIT;

优秀博客:

https://blog.csdn.net/qq_34577961/article/details/128944768

Java代码:


    @Test
    public void updateTest(){
        Connection conn = null;
        try{
            conn = ConnectUtil.getConnection();
            conn.setAutoCommit(false);////////////////////////精华
            String sql1 = "UPDATE Scores set score = score - 100 where  id = ?;";
//            System.out.println(10 / 0);//////////////////////精华
            String sql2 = "UPDATE Scores set score = score - 100 where  id = ?;";
            update(conn,sql1,1);///////////////////////////////精华,update方法在下面,弄成一个方法方便执行多行SQL语句
            update(conn,sql2,2);
            conn.commit();/////////////////////////////////精华,语句出现问题了就不会执行下去了Java异常和MySQL都是
            System.out.println("事务处理成功");
        }catch (Exception exception){
            exception.printStackTrace();
            try{
                conn.rollback();////////////////////////////精华
            }catch (Exception e){
                e.printStackTrace();
            }
        }finally {
            try {
                // 针对连接池可能使用到同个连接,因此需要重新将连接设置会自动提交,避免影响其他操作
                conn.setAutoCommit(true);/////////////////////////////////////精华
            }catch (Exception e){
                e.printStackTrace();
            }
            
            ConnectUtil.closeConnection(conn,null,null);
            System.out.println("资源关闭");
        }
    }



public int update(Connection conn, String sql, Object... args){
        PreparedStatement ps = null;
        try{
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }
            return ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ConnectUtil.closeConnection(null,ps,null);
        }
        return 0;
    }

在这里注意上面代码的优美:
    update(conn,sql1,1);
    for (int i = 0; i < args.length; i++) {  //这行代码的作用是一下设置sql语句里的??(update传入的第三个和以后的参数,这里的Object... args也很优美)
                ps.setObject(i+1,args[i]);
            }
posted @ 2023-07-08 16:13  周六6  阅读(35)  评论(0)    收藏  举报