(2)JDCB增删改(Statement)

1.通过 JDBC 向指定连接的数据库进行增删改
1). 通过Connection 的 createStatement() 方法来获取
2). 通过executeUpdate(sql) 可以执行SQL语句
3).传入的SQL可以是INSERT,UPDATE 或者 DELETE,但不能是SELECT
2. Connection , Statement 都是应用程序和数据库的连接资源,使用后一定要关闭
需要在finally 中关闭Connection 和statament 对象
3. 关闭的对象是: 先关闭后获取的 即先关闭Statement 后关闭 Connection

	public void testStatement() throws Exception
	{
		Connection conn = null;
		Statement statement = null;
		
		try {
			//这是自己写的getConnection()方法 用来直接调用连接数据库 稍后会在JDBCTools里面写到
			conn = JDBCTools.getConnection();
			String sql = null;
			
			// 这是 增加语句
//			sql = "insert into customers (name,email) "
//					+ "VALUES('123','123.com')";
			
			//这是删除语句
//			sql = "delete from customers where id = 1";
	
			//这是修改语句 
			sql = "update customers set name = 'Tom'"
					+ "where id = 2";
	
			//获取操作SQL语句的Statement对象;
			//调用Statement 对象的executeUpdate(sql)执行SQL语句进行插入
			statement = conn.createStatement();
			statement.executeUpdate(sql);
	
	
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				//5. 关闭Statement 对象.
				if(statement != null)
				{
					statement.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally
			{
				if(conn != null)
				{
					//2.关闭连接
					conn.close();
				}
				}
		}
	}

猜你喜欢

转载自blog.csdn.net/Yuz_99/article/details/84144345